Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/target-cli-notifications.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"trigger.dev": patch
---

Send the running CLI version when checking for platform notifications so notices can be limited to compatible CLI releases.
30 changes: 28 additions & 2 deletions apps/webapp/app/routes/admin.notifications.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ function parseNotificationFormData(formData: FormData) {
const cliShowEvery = formData.get("cliShowEvery")
? Number(formData.get("cliShowEvery"))
: undefined;
const minimumCliVersion =
(formData.get("minimumCliVersion") as string | null)?.trim() || undefined;
Comment thread
carderne marked this conversation as resolved.

const discoveryFilePatterns = (formData.get("discoveryFilePatterns") as string) || "";
const discoveryContentPattern = (formData.get("discoveryContentPattern") as string) || undefined;
Expand Down Expand Up @@ -177,6 +179,7 @@ function parseNotificationFormData(formData: FormData) {
cliMaxShowCount,
cliMaxDaysAfterFirstSeen,
cliShowEvery,
minimumCliVersion,
discovery,
};
}
Expand All @@ -192,6 +195,9 @@ function buildPayloadInput(fields: ReturnType<typeof parseNotificationFormData>)
...(fields.image ? { image: fields.image } : {}),
...(fields.dismissOnAction ? { dismissOnAction: true } : {}),
...(fields.discovery ? { discovery: fields.discovery } : {}),
...(fields.surface === "CLI" && fields.minimumCliVersion
? { minimumCliVersion: fields.minimumCliVersion }
: {}),
},
};
}
Expand Down Expand Up @@ -669,6 +675,7 @@ type NotificationFormDefaults = {
contentPattern?: string;
matchBehavior: "show-if-found" | "show-if-not-found";
} | null;
payloadMinimumCliVersion?: string | null;
cliMaxShowCount?: number | null;
cliMaxDaysAfterFirstSeen?: number | null;
cliShowEvery?: number | null;
Expand Down Expand Up @@ -1024,7 +1031,19 @@ function NotificationForm({
<>
<input type="hidden" name="discoveryMatchBehavior" value={discoveryMatchBehavior} />

<div className="grid grid-cols-3 gap-3 rounded border border-grid-dimmed bg-background-deep p-3">
<div className="grid grid-cols-2 gap-3 rounded border border-grid-dimmed bg-background-deep p-3">
<div>
<Label variant="small">Minimum CLI version</Label>
<Input
name="minimumCliVersion"
variant="medium"
fullWidth
defaultValue={n?.payloadMinimumCliVersion ?? ""}
placeholder="e.g. 4.5.7"
className="mt-1"
/>
<Hint>Exact SemVer, inclusive</Hint>
</div>
<div>
<Label variant="small">Max show count</Label>
<Input
Expand Down Expand Up @@ -1188,6 +1207,7 @@ function NotificationDetailContent({
payloadDescription: string | null;
payloadActionUrl: string | null | undefined;
payloadImage: string | null | undefined;
payloadMinimumCliVersion: string | null;
cliMaxShowCount: number | null;
cliMaxDaysAfterFirstSeen: number | null;
cliShowEvery: number | null;
Expand Down Expand Up @@ -1239,10 +1259,16 @@ function NotificationDetailContent({

{/* CLI settings */}
{n.surface === "CLI" &&
(n.cliMaxShowCount || n.cliMaxDaysAfterFirstSeen || n.cliShowEvery) && (
(n.payloadMinimumCliVersion ||
n.cliMaxShowCount ||
n.cliMaxDaysAfterFirstSeen ||
n.cliShowEvery) && (
<div>
<p className="mb-1 text-xs font-medium text-text-dimmed">CLI Settings</p>
<div className="grid grid-cols-2 gap-x-4 gap-y-2 text-xs">
{n.payloadMinimumCliVersion && (
<DetailRow label="Minimum CLI version" value={n.payloadMinimumCliVersion} />
)}
{n.cliMaxShowCount != null && (
<DetailRow label="Max show count" value={String(n.cliMaxShowCount)} />
)}
Expand Down
2 changes: 2 additions & 0 deletions apps/webapp/app/routes/api.v1.platform-notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ export async function loader({ request }: LoaderFunctionArgs) {

const url = new URL(request.url);
const projectRef = url.searchParams.get("projectRef") ?? undefined;
const cliVersion = request.headers.get("x-trigger-cli-version")?.trim() || undefined;

const notification = await getNextCliNotification({
userId: authenticationResult.userId,
projectRef,
cliVersion,
});

return json({ notification });
Expand Down
228 changes: 228 additions & 0 deletions apps/webapp/app/services/platformNotificationSchemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
import { z } from "zod";
import { normalizeExactSemVer } from "./platformNotificationVersionTargeting";

const DiscoverySchema = z.object({
filePatterns: z.array(z.string().min(1)).min(1),
contentPattern: z
.string()
.max(200)
.optional()
.refine(
(val) => {
if (!val) return true;
try {
new RegExp(val);
return true;
} catch {
return false;
}
},
{ message: "contentPattern must be a valid regular expression" }
),
matchBehavior: z.enum(["show-if-found", "show-if-not-found"]),
});

// Constrain URL fields to http/https; `.url()` alone accepts other schemes
// that would be unsafe to render into an `<a href>`.
const httpUrl = z
.string()
.url()
.refine(
(v) => {
try {
const proto = new URL(v).protocol;
return proto === "http:" || proto === "https:";
} catch {
return false;
}
},
{ message: "URL must use http or https" }
);

const ExactSemVerSchema = z
.string()
.transform((value) => value.trim())
.refine((value) => normalizeExactSemVer(value) !== null, {
message: "minimumCliVersion must be a complete, exact SemVer",
})
.transform((value) => normalizeExactSemVer(value)!);

const CardDataV1Schema = z.object({
type: z.enum(["card", "info", "warn", "error", "success", "changelog"]),
title: z.string(),
description: z.string(),
image: httpUrl.optional(),
actionLabel: z.string().optional(),
actionUrl: httpUrl.optional(),
dismissOnAction: z.boolean().optional(),
discovery: DiscoverySchema.optional(),
minimumCliVersion: ExactSemVerSchema.optional(),
});

export const PayloadV1Schema = z.object({
version: z.literal("1"),
data: CardDataV1Schema,
});

export type PayloadV1 = z.infer<typeof PayloadV1Schema>;

const SCOPE_REQUIRED_FK: Record<string, "userId" | "organizationId" | "projectId"> = {
USER: "userId",
ORGANIZATION: "organizationId",
PROJECT: "projectId",
};

const ALL_FK_FIELDS = ["userId", "organizationId", "projectId"] as const;
const CLI_ONLY_FIELDS = ["cliMaxDaysAfterFirstSeen", "cliMaxShowCount", "cliShowEvery"] as const;

const NotificationBaseFields = {
title: z.string().min(1),
payload: PayloadV1Schema,
surface: z.enum(["WEBAPP", "CLI"]),
scope: z.enum(["USER", "PROJECT", "ORGANIZATION", "GLOBAL"]),
userId: z.string().optional(),
organizationId: z.string().optional(),
projectId: z.string().optional(),
endsAt: z
.string()
.datetime()
.transform((s) => new Date(s)),
priority: z.number().int().default(0),
cliMaxDaysAfterFirstSeen: z.number().int().positive().optional(),
cliMaxShowCount: z.number().int().positive().optional(),
cliShowEvery: z.number().int().min(2).optional(),
};

export const CreatePlatformNotificationSchema = z
.object({
...NotificationBaseFields,
startsAt: z
.string()
.datetime()
.transform((s) => new Date(s))
.optional(),
})
.superRefine((data, ctx) => {
validateScopeForeignKeys(data, ctx);
validateSurfaceFields(data, ctx);
validatePayloadTypeForSurface(data, ctx);
validateStartsAt(data, ctx);
validateEndsAt(data, ctx);
});

function validateScopeForeignKeys(
data: { scope: string; userId?: string; organizationId?: string; projectId?: string },
ctx: z.RefinementCtx
) {
const requiredFk = SCOPE_REQUIRED_FK[data.scope];

if (requiredFk && !data[requiredFk]) {
ctx.addIssue({
code: "custom",
message: `${requiredFk} is required when scope is ${data.scope}`,
path: [requiredFk],
});
}

const forbiddenFks = ALL_FK_FIELDS.filter((fk) => fk !== requiredFk);
for (const fk of forbiddenFks) {
if (data[fk]) {
ctx.addIssue({
code: "custom",
message: `${fk} must not be set when scope is ${data.scope}`,
path: [fk],
});
}
}
}

function validateSurfaceFields(
data: {
surface: string;
payload: PayloadV1;
cliMaxDaysAfterFirstSeen?: number;
cliMaxShowCount?: number;
cliShowEvery?: number;
},
ctx: z.RefinementCtx
) {
if (data.surface !== "WEBAPP") return;

for (const field of CLI_ONLY_FIELDS) {
if (data[field] !== undefined) {
ctx.addIssue({
code: "custom",
message: `${field} is not allowed for WEBAPP surface`,
path: [field],
});
}
}

if (data.payload.data.minimumCliVersion !== undefined) {
ctx.addIssue({
code: "custom",
message: "minimumCliVersion is not allowed for WEBAPP surface",
path: ["payload", "data", "minimumCliVersion"],
});
}
}

function validateStartsAt(data: { startsAt?: Date }, ctx: z.RefinementCtx) {
if (!data.startsAt) return;

const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
if (data.startsAt < oneHourAgo) {
ctx.addIssue({
code: "custom",
message: "startsAt must be within the last hour or in the future",
path: ["startsAt"],
});
}
}

const CLI_TYPES = new Set(["info", "warn", "error", "success"]);
const WEBAPP_TYPES = new Set(["card", "changelog"]);

function validatePayloadTypeForSurface(
data: { surface: string; payload: PayloadV1 },
ctx: z.RefinementCtx
) {
const allowedTypes = data.surface === "CLI" ? CLI_TYPES : WEBAPP_TYPES;
if (!allowedTypes.has(data.payload.data.type)) {
ctx.addIssue({
code: "custom",
message: `payload.data.type "${data.payload.data.type}" is not allowed for ${data.surface} surface`,
path: ["payload", "data", "type"],
});
}
}

function validateEndsAt(data: { startsAt?: Date; endsAt: Date }, ctx: z.RefinementCtx) {
const effectiveStart = data.startsAt ?? new Date();
if (data.endsAt <= effectiveStart) {
ctx.addIssue({
code: "custom",
message: "endsAt must be after startsAt",
path: ["endsAt"],
});
}
}

export type CreatePlatformNotificationInput = z.input<typeof CreatePlatformNotificationSchema>;

export const UpdatePlatformNotificationSchema = z
.object({
...NotificationBaseFields,
id: z.string().min(1),
startsAt: z
.string()
.datetime()
.transform((s) => new Date(s)),
})
.superRefine((data, ctx) => {
validateScopeForeignKeys(data, ctx);
validateSurfaceFields(data, ctx);
validatePayloadTypeForSurface(data, ctx);
// Existing notifications may have a startsAt in the past.
validateEndsAt(data, ctx);
});
29 changes: 29 additions & 0 deletions apps/webapp/app/services/platformNotificationVersionTargeting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as semver from "semver";

export function normalizeExactSemVer(value: string): string | null {
const trimmed = value.trim();
const parsed = semver.parse(trimmed);

if (!parsed) return null;

const normalized = `${parsed.version}${
parsed.build.length > 0 ? `+${parsed.build.join(".")}` : ""
}`;

return normalized === trimmed ? normalized : null;
}

export function isCliVersionEligible(
minimumCliVersion: string | undefined,
cliVersion: string | undefined
): boolean {
if (minimumCliVersion === undefined) return true;

const normalizedMinimum = normalizeExactSemVer(minimumCliVersion);
if (!normalizedMinimum || cliVersion === undefined) return false;

const normalizedCliVersion = normalizeExactSemVer(cliVersion);
if (!normalizedCliVersion) return false;

return semver.gte(normalizedCliVersion, normalizedMinimum);
}
Loading
Loading