Skip to content

Open-source status page, incident response and uptime monitoring

chore: page-components clean up (#1790)

Maximilian Kaske4e1b9eebf1f1
diff --git a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx
index a4791a1c6..c36d2321b 100644
--- a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx
@@ -158,6 +158,11 @@ export function Client() {
value={workspace.usage?.pages ?? 0}
max={workspace.limits["status-pages"]}
/>
+ <BillingProgress
+ label="Page Components"
+ value={workspace.usage?.pageComponents ?? 0}
+ max={workspace.limits["page-components"]}
+ />
<BillingProgress
label="Notifications"
value={workspace.usage?.notifications ?? 0}
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx
index 318f05450..a510bcf52 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx
@@ -111,20 +111,20 @@ export function Sidebar() {
},
{
label: "Monitors",
- items: statusPage.monitors.flatMap((monitor) => {
+ items: statusPage.pageComponents.flatMap((component) => {
const arr = [];
arr.push({
label: "Name",
value: (
<TableCellLink
- href={`/monitors/${monitor.id}/overview`}
- value={monitor.name}
+ href={`/status-pages/${statusPage.id}/components`}
+ value={component.name}
/>
),
});
arr.push({
- label: "URL",
- value: monitor.url,
+ label: "Type",
+ value: component.type,
isNested: true,
});
return arr;
diff --git a/apps/dashboard/src/components/forms/components/form-components.tsx b/apps/dashboard/src/components/forms/components/form-components.tsx
index ec0b2f972..2d72d1ffd 100644
--- a/apps/dashboard/src/components/forms/components/form-components.tsx
+++ b/apps/dashboard/src/components/forms/components/form-components.tsx
@@ -5,6 +5,7 @@ import {
EmptyStateContainer,
EmptyStateTitle,
} from "@/components/content/empty-state";
+import { UpgradeDialog } from "@/components/dialogs/upgrade";
import {
FormCard,
FormCardContent,
@@ -80,6 +81,7 @@ import {
GripVertical,
Link2,
Link2Off,
+ Plug,
Plus,
Trash2,
} from "lucide-react";
@@ -90,6 +92,7 @@ import { z } from "zod";
type PageComponent = RouterOutputs["pageComponent"]["list"][number];
type Monitor = RouterOutputs["monitor"]["list"][number];
+type Workspace = RouterOutputs["workspace"]["get"];
type ComponentGroup = {
id: number;
@@ -103,7 +106,7 @@ const componentSchema = z.object({
order: z.number(),
name: z.string().min(1, { message: "Name is required" }),
description: z.string().optional(),
- type: z.enum(["monitor", "external"]),
+ type: z.enum(["monitor", "static"]),
});
const schema = z.object({
@@ -126,7 +129,7 @@ const getSortedComponents = (
id: number;
order: number;
name?: string;
- type?: "monitor" | "external";
+ type?: "monitor" | "static";
monitorId?: number | null;
}[],
monitors: Monitor[],
@@ -149,7 +152,7 @@ const getSortedComponents = (
componentMap.set(c.id, {
id: c.id,
name: c.name ?? "",
- type: c.type ?? "external",
+ type: c.type ?? "static",
monitorId: c.monitorId ?? null,
monitor: monitor ?? null,
groupId: null,
@@ -174,7 +177,7 @@ const getSortedItems = (
id: number;
order: number;
name?: string;
- type?: "monitor" | "external";
+ type?: "monitor" | "static";
monitorId?: number | null;
}[],
groups: Array<{
@@ -185,7 +188,7 @@ const getSortedItems = (
id: number;
order: number;
name?: string;
- type?: "monitor" | "external";
+ type?: "monitor" | "static";
monitorId?: number | null;
}>;
}>,
@@ -210,7 +213,7 @@ const getSortedItems = (
componentMap.set(c.id, {
id: c.id,
name: c.name ?? "",
- type: c.type ?? "external",
+ type: c.type ?? "static",
monitorId: c.monitorId ?? null,
monitor: monitor ?? null,
groupId: null,
@@ -259,7 +262,7 @@ export function FormComponents({
pageComponents,
allPageComponents,
monitors,
- legacy,
+ workspace,
...props
}: Omit<React.ComponentProps<"form">, "onSubmit"> & {
defaultValues?: FormValues;
@@ -270,9 +273,9 @@ export function FormComponents({
/** Monitors available for selection */
monitors: Monitor[];
/**
- * Whether the status page is legacy or new
+ * The workspace the page belongs to
*/
- legacy: boolean;
+ workspace: Workspace;
onSubmit: (values: FormValues) => Promise<void>;
}) {
const form = useForm<FormValues>({
@@ -282,6 +285,7 @@ export function FormComponents({
const [isPending, startTransition] = useTransition();
const watchComponents = form.watch("components");
const watchGroups = form.watch("groups");
+ const [openUpgradeDialog, setOpenUpgradeDialog] = useState(false);
const [data, setData] = useState<(PageComponent | ComponentGroup)[]>(
getSortedItems(
allPageComponents,
@@ -312,6 +316,15 @@ export function FormComponents({
setData(sortedItems);
}, [watchComponents, watchGroups, allPageComponents, monitors]);
+ const validateLimit = useCallback(() => {
+ const limitReached = workspace.limits["page-components"] <= data.length;
+ if (limitReached) {
+ setOpenUpgradeDialog(true);
+ return false;
+ }
+ return true;
+ }, [workspace, data.length]);
+
const onValueChange = useCallback(
(newItems: (PageComponent | ComponentGroup)[]) => {
setData(newItems);
@@ -372,6 +385,8 @@ export function FormComponents({
);
const handleAddGroup = useCallback(() => {
+ if (!validateLimit()) return;
+
const newGroupId = Date.now();
const existingGroups = form.getValues("groups") ?? [];
const existingComponents = form.getValues("components") ?? [];
@@ -382,7 +397,7 @@ export function FormComponents({
];
form.setValue("groups", newGroups);
setData((prev) => [...prev, { id: newGroupId, name: "", components: [] }]);
- }, [form]);
+ }, [form, validateLimit]);
const handleDeleteGroup = useCallback(
(groupId: number) => {
@@ -437,6 +452,7 @@ export function FormComponents({
form={form}
allPageComponents={allPageComponents}
monitors={monitors}
+ validateLimit={validateLimit}
/>
);
},
@@ -447,6 +463,7 @@ export function FormComponents({
allPageComponents,
monitors,
handleDeleteComponent,
+ validateLimit,
],
);
@@ -474,209 +491,216 @@ export function FormComponents({
}
return (
- <Form {...form}>
- <form onSubmit={form.handleSubmit(submitAction)} {...props}>
- <FormCard>
- <FormCardHeader>
- <FormCardTitle>Components</FormCardTitle>
- <FormCardDescription>
- Manage your page components
- </FormCardDescription>
- </FormCardHeader>
- <FormCardContent className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-4">
- <FormField
- control={form.control}
- name="components"
- render={({ field }) => (
- <FormItem className="flex flex-col">
- <FormLabel className="sr-only">Components</FormLabel>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="outline" className="w-full">
- <Plus />
- Add Component
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- className="w-[var(--radix-dropdown-menu-trigger-width)]"
- >
- <DropdownMenuGroup>
- <DropdownMenuItem
- disabled
- onClick={() => {
- form.setValue("components", [
- ...field.value,
- {
- id: Date.now(),
- monitorId: null,
- order: watchComponents.length,
- name: "",
- description: "",
- type: "external" as const,
- },
- ]);
- }}
- >
- <Link2Off className="text-muted-foreground" />
- Add External (soon)
- </DropdownMenuItem>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger className="gap-2 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0">
- <Link2 className="text-muted-foreground" />
- Add Monitor
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="p-0">
- <Command>
- <CommandInput
- placeholder="Search monitors..."
- className="h-9"
- />
- <CommandList>
- <CommandEmpty>No monitors found.</CommandEmpty>
- <CommandGroup>
- {monitors.map((monitor) => {
- const isUsed = usedMonitorIds.has(
- monitor.id,
- );
- const isSelected = field.value.some(
- (c) => c.monitorId === monitor.id,
- );
- return (
- <CommandItem
- value={monitor.name}
- key={monitor.id}
- disabled={isUsed}
- onSelect={() => {
- if (isSelected) {
- form.setValue(
- "components",
- field.value.filter(
- (c) =>
- c.monitorId !== monitor.id,
- ),
- );
- } else {
- form.setValue("components", [
- ...field.value,
- {
- id: Date.now(),
- monitorId: monitor.id,
- order: watchComponents.length,
- name: monitor.name,
- description:
- monitor.description,
- type: "monitor" as const,
- },
- ]);
- }
- }}
- >
- {monitor.name}
- <Check
- className={cn(
- "ml-auto",
- isSelected
- ? "opacity-100"
- : "opacity-0",
- )}
- />
- </CommandItem>
- );
- })}
- </CommandGroup>
- </CommandList>
- </Command>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- <FormMessage />
- </FormItem>
- )}
- />
- <Button
- variant="outline"
- type="button"
- className="w-full"
- onClick={handleAddGroup}
- >
- <Plus />
- Add Component Group
- </Button>
- </FormCardContent>
- <FormCardSeparator />
- <FormCardContent>
- <Sortable
- value={data}
- onValueChange={onValueChange}
- getItemValue={getItemValue}
- orientation="vertical"
- >
- {data.length ? (
- <SortableContent className="grid gap-2">
- {data.map((item) => {
- if ("type" in item) {
- const components = form.getValues("components") ?? [];
- const componentIndex = components.findIndex(
- (c) => c.id === item.id,
+ <>
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(submitAction)} {...props}>
+ <FormCard>
+ <FormCardHeader>
+ <FormCardTitle>Components</FormCardTitle>
+ <FormCardDescription>
+ Manage your page components
+ </FormCardDescription>
+ </FormCardHeader>
+ <FormCardContent className="flex flex-row gap-2">
+ <Button variant="outline" type="button" onClick={handleAddGroup}>
+ <Plus />
+ Add Component Group
+ </Button>
+ <FormField
+ control={form.control}
+ name="components"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel className="sr-only">Components</FormLabel>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" className="w-full">
+ <Plus />
+ Add Component
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuGroup>
+ <DropdownMenuItem
+ onClick={() => {
+ if (!validateLimit()) return;
+ form.setValue("components", [
+ ...field.value,
+ {
+ id: Date.now(),
+ monitorId: null,
+ order: watchComponents.length,
+ name: "",
+ description: "",
+ type: "static" as const,
+ },
+ ]);
+ }}
+ >
+ <Link2Off className="text-muted-foreground" />
+ Add Static Component
+ </DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger className="gap-2 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0">
+ <Link2 className="text-muted-foreground" />
+ Add Monitor Component
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="p-0">
+ <Command>
+ <CommandInput
+ placeholder="Search monitors..."
+ className="h-9"
+ />
+ <CommandList>
+ <CommandEmpty>
+ No monitors found.
+ </CommandEmpty>
+ <CommandGroup>
+ {monitors.map((monitor) => {
+ const isUsed = usedMonitorIds.has(
+ monitor.id,
+ );
+ const isSelected = field.value.some(
+ (c) => c.monitorId === monitor.id,
+ );
+ return (
+ <CommandItem
+ value={monitor.name}
+ key={monitor.id}
+ disabled={isUsed}
+ onSelect={() => {
+ if (isSelected) {
+ form.setValue(
+ "components",
+ field.value.filter(
+ (c) =>
+ c.monitorId !== monitor.id,
+ ),
+ );
+ } else {
+ if (!validateLimit()) return;
+ form.setValue("components", [
+ ...field.value,
+ {
+ id: Date.now(),
+ monitorId: monitor.id,
+ order: watchComponents.length,
+ name: monitor.name,
+ description:
+ monitor.description,
+ type: "monitor" as const,
+ },
+ ]);
+ }
+ }}
+ >
+ {monitor.name}
+ <Check
+ className={cn(
+ "ml-auto",
+ isSelected
+ ? "opacity-100"
+ : "opacity-0",
+ )}
+ />
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuItem disabled>
+ <Plug className="text-muted-foreground" />
+ Add Third-Party Component
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </FormCardContent>
+ <FormCardSeparator />
+ <FormCardContent>
+ <Sortable
+ value={data}
+ onValueChange={onValueChange}
+ getItemValue={getItemValue}
+ orientation="vertical"
+ >
+ {data.length ? (
+ <SortableContent className="grid gap-2">
+ {data.map((item) => {
+ if ("type" in item) {
+ const components = form.getValues("components") ?? [];
+ const componentIndex = components.findIndex(
+ (c) => c.id === item.id,
+ );
+ return (
+ <ComponentRow
+ key={`${item.id}-component`}
+ className="border-transparent border-x px-2"
+ component={item}
+ form={form}
+ onDelete={handleDeleteComponent}
+ fieldNamePrefix={
+ componentIndex >= 0
+ ? `components.${componentIndex}`
+ : undefined
+ }
+ />
+ );
+ }
+ const groups = form.getValues("groups") ?? [];
+ const groupIndex = groups.findIndex(
+ (g) => g.id === item.id,
);
return (
- <ComponentRow
- key={`${item.id}-component`}
- className="border-transparent border-x px-2"
- component={item}
+ <ComponentGroupRow
+ key={`${item.id}-group`}
+ group={item}
+ groupIndex={groupIndex}
+ onDeleteGroup={handleDeleteGroup}
form={form}
- onDelete={handleDeleteComponent}
- fieldNamePrefix={
- componentIndex >= 0
- ? `components.${componentIndex}`
- : undefined
- }
+ allPageComponents={allPageComponents}
+ monitors={monitors}
+ validateLimit={validateLimit}
/>
);
- }
- const groups = form.getValues("groups") ?? [];
- const groupIndex = groups.findIndex(
- (g) => g.id === item.id,
- );
- return (
- <ComponentGroupRow
- key={`${item.id}-group`}
- group={item}
- groupIndex={groupIndex}
- onDeleteGroup={handleDeleteGroup}
- form={form}
- allPageComponents={allPageComponents}
- monitors={monitors}
- />
- );
- })}
- <SortableOverlay>{renderOverlay}</SortableOverlay>
- </SortableContent>
- ) : (
- <EmptyStateContainer>
- <EmptyStateTitle>No components selected</EmptyStateTitle>
- </EmptyStateContainer>
- )}
- </Sortable>
- </FormCardContent>
- <FormCardFooter>
- <FormCardFooterInfo>
- Learn more about{" "}
- <Link href="https://docs.openstatus.dev/reference/status-page/#page-components">
- page components
- </Link>
- .
- </FormCardFooterInfo>
- <Button type="submit" disabled={isPending}>
- {isPending ? "Submitting..." : "Submit"}
- </Button>
- </FormCardFooter>
- </FormCard>
- </form>
- </Form>
+ })}
+ <SortableOverlay>{renderOverlay}</SortableOverlay>
+ </SortableContent>
+ ) : (
+ <EmptyStateContainer>
+ <EmptyStateTitle>No components selected</EmptyStateTitle>
+ </EmptyStateContainer>
+ )}
+ </Sortable>
+ </FormCardContent>
+ <FormCardFooter>
+ <FormCardFooterInfo>
+ Learn more about{" "}
+ <Link href="https://docs.openstatus.dev/reference/status-page/#page-components">
+ page components
+ </Link>
+ .
+ </FormCardFooterInfo>
+ <Button type="submit" disabled={isPending}>
+ {isPending ? "Submitting..." : "Submit"}
+ </Button>
+ </FormCardFooter>
+ </FormCard>
+ </form>
+ </Form>
+ <UpgradeDialog
+ limit="page-components"
+ open={openUpgradeDialog}
+ onOpenChange={setOpenUpgradeDialog}
+ />
+ </>
);
}
@@ -773,7 +797,7 @@ function ComponentRow({
<Link
href={`/monitors/${component.monitorId}/overview`}
onClick={(e) => e.stopPropagation()}
- className="flex w-full items-center gap-2 truncate text-sm"
+ className="flex w-full items-center gap-2 truncate py-1.5 text-sm"
>
<Link2 className="size-4 shrink-0" />{" "}
<span className="truncate">{component.monitor.name}</span>
@@ -781,7 +805,7 @@ function ComponentRow({
) : (
<span className="flex items-center gap-2 text-muted-foreground text-sm">
<Link2Off className="size-4 shrink-0" />{" "}
- <span className="truncate">External Component</span>
+ <span className="truncate">Static Component</span>
</span>
)}
</div>
@@ -836,8 +860,13 @@ function ComponentRow({
<AlertDialogHeader>
<AlertDialogTitle>Are you sure?</AlertDialogTitle>
<AlertDialogDescription>
- You are about to delete this component.
+ Once saved, this will unlink the component from attached
+ status reports and maintenances.
</AlertDialogDescription>
+ <ComponentAttachments
+ statusReports={component.statusReports ?? []}
+ maintenances={component.maintenances ?? []}
+ />
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
@@ -845,7 +874,7 @@ function ComponentRow({
className="bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40"
onClick={() => onDelete(component.id)}
>
- Delete
+ Remove
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -864,6 +893,7 @@ interface ComponentGroupRowProps
form: UseFormReturn<FormValues>;
allPageComponents: PageComponent[];
monitors: Monitor[];
+ validateLimit: () => boolean;
}
function ComponentGroupRow({
@@ -873,6 +903,7 @@ function ComponentGroupRow({
form,
allPageComponents,
monitors,
+ validateLimit,
}: ComponentGroupRowProps) {
const watchGroup = form.watch(`groups.${groupIndex}`);
const watchComponents = form.watch("components");
@@ -997,14 +1028,11 @@ function ComponentGroupRow({
Add Component
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- className="w-[var(--radix-dropdown-menu-trigger-width)]"
- >
+ <DropdownMenuContent align="start">
<DropdownMenuGroup>
<DropdownMenuItem
- disabled
onClick={() => {
+ if (!validateLimit()) return;
const current = field.value ?? [];
form.setValue(`groups.${groupIndex}.components`, [
...current,
@@ -1014,18 +1042,18 @@ function ComponentGroupRow({
order: current.length,
name: "",
description: "",
- type: "external" as const,
+ type: "static" as const,
},
]);
}}
>
<Link2Off className="text-muted-foreground" />
- Add External (soon)
+ Add Static Component
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger className="gap-2 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0">
<Link2 className="text-muted-foreground" />
- Add Monitor
+ Add Monitor Component
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="p-0">
<Command>
@@ -1046,7 +1074,7 @@ function ComponentGroupRow({
<CommandItem
value={monitor.name}
key={monitor.id}
- disabled={isTaken}
+ disabled={isTaken || isSelected}
onSelect={() => {
if (isSelected) {
form.setValue(
@@ -1056,6 +1084,7 @@ function ComponentGroupRow({
),
);
} else {
+ if (!validateLimit()) return;
form.setValue(
`groups.${groupIndex}.components`,
[
@@ -1090,6 +1119,10 @@ function ComponentGroupRow({
</Command>
</DropdownMenuSubContent>
</DropdownMenuSub>
+ <DropdownMenuItem disabled>
+ <Plug className="text-muted-foreground" />
+ Add Third-Party Component
+ </DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
@@ -1118,8 +1151,25 @@ function ComponentGroupRow({
<AlertDialogHeader>
<AlertDialogTitle>Are you sure?</AlertDialogTitle>
<AlertDialogDescription>
- You are about to delete this group and all its components.
+ Once saved, this will delete all components in the group and
+ unlink them from attached status reports and maintenances.
</AlertDialogDescription>
+ <ComponentAttachments
+ statusReports={Array.from(
+ new Map(
+ group.components
+ .flatMap((c) => c.statusReports ?? [])
+ .map((sr) => [sr.id, sr]),
+ ).values(),
+ )}
+ maintenances={Array.from(
+ new Map(
+ group.components
+ .flatMap((c) => c.maintenances ?? [])
+ .map((m) => [m.id, m]),
+ ).values(),
+ )}
+ />
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
@@ -1127,7 +1177,7 @@ function ComponentGroupRow({
className="bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40"
onClick={() => onDeleteGroup(group.id)}
>
- Delete
+ Remove
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -1175,3 +1225,46 @@ function ComponentGroupRow({
</SortableItem>
);
}
+
+function ComponentAttachments({
+ statusReports,
+ maintenances,
+}: {
+ statusReports: Array<{ id: number; title: string }>;
+ maintenances: Array<{ id: number; title: string }>;
+}) {
+ if (statusReports.length === 0 && maintenances.length === 0) {
+ return null;
+ }
+
+ const allItems = [
+ ...statusReports.map((report) => ({
+ id: `report-${report.id}`,
+ title: report.title,
+ type: "report" as const,
+ })),
+ ...maintenances.map((maintenance) => ({
+ id: `maintenance-${maintenance.id}`,
+ title: maintenance.title,
+ type: "maintenance" as const,
+ })),
+ ];
+
+ const displayLimit = 3;
+ const displayedItems = allItems.slice(0, displayLimit);
+ const remainingCount = allItems.length - displayLimit;
+
+ return (
+ <ul className="list-inside list-disc space-y-1 text-foreground text-sm">
+ {displayedItems.map((item) => (
+ <li key={item.id}>
+ {item.title}{" "}
+ <span className="text-muted-foreground">({item.type})</span>
+ </li>
+ ))}
+ {remainingCount > 0 && (
+ <li className="text-muted-foreground">+ {remainingCount} more</li>
+ )}
+ </ul>
+ );
+}
diff --git a/apps/dashboard/src/components/forms/components/update.tsx b/apps/dashboard/src/components/forms/components/update.tsx
index 72cf6f41b..30de31345 100644
--- a/apps/dashboard/src/components/forms/components/update.tsx
+++ b/apps/dashboard/src/components/forms/components/update.tsx
@@ -5,6 +5,7 @@ import { useTRPC } from "@/lib/trpc/client";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useParams } from "next/navigation";
import { FormCardGroup } from "../form-card";
+import { FormConfiguration } from "../status-page/form-configuration";
export function FormComponentsUpdate() {
const { id } = useParams<{ id: string }>();
@@ -16,6 +17,7 @@ export function FormComponentsUpdate() {
trpc.pageComponent.list.queryOptions({ pageId: Number.parseInt(id) }),
);
const { data: monitors } = useQuery(trpc.monitor.list.queryOptions());
+ const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());
const updateComponentsMutation = useMutation(
trpc.pageComponent.updateOrder.mutationOptions({
@@ -26,7 +28,13 @@ export function FormComponentsUpdate() {
}),
);
- if (!statusPage || !pageComponents || !monitors) return null;
+ const updatePageConfigurationMutation = useMutation(
+ trpc.page.updatePageConfiguration.mutationOptions({
+ onSuccess: () => refetch(),
+ }),
+ );
+
+ if (!statusPage || !pageComponents || !monitors || !workspace) return null;
// Separate standalone components from grouped components
const standaloneComponents = pageComponents.filter((c) => !c.groupId);
@@ -67,6 +75,10 @@ export function FormComponentsUpdate() {
groups,
};
+ const configLink = `https://${
+ statusPage.slug
+ }.stpg.dev?configuration-token=${statusPage.createdAt?.getTime().toString()}`;
+
return (
<FormCardGroup>
<FormComponents
@@ -74,7 +86,7 @@ export function FormComponentsUpdate() {
monitors={monitors}
allPageComponents={pageComponents}
defaultValues={defaultValues}
- legacy={statusPage.legacyPage}
+ workspace={workspace}
onSubmit={async (values) => {
await updateComponentsMutation.mutateAsync({
pageId: Number.parseInt(id),
@@ -86,6 +98,26 @@ export function FormComponentsUpdate() {
});
}}
/>
+ <FormConfiguration
+ defaultValues={{
+ configuration: statusPage.configuration ?? {},
+ }}
+ onSubmit={async (values) => {
+ await updatePageConfigurationMutation.mutateAsync({
+ id: Number.parseInt(id),
+ configuration: {
+ uptime:
+ typeof values.configuration.uptime === "boolean"
+ ? values.configuration.uptime
+ : values.configuration.uptime === "true",
+ value: values.configuration.value ?? "duration",
+ type: values.configuration.type ?? "absolute",
+ theme: values.configuration.theme ?? undefined,
+ },
+ });
+ }}
+ configLink={configLink}
+ />
</FormCardGroup>
);
}
diff --git a/apps/dashboard/src/components/forms/status-page/form-configuration.tsx b/apps/dashboard/src/components/forms/status-page/form-configuration.tsx
index b118f9a40..fc00915c9 100644
--- a/apps/dashboard/src/components/forms/status-page/form-configuration.tsx
+++ b/apps/dashboard/src/components/forms/status-page/form-configuration.tsx
@@ -139,11 +139,11 @@ export function FormConfiguration({
<>
<Form {...form}>
<form id="redesign" onSubmit={form.handleSubmit(submitAction)}>
- <FormCard variant="info">
+ <FormCard>
<FormCardHeader>
- <FormCardTitle>Tracker Configuration</FormCardTitle>
+ <FormCardTitle>Components Configuration</FormCardTitle>
<FormCardDescription>
- Configure which data should be shown in the monitor tracker.
+ Configure which data should be shown for your components.
</FormCardDescription>
</FormCardHeader>
<FormCardSeparator />
@@ -153,7 +153,7 @@ export function FormConfiguration({
name="configuration.type"
render={({ field }) => (
<FormItem>
- <FormLabel>Bar Type</FormLabel>
+ <FormLabel>Bar Type*</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={String(field.value) ?? "absolute"}
@@ -184,7 +184,7 @@ export function FormConfiguration({
name="configuration.value"
render={({ field }) => (
<FormItem>
- <FormLabel>Card Value</FormLabel>
+ <FormLabel>Card Value*</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={String(field.value) ?? "duration"}
@@ -242,41 +242,40 @@ export function FormConfiguration({
</FormItem>
)}
/>
+ <p className="col-span-full text-foreground/70 text-sm">
+ *Configuration settings only apply to monitor components.
+ </p>
<Note className="col-span-full">
<ul className="list-inside list-disc">
<li>
+ <span>Bar Type </span>
<span className="font-medium">
- Bar Type{" "}
- <span className="font-semibold">
- {watchConfigurationType}
- </span>
+ {watchConfigurationType}
</span>
- : {message.type[watchConfigurationType]}
+ : <span>{message.type[watchConfigurationType]}</span>
</li>
<li>
+ <span>Card Value </span>
<span className="font-medium">
- Card Value{" "}
- <span className="font-semibold">
- {watchConfigurationValue}
- </span>
+ {watchConfigurationValue}
</span>
:{" "}
- {message.value[watchConfigurationValue] ??
- message.value.default}
+ <span>
+ {message.value[watchConfigurationValue] ??
+ message.value.default}
+ </span>
</li>
<li>
- <span className="font-medium">
- Show Uptime{" "}
- <span className="font-semibold">
- {watchConfigurationUptime}
- </span>
+ <span>Show Uptime </span>
+ <span className="font-medium capitalize">
+ {String(watchConfigurationUptime)}
</span>
- : {message.uptime[watchConfigurationUptime]}
+ : <span>{message.uptime[watchConfigurationUptime]}</span>
</li>
</ul>
</Note>
</FormCardContent>
- <FormCardFooter variant="info">
+ <FormCardFooter>
<FormCardFooterInfo>
Learn more about{" "}
<Link
diff --git a/apps/dashboard/src/components/forms/status-page/update.tsx b/apps/dashboard/src/components/forms/status-page/update.tsx
index 680d1d7ad..85314284a 100644
--- a/apps/dashboard/src/components/forms/status-page/update.tsx
+++ b/apps/dashboard/src/components/forms/status-page/update.tsx
@@ -6,7 +6,6 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Info } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { FormAppearance } from "./form-appearance";
-import { FormConfiguration } from "./form-configuration";
import { FormCustomDomain } from "./form-custom-domain";
import { FormDangerZone } from "./form-danger-zone";
import { FormGeneral } from "./form-general";
@@ -69,12 +68,6 @@ export function FormStatusPageUpdate() {
}),
);
- const updatePageConfigurationMutation = useMutation(
- trpc.page.updatePageConfiguration.mutationOptions({
- onSuccess: () => refetch(),
- }),
- );
-
const updateLinksMutation = useMutation(
trpc.page.updateLinks.mutationOptions({
onSuccess: () => refetch(),
@@ -83,10 +76,6 @@ export function FormStatusPageUpdate() {
if (!statusPage || !monitors || !workspace) return null;
- const configLink = `https://${
- statusPage.slug
- }.stpg.dev?configuration-token=${statusPage.createdAt?.getTime().toString()}`;
-
return (
<FormCardGroup>
<Note color="warning">
@@ -154,26 +143,6 @@ export function FormStatusPageUpdate() {
});
}}
/>
- <FormConfiguration
- defaultValues={{
- configuration: statusPage.configuration ?? {},
- }}
- onSubmit={async (values) => {
- await updatePageConfigurationMutation.mutateAsync({
- id: Number.parseInt(id),
- configuration: {
- uptime:
- typeof values.configuration.uptime === "boolean"
- ? values.configuration.uptime
- : values.configuration.uptime === "true",
- value: values.configuration.value ?? "duration",
- type: values.configuration.type ?? "absolute",
- theme: values.configuration.theme ?? undefined,
- },
- });
- }}
- configLink={configLink}
- />
<FormPageAccess
lockedMap={
new Map([
diff --git a/apps/docs/astro.config.mjs b/apps/docs/astro.config.mjs
index 40ac2ff9a..9f32b0f7d 100644
--- a/apps/docs/astro.config.mjs
+++ b/apps/docs/astro.config.mjs
@@ -191,6 +191,10 @@ export default defineConfig({
label: "Status Page",
slug: "reference/status-page",
},
+ {
+ label: "Page Components",
+ slug: "reference/page-components",
+ },
{
label: "Status Report",
slug: "reference/status-report",
diff --git a/apps/docs/src/content/docs/reference/page-components.mdx b/apps/docs/src/content/docs/reference/page-components.mdx
new file mode 100644
index 000000000..2a9628292
--- /dev/null
+++ b/apps/docs/src/content/docs/reference/page-components.mdx
@@ -0,0 +1,304 @@
+---
+title: Page Components Reference
+description: Complete specification for OpenStatus page components on status pages.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+## Overview
+
+Page components are the individual elements displayed on your status page that show the operational status of your services. They provide a flexible way to organize and present both monitored services and static content on your status page.
+
+**Key features:**
+- Support for both monitor-linked and static components.
+- Organize components into logical groups.
+- Custom ordering and arrangement.
+- Individual status tracking with incidents, reports, and maintenances.
+- Granular control over what appears on your status page.
+
+## Component Types
+
+Page components come in two distinct types, each serving different purposes on your status page.
+
+### Monitor Components
+
+**Type:** `monitor`
+
+Monitor components are linked to an active monitor in your workspace. They automatically inherit the monitor's status and display real-time health information.
+
+**Characteristics:**
+- Display live monitor status (up, degraded, down).
+- Show active incidents from the linked monitor.
+- Include historical uptime data.
+- Reflect the monitor's current operational state.
+- Automatically update when the monitor changes.
+
+**Use cases:**
+- Displaying API endpoint health.
+- Showing website availability.
+- Tracking critical service dependencies.
+- Monitoring infrastructure components.
+
+#### Configuring Monitor Components
+
+When you create a monitor component, you link it to an existing monitor in your workspace. This connection provides several benefits:
+
+**Automatic incident tracking:**
+When your monitor detects a failure (connection timeout, HTTP error, assertion failure), an incident is automatically created and displayed on the status page. The component will show an **error** status until the monitor recovers.
+
+**Real-time status updates:**
+The component reflects the current operational state of your monitor. If the monitor is actively checking and healthy, your visitors see a **success** status. If checks fail, they immediately see the issue.
+
+**Historical data visualization:**
+Monitor components display historical uptime data through status trackers. Depending on your [tracker configuration](/tutorial/how-to-configure-status-page#1-tracker-configuration), you can show:
+- **Absolute bar with duration card**: Shows the time spent in each status (success, error, degraded, maintenance).
+- **Absolute bar with request card**: Shows the number of successful vs. failed requests.
+- **Manual bar**: Shows only the most significant status of each day.
+
+**Uptime calculations:**
+Monitor components calculate uptime percentages based on:
+- Duration of successful vs. failed checks (for duration-based tracking).
+- Number of successful vs. failed requests (for request-based tracking).
+- Includes incidents and status reports in the calculation.
+
+**Monitor selection:**
+When adding a monitor component, the dashboard shows you available monitors with indicators for:
+- **Public/Private status**: Whether the monitor is already public.
+- **Active status**: Only active monitors can be linked.
+- **Already linked**: Monitors already used on this status page are unavailable.
+
+<Aside type="tip">
+You can customize the component name to be different from the monitor name. For example, your monitor might be named "prod-api-health-check" internally, but the component can display as "API Server" for your visitors.
+</Aside>
+
+**Status hierarchy:**
+1. **Error** - Active incidents from the linked monitor.
+2. **Degraded** - Unresolved status reports affecting this component.
+3. **Info** - Ongoing scheduled maintenance.
+4. **Success** - Healthy and operational.
+
+**What affects monitor components:**
+- ✅ Automatic incidents (from monitor failures)
+- ✅ Manual status reports
+- ✅ Scheduled maintenances
+
+### Static Components
+
+**Type:** `static`
+
+Static components are independent elements not linked to any monitor. They allow you to display services or systems that you manually manage through status reports and maintenance windows only.
+
+**Characteristics:**
+- No automatic status updates.
+- Status controlled exclusively by manual status reports and scheduled maintenances.
+- Useful for third-party services or manual tracking.
+- Do not display incidents (no automatic incident creation).
+- Provide flexibility for non-monitored services.
+
+**Use cases:**
+- Third-party service dependencies (e.g., payment providers like Stripe, email services like SendGrid).
+- Manual status tracking for systems without monitors.
+- Services monitored through external tools.
+- Components that only need maintenance window communication.
+- Legacy systems without API endpoints to monitor.
+
+<Aside type="caution">
+Static components **only** respond to manual status reports and scheduled maintenances. They never automatically detect issues or create incidents. If you need automatic failure detection, use a monitor component instead.
+</Aside>
+
+#### Managing Static Components
+
+Static components give you full manual control over what your visitors see:
+
+**Status reports:**
+Create status reports to indicate issues or degraded performance for static components. For example:
+- "Stripe payment processing experiencing delays" (degraded status).
+- "Email delivery service partially unavailable" (degraded status).
+
+Once you resolve the issue and mark the status report as resolved, the component returns to a success status.
+
+**Maintenance windows:**
+Schedule maintenance windows to inform visitors about planned downtime:
+- "Scheduled database backup - Sunday 2:00 AM - 4:00 AM" (info status).
+- "Third-party CDN maintenance window" (info status).
+
+During the maintenance window, the component shows an info status. After the window ends, it returns to its previous status.
+
+**No automatic monitoring:**
+Static components do not perform any health checks or generate incidents. You are responsible for:
+- Monitoring the service through other means.
+- Creating status reports when issues occur.
+- Updating reports when issues are resolved.
+- Communicating maintenance windows in advance.
+
+**Status hierarchy:**
+1. **Degraded** - Unresolved status reports affecting this component.
+2. **Info** - Ongoing scheduled maintenance.
+3. **Success** - No active reports or maintenances.
+
+**What affects static components:**
+- ✅ Manual status reports
+- ✅ Scheduled maintenances
+- ❌ Automatic incidents (not supported)
+
+## Component Groups
+
+Component groups allow you to organize related page components into logical sections on your status page. Groups improve readability and help visitors understand your service architecture.
+
+**Benefits:**
+- Visual organization of related services.
+- Collapsible sections for better page structure.
+- Independent ordering within groups.
+- Clear service categorization.
+
+**Examples of grouping strategies:**
+
+| Group Name | Components |
+|------------|------------|
+| **API Services** | Authentication API, Data API, WebSocket API |
+| **Infrastructure** | Database, Cache, Message Queue |
+| **External Dependencies** | Payment Provider, Email Service, CDN |
+| **Regional Services** | US Region, EU Region, APAC Region |
+
+**Group configuration:**
+- **Name:** The group heading displayed on your status page.
+- **Order:** Position of the group relative to other groups and ungrouped components.
+- **Components:** The page components contained within this group.
+## Events and Status
+
+Page components can be affected by up to three types of events that influence their displayed status. The type of component determines which events apply:
+
+| Event Type | Monitor Components | Static Components |
+|------------|-------------------|-------------------|
+| **Incidents** | ✅ Automatic | ❌ Not supported |
+| **Status Reports** | ✅ Manual | ✅ Manual |
+| **Maintenances** | ✅ Manual | ✅ Manual |
+
+### Incidents
+
+**Applies to:** Monitor components only
+
+Incidents are automatically generated when a monitor detects a failure. They represent unplanned outages or degraded performance discovered through active monitoring.
+
+**How incidents are created:**
+- Monitor check fails (connection timeout, HTTP error, DNS failure).
+- Monitor assertion fails (wrong status code, unexpected response body).
+- Monitor reaches degraded threshold (response time too slow).
+
+**Status impact:** Components with active incidents show an **error** status. This takes the highest priority in the status hierarchy.
+
+**Resolution:** Incidents are automatically resolved when the monitor recovers and checks succeed again.
+
+<Aside>
+Static components **never** generate incidents because they are not linked to monitors. Use status reports for manual issue tracking on static components.
+</Aside>
+
+### Status Reports
+
+**Applies to:** Both monitor and static components
+
+Status reports are manually created updates about component health or issues. They provide a way to communicate problems that may not trigger automatic monitoring or to manually report issues with static components.
+
+**Status impact:** Components with unresolved status reports show a **degraded** status (unless overridden by an incident for monitor components).
+
+**Use cases for monitor components:**
+- Reporting known issues that don't cause complete outages.
+- Communicating performance degradation not captured by monitoring.
+- Providing context for intermittent issues.
+
+**Use cases for static components:**
+- Reporting third-party service issues (e.g., "Stripe processing delays").
+- Communicating external service degradation.
+- Announcing partial outages of non-monitored systems.
+
+**Attaching to components:** When creating a status report, you can select which components are affected. Multiple components can be attached to a single report.
+
+### Maintenances
+
+**Applies to:** Both monitor and static components
+
+Maintenances are scheduled maintenance windows that you create in advance. They inform visitors about planned downtime or service interruptions for both monitored and static components.
+
+**Status impact:** Components with ongoing maintenances show an **info** status (unless overridden by incidents or reports).
+
+**Use cases for monitor components:**
+- Scheduled system upgrades that will cause downtime.
+- Infrastructure changes that affect monitored services.
+- Planned deployments requiring service restarts.
+
+**Use cases for static components:**
+- Third-party maintenance windows (e.g., "Payment provider scheduled maintenance").
+- External service upgrade notifications.
+- Planned downtime for non-monitored dependencies.
+
+**Scheduling:** Maintenances have a defined start and end time. The info status automatically appears during the window and disappears when the maintenance ends.
+
+**Attaching to components:** When creating a maintenance, you select which components will be affected. This allows you to communicate maintenance impact across multiple services.
+
+## Managing Components
+
+### Adding Components
+
+You can add components to your status page in two ways:
+
+1. **Individual components:** Add a single component outside of any group.
+2. **Components within groups:** Add a component directly into a new or existing group.
+
+When adding a monitor component, you can only select from monitors that:
+- Are currently active.
+- Have not been deleted.
+- Are not already linked to another component on this status page.
+
+### Reordering Components
+
+Components and groups can be reordered using drag-and-drop functionality in the dashboard. The order determines how they appear on your status page from top to bottom.
+
+**Ordering tips:**
+- Place your most critical services at the top.
+- Group related services together.
+- Consider visitor priorities when ordering.
+
+### Editing Components
+
+You can modify the following properties of existing components:
+- Component name and description.
+- Group assignment (move between groups or make ungrouped).
+- Display order.
+
+**Note:** You cannot change a component's type (monitor to static or vice versa) after creation. To change types, delete the component and create a new one.
+
+### Deleting Components
+
+When you delete a component, any associations with status reports and maintenances are automatically removed. The linked monitor (if applicable) is not deleted and remains available in your workspace.
+
+**Warning:** Deletion is permanent and cannot be undone. Ensure you want to remove the component before confirming deletion.
+
+## Deprecation Notice
+
+The legacy monitor-only system for status pages is deprecated in favor of the more flexible page component system.
+
+**Deprecated approach:**
+- Status pages directly referenced monitors.
+- No support for static content.
+- Limited organizational flexibility.
+
+**Current approach (page components):**
+- Status pages contain page components.
+- Components can be monitors or static content.
+- Full support for grouping and custom ordering.
+- Better separation between monitoring and status page presentation.
+
+### API Compatibility
+
+**v1 API (backward compatibility):**
+The v1 API continues to display `monitorIds` and `monitors` fields in status page responses to avoid breaking changes for existing integrations. However, these fields now only include page components that are explicitly of type `monitor`. Static components are not included in these legacy fields.
+
+**Future API versions:**
+Newer API versions will primarily use the `pageComponents` structure. The legacy `monitors` and `monitorIds` fields will be removed in future API versions. We recommend migrating your integrations to use `pageComponents` for full feature support.
+
+## Related resources
+
+- **[Status Page Reference](/reference/status-page)** - Complete status page configuration reference.
+- **[Status Report Reference](/reference/status-report)** - Details on creating and managing status reports.
+- **[Create Status Page](/status-page/create-status-page)** - Step-by-step tutorial on creating a status page.
+- **[HTTP Monitor Reference](/reference/http-monitor)** - Technical specification for HTTP monitors that can be linked to components.
diff --git a/apps/server/src/libs/test/preload.ts b/apps/server/src/libs/test/preload.ts
index 0b119d654..fc6731f61 100644
--- a/apps/server/src/libs/test/preload.ts
+++ b/apps/server/src/libs/test/preload.ts
@@ -1,9 +1,5 @@
import { mock } from "bun:test";
-import { app } from "@/index";
-
-console.log(app);
-
mock.module("@openstatus/upstash", () => ({
Redis: {
fromEnv() {
diff --git a/apps/server/src/routes/public/status.test.ts b/apps/server/src/routes/public/status.test.ts
new file mode 100644
index 000000000..f1261efb6
--- /dev/null
+++ b/apps/server/src/routes/public/status.test.ts
@@ -0,0 +1,501 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { app } from "@/index";
+import { db, eq } from "@openstatus/db";
+import {
+ incidentTable,
+ maintenance,
+ monitor,
+ page,
+ pageComponent,
+ statusReport,
+} from "@openstatus/db/src/schema";
+
+/**
+ * Status Route Tests: Verify the status route uses pageComponents with single DB call
+ *
+ * These tests verify that the /public/status/:slug endpoint:
+ * - Uses pageComponents instead of monitorsToPages
+ * - Makes a single database query
+ * - Correctly filters for active monitors only
+ * - Correctly identifies ongoing incidents
+ * - Correctly identifies unresolved status reports
+ * - Correctly identifies ongoing maintenances
+ * - Returns correct status based on the Tracker logic
+ */
+
+const TEST_PREFIX = "status-test";
+let testPageId: number;
+let testMonitorId: number;
+let testMonitor2Id: number;
+let testIncidentId: number;
+let testStatusReportId: number;
+let testMaintenanceId: number;
+
+beforeAll(async () => {
+ // Clean up any existing test data by slug/name before creating new ones
+ await db.delete(page).where(eq(page.slug, `${TEST_PREFIX}-page`));
+ await db.delete(page).where(eq(page.slug, `${TEST_PREFIX}-private-page`));
+ await db.delete(page).where(eq(page.slug, `${TEST_PREFIX}-cache-test`));
+ await db.delete(monitor).where(eq(monitor.name, `${TEST_PREFIX}-monitor-1`));
+ await db.delete(monitor).where(eq(monitor.name, `${TEST_PREFIX}-monitor-2`));
+
+ // Create test page
+ const testPage = await db
+ .insert(page)
+ .values({
+ workspaceId: 1,
+ title: "Status Test Page",
+ description: "A test page for status route tests",
+ slug: `${TEST_PREFIX}-page`,
+ customDomain: "",
+ accessType: "public",
+ })
+ .returning()
+ .get();
+ testPageId = testPage.id;
+
+ // Create first test monitor (active)
+ const testMonitor = await db
+ .insert(monitor)
+ .values({
+ workspaceId: 1,
+ name: `${TEST_PREFIX}-monitor-1`,
+ url: "https://status-test-1.example.com",
+ periodicity: "1m",
+ active: true,
+ regions: "ams",
+ jobType: "http",
+ })
+ .returning()
+ .get();
+ testMonitorId = testMonitor.id;
+
+ // Create second test monitor (inactive)
+ const testMonitor2 = await db
+ .insert(monitor)
+ .values({
+ workspaceId: 1,
+ name: `${TEST_PREFIX}-monitor-2`,
+ url: "https://status-test-2.example.com",
+ periodicity: "1m",
+ active: false, // Inactive monitor
+ regions: "ams",
+ jobType: "http",
+ })
+ .returning()
+ .get();
+ testMonitor2Id = testMonitor2.id;
+
+ // Create page components for both monitors
+ await db.insert(pageComponent).values({
+ workspaceId: 1,
+ pageId: testPageId,
+ monitorId: testMonitorId,
+ type: "monitor",
+ name: `${TEST_PREFIX}-monitor-1`,
+ order: 1,
+ });
+
+ await db.insert(pageComponent).values({
+ workspaceId: 1,
+ pageId: testPageId,
+ monitorId: testMonitor2Id,
+ type: "monitor",
+ name: `${TEST_PREFIX}-monitor-2`,
+ order: 2,
+ });
+});
+
+afterAll(async () => {
+ // Clean up test data
+ if (testIncidentId) {
+ await db
+ .delete(incidentTable)
+ .where(eq(incidentTable.id, testIncidentId))
+ .catch(() => {});
+ }
+ if (testStatusReportId) {
+ await db
+ .delete(statusReport)
+ .where(eq(statusReport.id, testStatusReportId))
+ .catch(() => {});
+ }
+ if (testMaintenanceId) {
+ await db
+ .delete(maintenance)
+ .where(eq(maintenance.id, testMaintenanceId))
+ .catch(() => {});
+ }
+ await db
+ .delete(pageComponent)
+ .where(eq(pageComponent.pageId, testPageId))
+ .catch(() => {});
+ await db
+ .delete(page)
+ .where(eq(page.id, testPageId))
+ .catch(() => {});
+ await db
+ .delete(monitor)
+ .where(eq(monitor.id, testMonitorId))
+ .catch(() => {});
+ await db
+ .delete(monitor)
+ .where(eq(monitor.id, testMonitor2Id))
+ .catch(() => {});
+});
+
+describe("Status Route: Basic functionality", () => {
+ test("returns operational status for page with no incidents", async () => {
+ const res = await app.request(`/public/status/${TEST_PREFIX}-page`);
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ expect(data.status).toBe("operational");
+ });
+
+ test("returns unknown status for non-existent page", async () => {
+ const res = await app.request("/public/status/non-existent-page");
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ expect(data.status).toBe("unknown");
+ });
+
+ test("returns unknown status for non-public page", async () => {
+ // Create a private page
+ const privatePage = await db
+ .insert(page)
+ .values({
+ workspaceId: 1,
+ title: "Private Test Page",
+ description: "A private test page",
+ slug: `${TEST_PREFIX}-private-page`,
+ customDomain: "",
+ accessType: "password",
+ password: "secret",
+ })
+ .returning()
+ .get();
+
+ const res = await app.request(`/public/status/${TEST_PREFIX}-private-page`);
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ expect(data.status).toBe("unknown");
+
+ // Clean up
+ await db.delete(page).where(eq(page.id, privatePage.id));
+ });
+});
+
+describe("Status Route: Active monitor filtering", () => {
+ test("only considers active monitors for status calculation", async () => {
+ // Create an incident for the inactive monitor
+ const inactiveIncident = await db
+ .insert(incidentTable)
+ .values({
+ monitorId: testMonitor2Id,
+ title: "Inactive Monitor Incident",
+ status: "investigating",
+ })
+ .returning()
+ .get();
+
+ const res = await app.request(`/public/status/${TEST_PREFIX}-page`);
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ // Status should still be operational because the monitor is inactive
+ expect(data.status).toBe("operational");
+
+ // Clean up
+ await db
+ .delete(incidentTable)
+ .where(eq(incidentTable.id, inactiveIncident.id));
+ });
+});
+
+describe("Status Route: Incident detection", () => {
+ test("returns incident status with ongoing incident", async () => {
+ // Create an ongoing incident for the active monitor
+ const incident = await db
+ .insert(incidentTable)
+ .values({
+ monitorId: testMonitorId,
+ title: "Test Incident",
+ status: "investigating",
+ // resolvedAt is null, meaning it's ongoing
+ })
+ .returning()
+ .get();
+ testIncidentId = incident.id;
+
+ const res = await app.request(`/public/status/${TEST_PREFIX}-page`);
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ expect(data.status).toBe("incident");
+
+ // Clean up
+ await db.delete(incidentTable).where(eq(incidentTable.id, testIncidentId));
+ testIncidentId = 0;
+ });
+
+ test("ignores resolved incidents", async () => {
+ // First clean up the ongoing incident from previous test if it still exists
+ if (testIncidentId) {
+ await db
+ .delete(incidentTable)
+ .where(eq(incidentTable.id, testIncidentId))
+ .catch(() => {});
+ testIncidentId = 0;
+ }
+
+ // Create a resolved incident
+ const resolvedIncident = await db
+ .insert(incidentTable)
+ .values({
+ monitorId: testMonitorId,
+ title: "Resolved Incident",
+ status: "resolved",
+ resolvedAt: new Date(),
+ })
+ .returning()
+ .get();
+
+ const res = await app.request(`/public/status/${TEST_PREFIX}-page`);
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ // Status should be operational because the incident is resolved
+ expect(data.status).toBe("operational");
+
+ // Clean up
+ await db
+ .delete(incidentTable)
+ .where(eq(incidentTable.id, resolvedIncident.id));
+ });
+});
+
+describe("Status Route: Status report detection", () => {
+ test("returns degraded_performance status with unresolved status report", async () => {
+ // Create an unresolved status report
+ const report = await db
+ .insert(statusReport)
+ .values({
+ workspaceId: 1,
+ pageId: testPageId,
+ title: "Test Status Report",
+ status: "investigating",
+ })
+ .returning()
+ .get();
+ testStatusReportId = report.id;
+
+ const res = await app.request(`/public/status/${TEST_PREFIX}-page`);
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ expect(data.status).toBe("degraded_performance");
+
+ // Clean up
+ await db
+ .delete(statusReport)
+ .where(eq(statusReport.id, testStatusReportId));
+ testStatusReportId = 0;
+ });
+
+ test("ignores resolved status reports", async () => {
+ // First clean up the ongoing status report from previous test if it still exists
+ if (testStatusReportId) {
+ await db
+ .delete(statusReport)
+ .where(eq(statusReport.id, testStatusReportId))
+ .catch(() => {});
+ testStatusReportId = 0;
+ }
+
+ // Create a resolved status report
+ const resolvedReport = await db
+ .insert(statusReport)
+ .values({
+ workspaceId: 1,
+ pageId: testPageId,
+ title: "Resolved Status Report",
+ status: "resolved",
+ })
+ .returning()
+ .get();
+
+ const res = await app.request(`/public/status/${TEST_PREFIX}-page`);
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ // Status should be operational because the report is resolved
+ expect(data.status).toBe("operational");
+
+ // Clean up
+ await db.delete(statusReport).where(eq(statusReport.id, resolvedReport.id));
+ });
+});
+
+describe("Status Route: Maintenance detection", () => {
+ test("returns under_maintenance status with ongoing maintenance", async () => {
+ // Create an ongoing maintenance
+ const now = new Date();
+ const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
+ const oneHourFromNow = new Date(now.getTime() + 60 * 60 * 1000);
+
+ const maint = await db
+ .insert(maintenance)
+ .values({
+ workspaceId: 1,
+ pageId: testPageId,
+ title: "Test Maintenance",
+ message: "Ongoing maintenance",
+ from: oneHourAgo,
+ to: oneHourFromNow,
+ })
+ .returning()
+ .get();
+ testMaintenanceId = maint.id;
+
+ const res = await app.request(`/public/status/${TEST_PREFIX}-page`);
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ expect(data.status).toBe("under_maintenance");
+
+ // Clean up
+ await db.delete(maintenance).where(eq(maintenance.id, testMaintenanceId));
+ testMaintenanceId = 0;
+ });
+
+ test("ignores past maintenances", async () => {
+ // First clean up the ongoing maintenance from previous test if it still exists
+ if (testMaintenanceId) {
+ await db
+ .delete(maintenance)
+ .where(eq(maintenance.id, testMaintenanceId))
+ .catch(() => {});
+ testMaintenanceId = 0;
+ }
+
+ // Create a past maintenance
+ const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000);
+ const oneDayAgo = new Date(Date.now() - 1 * 24 * 60 * 60 * 1000);
+
+ const pastMaint = await db
+ .insert(maintenance)
+ .values({
+ workspaceId: 1,
+ pageId: testPageId,
+ title: "Past Maintenance",
+ message: "Past maintenance",
+ from: twoDaysAgo,
+ to: oneDayAgo,
+ })
+ .returning()
+ .get();
+
+ const res = await app.request(`/public/status/${TEST_PREFIX}-page`);
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ // Status should be operational because the maintenance is in the past
+ expect(data.status).toBe("operational");
+
+ // Clean up
+ await db.delete(maintenance).where(eq(maintenance.id, pastMaint.id));
+ });
+
+ test("ignores future maintenances", async () => {
+ // First clean up any ongoing maintenance from previous test if it still exists
+ if (testMaintenanceId) {
+ await db
+ .delete(maintenance)
+ .where(eq(maintenance.id, testMaintenanceId))
+ .catch(() => {});
+ testMaintenanceId = 0;
+ }
+
+ // Create a future maintenance
+ const oneDayFromNow = new Date(Date.now() + 1 * 24 * 60 * 60 * 1000);
+ const twoDaysFromNow = new Date(Date.now() + 2 * 24 * 60 * 60 * 1000);
+
+ const futureMaint = await db
+ .insert(maintenance)
+ .values({
+ workspaceId: 1,
+ pageId: testPageId,
+ title: "Future Maintenance",
+ message: "Future maintenance",
+ from: oneDayFromNow,
+ to: twoDaysFromNow,
+ })
+ .returning()
+ .get();
+
+ const res = await app.request(`/public/status/${TEST_PREFIX}-page`);
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ // Status should be operational because the maintenance is in the future
+ expect(data.status).toBe("operational");
+
+ // Clean up
+ await db.delete(maintenance).where(eq(maintenance.id, futureMaint.id));
+ });
+});
+
+describe("Status Route: Cache functionality", () => {
+ test("returns cached status on second request if cache is available", async () => {
+ const slug = `${TEST_PREFIX}-cache-test`;
+
+ // Create a test page for cache testing
+ const cachePage = await db
+ .insert(page)
+ .values({
+ workspaceId: 1,
+ title: "Cache Test Page",
+ description: "A test page for cache testing",
+ slug,
+ customDomain: "",
+ accessType: "public",
+ })
+ .returning()
+ .get();
+
+ // First request should hit the database
+ const res1 = await app.request(`/public/status/${slug}`);
+ expect(res1.status).toBe(200);
+ const data1 = await res1.json();
+ expect(data1.status).toBe("operational");
+ expect(res1.headers.get("OpenStatus-Cache")).toBeNull();
+
+ // Second request may hit the cache if Redis is configured
+ const res2 = await app.request(`/public/status/${slug}`);
+ expect(res2.status).toBe(200);
+ const data2 = await res2.json();
+ expect(data2.status).toBe("operational");
+ // Cache header may be "HIT" if Redis is available, or null if not
+ const cacheHeader = res2.headers.get("OpenStatus-Cache");
+ if (cacheHeader !== null) {
+ expect(cacheHeader).toBe("HIT");
+ }
+
+ // Clean up
+ await db.delete(page).where(eq(page.id, cachePage.id));
+ });
+});
diff --git a/apps/server/src/routes/public/status.ts b/apps/server/src/routes/public/status.ts
index 32d3f1c8e..0c3b60837 100644
--- a/apps/server/src/routes/public/status.ts
+++ b/apps/server/src/routes/public/status.ts
@@ -2,22 +2,13 @@ import { getLogger } from "@logtape/logtape";
import { Hono } from "hono";
import { endTime, setMetric, startTime } from "hono/timing";
-import { and, db, eq, gte, inArray, isNull, lte, ne } from "@openstatus/db";
+import { db, eq } from "@openstatus/db";
+import { page } from "@openstatus/db/src/schema";
const logger = getLogger("api-server");
-import {
- incidentTable,
- maintenance,
- monitor,
- monitorsToPages,
- monitorsToStatusReport,
- page,
- statusReport,
-} from "@openstatus/db/src/schema";
import { Status, Tracker } from "@openstatus/tracker";
import { redis } from "@/libs/clients";
-import { notEmpty } from "@/utils/not-empty";
// TODO: include ratelimiting
@@ -36,11 +27,25 @@ status.get("/:slug", async (c) => {
startTime(c, "database");
- const currentPage = await db
- .select()
- .from(page)
- .where(eq(page.slug, slug))
- .get();
+ // Single query with all relations
+ const currentPage = await db.query.page.findFirst({
+ where: eq(page.slug, slug),
+ with: {
+ pageComponents: {
+ with: {
+ monitor: {
+ with: {
+ incidents: true,
+ },
+ },
+ },
+ },
+ statusReports: true,
+ maintenances: true,
+ },
+ });
+
+ endTime(c, "database");
if (!currentPage) {
return c.json({ status: Status.Unknown });
@@ -50,24 +55,36 @@ status.get("/:slug", async (c) => {
return c.json({ status: Status.Unknown });
}
- const {
- pageStatusReportData,
- monitorStatusReportData,
- ongoingIncidents,
- maintenanceData,
- } = await getStatusPageData(currentPage.id);
- endTime(c, "database");
+ // Extract active monitor components
+ const monitorComponents = currentPage.pageComponents.filter(
+ (c) =>
+ c.type === "monitor" &&
+ c.monitor &&
+ c.monitor.active &&
+ !c.monitor.deletedAt,
+ );
- const statusReports = [...monitorStatusReportData].map((item) => {
- return item.status_report;
- });
+ // Extract all ongoing incidents from active monitors
+ const ongoingIncidents = monitorComponents.flatMap(
+ (c) => c.monitor?.incidents?.filter((inc) => !inc.resolvedAt) ?? [],
+ );
- statusReports.push(...pageStatusReportData);
+ // Filter for unresolved status reports
+ const unresolvedStatusReports = currentPage.statusReports.filter(
+ (report) => report.status !== "resolved",
+ );
+ // Filter for ongoing maintenances
+ const now = new Date();
+ const ongoingMaintenances = currentPage.maintenances.filter(
+ (m) => m.from <= now && m.to >= now,
+ );
+
+ // Use the tracker to determine status
const tracker = new Tracker({
incidents: ongoingIncidents,
- statusReports,
- maintenances: maintenanceData,
+ statusReports: unresolvedStatusReports,
+ maintenances: ongoingMaintenances,
});
const status = tracker.currentStatus;
@@ -82,88 +99,3 @@ status.get("/:slug", async (c) => {
return c.json({ status: Status.Unknown });
}
});
-
-async function getStatusPageData(pageId: number) {
- const monitorData = await db
- .select()
- .from(monitorsToPages)
- .innerJoin(
- monitor,
- // REMINDER: query only active monitors as they are the ones that are displayed on the status page
- and(
- eq(monitorsToPages.monitorId, monitor.id),
- eq(monitor.active, true),
- eq(monitorsToPages.pageId, pageId),
- ),
- )
-
- .all();
-
- const monitorIds = monitorData.map((i) => i.monitor?.id).filter(notEmpty);
- if (monitorIds.length === 0) {
- return {
- monitorData,
- pageStatusReportData: [],
- monitorStatusReportData: [],
- ongoingIncidents: [],
- };
- }
-
- const monitorStatusReportQuery = db
- .select()
- .from(monitorsToStatusReport)
- .innerJoin(
- statusReport,
- eq(monitorsToStatusReport.statusReportId, statusReport.id),
- )
- .where(inArray(monitorsToStatusReport.monitorId, monitorIds))
- .all();
-
- const ongoingIncidentsQuery = db
- .select()
- .from(incidentTable)
- .where(
- and(
- isNull(incidentTable.resolvedAt),
- inArray(incidentTable.monitorId, monitorIds),
- ),
- )
- .all();
-
- const ongoingMaintenancesQuery = db
- .select()
- .from(maintenance)
- .where(
- and(
- eq(maintenance.pageId, pageId),
- lte(maintenance.from, new Date()),
- gte(maintenance.to, new Date()),
- ),
- );
-
- const pageStatusReportDataQuery = db
- .select()
- .from(statusReport)
- .where(
- and(eq(statusReport.pageId, pageId), ne(statusReport.status, "resolved")),
- );
-
- const [
- pageStatusReportData,
- monitorStatusReportData,
- ongoingIncidents,
- maintenanceData,
- ] = await Promise.all([
- pageStatusReportDataQuery,
- monitorStatusReportQuery,
- ongoingIncidentsQuery,
- ongoingMaintenancesQuery,
- ]);
-
- return {
- pageStatusReportData,
- monitorStatusReportData,
- maintenanceData,
- ongoingIncidents,
- };
-}
diff --git a/apps/server/src/routes/rpc/services/status-report/__tests__/status-report.test.ts b/apps/server/src/routes/rpc/services/status-report/__tests__/status-report.test.ts
index 51113cd8d..5ac95a720 100644
--- a/apps/server/src/routes/rpc/services/status-report/__tests__/status-report.test.ts
+++ b/apps/server/src/routes/rpc/services/status-report/__tests__/status-report.test.ts
@@ -74,7 +74,7 @@ beforeAll(async () => {
.values({
workspaceId: 1,
pageId: 1,
- type: "external",
+ type: "static",
name: `${TEST_PREFIX}-component`,
description: "Test component for status report tests",
order: 100,
@@ -102,7 +102,7 @@ beforeAll(async () => {
.values({
workspaceId: 1,
pageId: testPage2Id,
- type: "external",
+ type: "static",
name: `${TEST_PREFIX}-component-2`,
description: "Test component on page 2",
order: 100,
diff --git a/apps/server/src/routes/v1/check/http/post.ts b/apps/server/src/routes/v1/check/http/post.ts
index 3f209aea2..2d6e0b685 100644
--- a/apps/server/src/routes/v1/check/http/post.ts
+++ b/apps/server/src/routes/v1/check/http/post.ts
@@ -115,7 +115,7 @@ export function registerHTTPPostCheck(api: typeof checkApi) {
workspace_id: workspaceId,
validation_errors: parsed.error,
});
- throw new Error(`Failed to parse response: ${parsed.error}`);
+ throw new Error(`Failed to parse response: ${parsed.error.message}`);
}
fulfilledRequest.push(parsed.data);
@@ -198,7 +198,7 @@ function getAggregate(data: number[]) {
logger.error("Failed to parse aggregated response", {
validation_errors: parsed.error,
});
- throw new Error(`Failed to parse response: ${parsed.error}`);
+ throw new Error(`Failed to parse response: ${parsed.error.message}`);
}
return parsed.data;
diff --git a/apps/server/src/routes/v1/maintenances/post.ts b/apps/server/src/routes/v1/maintenances/post.ts
index 2f36939a5..47e75bc3c 100644
--- a/apps/server/src/routes/v1/maintenances/post.ts
+++ b/apps/server/src/routes/v1/maintenances/post.ts
@@ -137,6 +137,7 @@ export function registerPostMaintenance(api: typeof maintenancesApi) {
and(
eq(pageSubscriber.pageId, _newMaintenance.pageId),
isNotNull(pageSubscriber.acceptedAt),
+ isNull(pageSubscriber.unsubscribedAt),
),
)
.all();
diff --git a/apps/server/src/routes/v1/pageSubscribers/post.ts b/apps/server/src/routes/v1/pageSubscribers/post.ts
index 05e29fef0..1ba27607c 100644
--- a/apps/server/src/routes/v1/pageSubscribers/post.ts
+++ b/apps/server/src/routes/v1/pageSubscribers/post.ts
@@ -76,6 +76,7 @@ export function registerPostPageSubscriber(api: typeof pageSubscribersApi) {
eq(pageSubscriber.email, input.email),
eq(pageSubscriber.pageId, Number(id)),
isNotNull(pageSubscriber.acceptedAt),
+ isNotNull(pageSubscriber.unsubscribedAt),
),
)
.get();
diff --git a/apps/server/src/routes/v1/pages/post.test.ts b/apps/server/src/routes/v1/pages/post.test.ts
index 38e15550f..a97589fe4 100644
--- a/apps/server/src/routes/v1/pages/post.test.ts
+++ b/apps/server/src/routes/v1/pages/post.test.ts
@@ -2,7 +2,12 @@ import { expect, test } from "bun:test";
import { app } from "@/index";
import { db, eq } from "@openstatus/db";
-import { page } from "@openstatus/db/src/schema";
+import {
+ monitor,
+ monitorsToPages,
+ page,
+ pageComponent,
+} from "@openstatus/db/src/schema";
import { PageSchema } from "./schema";
test("create a valid page", async () => {
@@ -95,3 +100,383 @@ test("no auth key should return 401", async () => {
expect(res.status).toBe(401);
});
+
+test("create a page with custom domain without limits should return 402", async () => {
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "2", // Free plan
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus",
+ description: "OpenStatus website",
+ slug: `custom-domain-${Date.now()}`,
+ customDomain: "status.example.com",
+ }),
+ });
+
+ expect(res.status).toBe(402);
+ const json = await res.json();
+ expect(json.message).toBe("Upgrade for custom domains");
+});
+
+test("create a page with custom domain containing 'openstatus' should return 400", async () => {
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus",
+ description: "OpenStatus website",
+ slug: `openstatus-domain-${Date.now()}`,
+ customDomain: "status.openstatus.dev",
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ const json = await res.json();
+ expect(json.message).toBe("Domain cannot contain 'openstatus'");
+});
+
+test("create a page with reserved slug should return 400", async () => {
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus",
+ description: "OpenStatus website",
+ slug: "api", // Reserved slug
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ const json = await res.json();
+ expect(json.message).toBe("Slug is reserved");
+});
+
+test("create a page with duplicate slug should return 400", async () => {
+ const uniqueSlug = `duplicate-test-${Date.now()}`;
+
+ // Create first page
+ const res1 = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus First",
+ description: "First page",
+ slug: uniqueSlug,
+ }),
+ });
+
+ expect(res1.status).toBe(200);
+ const result1 = PageSchema.safeParse(await res1.json());
+ expect(result1.success).toBe(true);
+
+ // Try to create second page with same slug
+ const res2 = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus Second",
+ description: "Second page",
+ slug: uniqueSlug,
+ }),
+ });
+
+ expect(res2.status).toBe(400);
+ const json = await res2.json();
+ expect(json.message).toBe("Slug has to be unique and has already been taken");
+
+ // Cleanup
+ if (result1.success) {
+ await db.delete(page).where(eq(page.id, result1.data.id));
+ }
+});
+
+test("create a page with email domain protection on free plan should return 402", async () => {
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "2", // Free plan
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus",
+ description: "OpenStatus website",
+ slug: `email-domain-${Date.now()}`,
+ accessType: "email-domain",
+ authEmailDomains: ["example.com"],
+ }),
+ });
+
+ expect(res.status).toBe(402);
+ const json = await res.json();
+ expect(json.message).toBe("Upgrade for email domain protection");
+});
+
+test("create a page with accessType password on free plan should return 402", async () => {
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "2", // Free plan
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus",
+ description: "OpenStatus website",
+ slug: `access-type-password-${Date.now()}`,
+ accessType: "password",
+ password: "secret123",
+ }),
+ });
+
+ expect(res.status).toBe(402);
+ const json = await res.json();
+ expect(json.message).toBe("Upgrade for password protection");
+});
+
+test("create a page with monitors as objects with order", async () => {
+ const uniqueSlug = `ordered-monitors-${Date.now()}`;
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus Ordered",
+ description: "Page with ordered monitors",
+ slug: uniqueSlug,
+ monitors: [
+ { monitorId: 1, order: 1 },
+ { monitorId: 2, order: 0 },
+ ],
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = PageSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+
+ if (result.success) {
+ // Verify pageComponent entries were created with correct order
+ const components = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, result.data.id))
+ .all();
+
+ expect(components.length).toBe(2);
+ expect(components.find((c) => c.monitorId === 1)?.order).toBe(1);
+ expect(components.find((c) => c.monitorId === 2)?.order).toBe(0);
+
+ // Verify sync to legacy table
+ const legacyEntries = await db
+ .select()
+ .from(monitorsToPages)
+ .where(eq(monitorsToPages.pageId, result.data.id))
+ .all();
+
+ expect(legacyEntries.length).toBe(2);
+ expect(legacyEntries.find((e) => e.monitorId === 1)?.order).toBe(1);
+ expect(legacyEntries.find((e) => e.monitorId === 2)?.order).toBe(0);
+
+ // Cleanup
+ await db.delete(page).where(eq(page.id, result.data.id));
+ }
+});
+
+test("create a page without monitors should succeed", async () => {
+ const uniqueSlug = `no-monitors-${Date.now()}`;
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus No Monitors",
+ description: "Page without monitors",
+ slug: uniqueSlug,
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = PageSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+
+ if (result.success) {
+ // Verify no pageComponent entries were created
+ const components = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, result.data.id))
+ .all();
+
+ expect(components.length).toBe(0);
+
+ // Cleanup
+ await db.delete(page).where(eq(page.id, result.data.id));
+ }
+});
+
+test("create a page with monitors as number array should use index as order", async () => {
+ const uniqueSlug = `number-array-${Date.now()}`;
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus Number Array",
+ description: "Page with monitors as numbers",
+ slug: uniqueSlug,
+ monitors: [2, 1],
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = PageSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+
+ if (result.success) {
+ // Verify pageComponent entries were created with index as order
+ const components = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, result.data.id))
+ .all();
+
+ expect(components.length).toBe(2);
+ expect(components.find((c) => c.monitorId === 2)?.order).toBe(0);
+ expect(components.find((c) => c.monitorId === 1)?.order).toBe(1);
+
+ // Cleanup
+ await db.delete(page).where(eq(page.id, result.data.id));
+ }
+});
+
+test("create a page with partial invalid monitors should return 400", async () => {
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "OpenStatus",
+ description: "OpenStatus website",
+ slug: `partial-invalid-${Date.now()}`,
+ monitors: [1, 999], // 1 exists, 999 doesn't
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ const json = await res.json();
+ expect(json.message).toContain("not found");
+});
+
+test("create a page syncs correctly to pageComponent and legacy monitorsToPages", async () => {
+ const uniqueSlug = `sync-test-${Date.now()}`;
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "Sync Test",
+ description: "Testing sync to both tables",
+ slug: uniqueSlug,
+ monitors: [{ monitorId: 1, order: 0 }],
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = PageSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+
+ if (result.success) {
+ // Verify pageComponent (primary table)
+ const components = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, result.data.id))
+ .all();
+
+ expect(components.length).toBe(1);
+ expect(components[0].monitorId).toBe(1);
+ expect(components[0].type).toBe("monitor");
+
+ // Verify monitorsToPages (legacy table)
+ const legacyEntries = await db
+ .select()
+ .from(monitorsToPages)
+ .where(eq(monitorsToPages.pageId, result.data.id))
+ .all();
+
+ expect(legacyEntries.length).toBe(1);
+ expect(legacyEntries[0].monitorId).toBe(1);
+
+ // Cleanup
+ await db.delete(page).where(eq(page.id, result.data.id));
+ }
+});
+
+test("create a page uses monitor externalName when available", async () => {
+ const uniqueSlug = `external-name-${Date.now()}`;
+
+ // First, check if monitor has externalName set
+ const monitorData = await db
+ .select()
+ .from(monitor)
+ .where(eq(monitor.id, 1))
+ .get();
+
+ const res = await app.request("/v1/page", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ title: "External Name Test",
+ description: "Testing monitor external name",
+ slug: uniqueSlug,
+ monitors: [1],
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = PageSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+
+ if (result.success) {
+ const components = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, result.data.id))
+ .all();
+
+ expect(components.length).toBe(1);
+ // Should use externalName if available, otherwise name
+ const expectedName = monitorData?.externalName || monitorData?.name;
+ expect(components[0].name).toBe(expectedName);
+
+ // Cleanup
+ await db.delete(page).where(eq(page.id, result.data.id));
+ }
+});
diff --git a/apps/server/src/routes/v1/pages/post.ts b/apps/server/src/routes/v1/pages/post.ts
index 9d73aeb15..f93f11e3b 100644
--- a/apps/server/src/routes/v1/pages/post.ts
+++ b/apps/server/src/routes/v1/pages/post.ts
@@ -6,13 +6,13 @@ import {
inArray,
isNull,
sql,
- syncMonitorsToPageInsert,
+ syncPageComponentToMonitorsToPageInsertMany,
} from "@openstatus/db";
import { db } from "@openstatus/db/src/db";
import {
monitor,
- monitorsToPages,
page,
+ pageComponent,
subdomainSafeList,
} from "@openstatus/db/src/schema";
@@ -171,7 +171,7 @@ export function registerPostPage(api: typeof pagesApi) {
.values({
...rest,
workspaceId: workspaceId,
- customDomain: rest.customDomain ?? "", // TODO: make database migration to allow null
+ customDomain: rest.customDomain ?? "", // TODO : make database migration to allow null
accessType:
rest.accessType ?? (rest.passwordProtected ? "password" : "public"),
authEmailDomains: rest.authEmailDomains?.join(","),
@@ -181,21 +181,56 @@ export function registerPostPage(api: typeof pagesApi) {
// TODO: missing order
if (monitors?.length) {
- for (const monitor of monitors) {
- const values =
- typeof monitor === "number" ? { monitorId: monitor } : monitor;
+ for (const [index, m] of monitors.entries()) {
+ const values = typeof m === "number" ? { monitorId: m } : m;
+ const _monitor = await db.query.monitor.findFirst({
+ where: and(
+ eq(monitor.id, values.monitorId),
+ eq(monitor.workspaceId, workspaceId),
+ isNull(monitor.deletedAt),
+ ),
+ });
+
+ if (!_monitor) {
+ throw new OpenStatusApiError({
+ code: "BAD_REQUEST",
+ message: `Monitor ${values.monitorId} not found`,
+ });
+ }
+
+ // Insert to pageComponent (primary table)
await db
- .insert(monitorsToPages)
- .values({ pageId: _page.id, ...values })
+ .insert(pageComponent)
+ .values({
+ workspaceId: _page.workspaceId,
+ pageId: _page.id,
+ type: "monitor",
+ monitorId: values.monitorId,
+ name: _monitor.externalName || _monitor.name,
+ order: "order" in values ? values.order : index,
+ groupId: null,
+ groupOrder: 0,
+ })
.run();
- // Sync to page components
- await syncMonitorsToPageInsert(db, {
- monitorId: values.monitorId,
- pageId: _page.id,
- order: "order" in values ? values.order : undefined,
- });
}
+
+ // Sync to legacy table for backwards compatibility
+ const monitorsToPageValues = monitors.map((m, index) => {
+ const values = typeof m === "number" ? { monitorId: m } : m;
+ return {
+ pageId: _page.id,
+ monitorId: values.monitorId,
+ order: "order" in values ? values.order : index,
+ monitorGroupId: null,
+ groupOrder: 0,
+ };
+ });
+
+ await syncPageComponentToMonitorsToPageInsertMany(
+ db,
+ monitorsToPageValues,
+ );
}
const data = transformPageData(PageSchema.parse(_page));
return c.json(data, 200);
diff --git a/apps/server/src/routes/v1/pages/put.ts b/apps/server/src/routes/v1/pages/put.ts
index 0359385a8..21640126f 100644
--- a/apps/server/src/routes/v1/pages/put.ts
+++ b/apps/server/src/routes/v1/pages/put.ts
@@ -2,6 +2,7 @@ import { createRoute } from "@hono/zod-openapi";
import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";
import { trackMiddleware } from "@/libs/middlewares";
+import { notEmpty } from "@/utils/not-empty";
import { Events } from "@openstatus/analytics";
import {
and,
@@ -9,14 +10,14 @@ import {
inArray,
isNull,
sql,
- syncMonitorsToPageDelete,
- syncMonitorsToPageInsert,
+ syncPageComponentToMonitorsToPageDelete,
+ syncPageComponentToMonitorsToPageInsertMany,
} from "@openstatus/db";
import { db } from "@openstatus/db/src/db";
import {
monitor,
- monitorsToPages,
page,
+ pageComponent,
subdomainSafeList,
} from "@openstatus/db/src/schema";
import { isNumberArray } from "../utils";
@@ -184,55 +185,107 @@ export function registerPutPage(api: typeof pagesApi) {
.returning()
.get();
- const currentMonitorsToPages = await db
+ // Query current pageComponents instead of monitorsToPages
+ const currentPageComponents = await db
.select()
- .from(monitorsToPages)
- .where(eq(monitorsToPages.pageId, _page.id));
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, _page.id))
+ .all();
- const removedMonitors = currentMonitorsToPages
- .map(({ monitorId }) => monitorId)
- .filter((x) => !monitorIds?.includes(x));
+ const currentMonitorIds = currentPageComponents
+ .filter((pc) => pc.type === "monitor" && pc.monitorId !== null)
+ .map((pc) => pc.monitorId as number);
- if (removedMonitors.length) {
+ const removedMonitorIds = currentMonitorIds.filter(
+ (id) => !monitorIds?.includes(id),
+ );
+
+ // Delete removed monitors from pageComponent (primary table)
+ if (removedMonitorIds.length) {
await db
- .delete(monitorsToPages)
+ .delete(pageComponent)
.where(
and(
- inArray(monitorsToPages.monitorId, removedMonitors),
- eq(monitorsToPages.pageId, newPage.id),
+ inArray(pageComponent.monitorId, removedMonitorIds),
+ eq(pageComponent.pageId, newPage.id),
),
);
- // Sync delete to page components
- for (const monitorId of removedMonitors) {
- await syncMonitorsToPageDelete(db, { monitorId, pageId: newPage.id });
+ // Reverse sync delete to monitorsToPages (for backwards compatibility)
+ for (const monitorId of removedMonitorIds) {
+ await syncPageComponentToMonitorsToPageDelete(db, {
+ monitorId,
+ pageId: newPage.id,
+ });
}
}
+ // Insert or update pageComponents (primary table)
if (monitors) {
- for (const monitor of monitors) {
- const values =
- typeof monitor === "number" ? { monitorId: monitor } : monitor;
+ for (const [index, m] of monitors.entries()) {
+ const values = typeof m === "number" ? { monitorId: m } : m;
+
+ const _monitor = await db.query.monitor.findFirst({
+ where: and(
+ eq(monitor.id, values.monitorId),
+ eq(monitor.workspaceId, workspaceId),
+ isNull(monitor.deletedAt),
+ ),
+ });
+
+ if (!_monitor) {
+ throw new OpenStatusApiError({
+ code: "BAD_REQUEST",
+ message: `Monitor ${values.monitorId} not found`,
+ });
+ }
+ // Insert or update pageComponent
await db
- .insert(monitorsToPages)
- .values({ pageId: newPage.id, ...values })
+ .insert(pageComponent)
+ .values({
+ workspaceId: newPage.workspaceId,
+ pageId: newPage.id,
+ type: "monitor",
+ monitorId: values.monitorId,
+ name: _monitor.externalName || _monitor.name,
+ order: "order" in values ? values.order : index,
+ groupId: null,
+ groupOrder: 0,
+ })
.onConflictDoUpdate({
- target: [monitorsToPages.monitorId, monitorsToPages.pageId],
- set: { order: sql.raw("excluded.`order`") },
- });
- // Sync to page components (existing ones will be ignored due to onConflictDoNothing in sync)
- await syncMonitorsToPageInsert(db, {
- monitorId: values.monitorId,
- pageId: newPage.id,
- order: "order" in values ? values.order : undefined,
- });
+ target: [pageComponent.monitorId, pageComponent.pageId],
+ set: {
+ order: sql.raw("excluded.`order`"),
+ name: sql.raw("excluded.`name`"),
+ },
+ })
+ .run();
}
+
+ // Reverse sync to monitorsToPages (for backwards compatibility)
+ const monitorsToPageValues = monitors.map((m, index) => {
+ const values = typeof m === "number" ? { monitorId: m } : m;
+ return {
+ pageId: newPage.id,
+ monitorId: values.monitorId,
+ order: "order" in values ? values.order : index,
+ monitorGroupId: null,
+ groupOrder: 0,
+ };
+ });
+
+ await syncPageComponentToMonitorsToPageInsertMany(
+ db,
+ monitorsToPageValues,
+ );
}
const data = transformPageData(
PageSchema.parse({
...newPage,
- monitors: monitors || currentMonitorsToPages,
+ monitors:
+ monitors ||
+ currentPageComponents.map((pc) => pc.monitorId).filter(notEmpty),
}),
);
diff --git a/apps/server/src/routes/v1/statusReportUpdates/post.ts b/apps/server/src/routes/v1/statusReportUpdates/post.ts
index a7aae0124..b55bd6087 100644
--- a/apps/server/src/routes/v1/statusReportUpdates/post.ts
+++ b/apps/server/src/routes/v1/statusReportUpdates/post.ts
@@ -106,13 +106,6 @@ export function registerPostStatusReportUpdate(
const _page = await db.query.page.findFirst({
where: eq(page.id, _statusReport.pageId),
- with: {
- monitorsToPages: {
- with: {
- monitor: true,
- },
- },
- },
});
const validSubscribers = subscribers.filter(
diff --git a/apps/server/src/routes/v1/statusReports/post.test.ts b/apps/server/src/routes/v1/statusReports/post.test.ts
index b419e024a..2b36ad906 100644
--- a/apps/server/src/routes/v1/statusReports/post.test.ts
+++ b/apps/server/src/routes/v1/statusReports/post.test.ts
@@ -1,6 +1,13 @@
import { expect, test } from "bun:test";
import { app } from "@/index";
+import { db, eq } from "@openstatus/db";
+import {
+ monitorsToStatusReport,
+ pageComponent,
+ statusReport,
+ statusReportsToPageComponents,
+} from "@openstatus/db/src/schema";
import { StatusReportSchema } from "./schema";
test("create a valid status report", async () => {
@@ -158,3 +165,267 @@ test("no auth key should return 401", async () => {
expect(res.status).toBe(401);
});
+
+test("create a status report syncs correctly to statusReportsToPageComponents and legacy monitorsToStatusReport", async () => {
+ const date = new Date();
+ date.setMilliseconds(0);
+
+ const res = await app.request("/v1/status_report", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ status: "investigating",
+ title: "Sync Test Status Report",
+ message: "Testing sync to both tables",
+ monitorIds: [1],
+ date: date.toISOString(),
+ pageId: 1,
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = StatusReportSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+
+ if (result.success) {
+ const statusReportId = result.data.id;
+
+ // Verify statusReportsToPageComponents (primary table)
+ const components = await db
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, statusReportId))
+ .all();
+
+ expect(components.length).toBeGreaterThan(0);
+
+ // Get the page component to verify it's linked correctly
+ const pageComponents = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.id, components[0].pageComponentId))
+ .all();
+
+ expect(pageComponents.length).toBe(1);
+ expect(pageComponents[0].monitorId).toBe(1);
+ expect(pageComponents[0].pageId).toBe(1);
+ expect(pageComponents[0].type).toBe("monitor");
+
+ // Verify monitorsToStatusReport (legacy table)
+ const legacyEntries = await db
+ .select()
+ .from(monitorsToStatusReport)
+ .where(eq(monitorsToStatusReport.statusReportId, statusReportId))
+ .all();
+
+ expect(legacyEntries.length).toBe(1);
+ expect(legacyEntries[0].monitorId).toBe(1);
+
+ // Cleanup
+ await db
+ .delete(statusReport)
+ .where(eq(statusReport.id, statusReportId))
+ .run();
+ }
+});
+
+test("create a status report with multiple monitors syncs correctly to both tables", async () => {
+ const date = new Date();
+ date.setMilliseconds(0);
+
+ // First, check which monitors from [1, 2] exist as page components on page 1
+ const existingPageComponents = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, 1))
+ .all();
+
+ const existingMonitorIds = existingPageComponents
+ .filter(
+ (c) =>
+ c.monitorId !== null &&
+ c.type === "monitor" &&
+ [1, 2].includes(c.monitorId),
+ )
+ .map((c) => c.monitorId as number);
+
+ const res = await app.request("/v1/status_report", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ status: "investigating",
+ title: "Multi-Monitor Sync Test",
+ message: "Testing sync with multiple monitors",
+ monitorIds: [1, 2],
+ date: date.toISOString(),
+ pageId: 1,
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = StatusReportSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+
+ if (result.success) {
+ const statusReportId = result.data.id;
+
+ // Verify statusReportsToPageComponents (primary table)
+ const components = await db
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, statusReportId))
+ .all();
+
+ // Should only link monitors that exist as page components on this page
+ expect(components.length).toBe(existingMonitorIds.length);
+
+ // Verify monitorsToStatusReport (legacy table)
+ const legacyEntries = await db
+ .select()
+ .from(monitorsToStatusReport)
+ .where(eq(monitorsToStatusReport.statusReportId, statusReportId))
+ .all();
+
+ // Both tables should have the same number of entries
+ expect(legacyEntries.length).toBe(components.length);
+
+ // Verify the monitor IDs in legacy table match what we expect
+ const legacyMonitorIds = legacyEntries.map((e) => e.monitorId).sort();
+ expect(legacyMonitorIds).toEqual(existingMonitorIds.sort());
+
+ // Cleanup
+ await db
+ .delete(statusReport)
+ .where(eq(statusReport.id, statusReportId))
+ .run();
+ }
+});
+
+test("create a status report without monitorIds should not create sync entries", async () => {
+ const date = new Date();
+ date.setMilliseconds(0);
+
+ const res = await app.request("/v1/status_report", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ status: "investigating",
+ title: "No Monitors Status Report",
+ message: "No specific monitors affected",
+ date: date.toISOString(),
+ pageId: 1,
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = StatusReportSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+
+ if (result.success) {
+ const statusReportId = result.data.id;
+
+ // Verify no statusReportsToPageComponents entries
+ const components = await db
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, statusReportId))
+ .all();
+
+ expect(components.length).toBe(0);
+
+ // Verify no monitorsToStatusReport entries
+ const legacyEntries = await db
+ .select()
+ .from(monitorsToStatusReport)
+ .where(eq(monitorsToStatusReport.statusReportId, statusReportId))
+ .all();
+
+ expect(legacyEntries.length).toBe(0);
+
+ // Cleanup
+ await db
+ .delete(statusReport)
+ .where(eq(statusReport.id, statusReportId))
+ .run();
+ }
+});
+
+test("create a status report only links monitors that exist as page components", async () => {
+ const date = new Date();
+ date.setMilliseconds(0);
+
+ // First, check which monitors exist as page components on page 1
+ const existingComponents = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, 1))
+ .all();
+
+ const existingMonitorIds = existingComponents
+ .filter((c) => c.monitorId !== null && c.type === "monitor")
+ .map((c) => c.monitorId as number);
+
+ if (existingMonitorIds.length === 0) {
+ // Skip test if no monitors exist on the page
+ return;
+ }
+
+ const res = await app.request("/v1/status_report", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ status: "investigating",
+ title: "Page Component Link Test",
+ message: "Testing page component linking",
+ monitorIds: existingMonitorIds,
+ date: date.toISOString(),
+ pageId: 1,
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const result = StatusReportSchema.safeParse(await res.json());
+ expect(result.success).toBe(true);
+
+ if (result.success) {
+ const statusReportId = result.data.id;
+
+ // Verify statusReportsToPageComponents entries match existing components
+ const components = await db
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, statusReportId))
+ .all();
+
+ // Each linked component should correspond to a page component
+ for (const component of components) {
+ const pageComp = await db
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.id, component.pageComponentId))
+ .get();
+
+ expect(pageComp).toBeDefined();
+ expect(pageComp?.pageId).toBe(1);
+ expect(existingMonitorIds).toContain(pageComp?.monitorId as number);
+ }
+
+ // Cleanup
+ await db
+ .delete(statusReport)
+ .where(eq(statusReport.id, statusReportId))
+ .run();
+ }
+});
diff --git a/apps/server/src/routes/v1/statusReports/post.ts b/apps/server/src/routes/v1/statusReports/post.ts
index d9706de0c..0a4bd58a8 100644
--- a/apps/server/src/routes/v1/statusReports/post.ts
+++ b/apps/server/src/routes/v1/statusReports/post.ts
@@ -7,15 +7,16 @@ import {
inArray,
isNotNull,
isNull,
- syncStatusReportToMonitorInsertMany,
+ syncStatusReportToPageComponentInsertMany,
} from "@openstatus/db";
import {
monitor,
- monitorsToStatusReport,
page,
+ pageComponent,
pageSubscriber,
statusReport,
statusReportUpdate,
+ statusReportsToPageComponents,
} from "@openstatus/db/src/schema";
import { env } from "@/env";
@@ -129,24 +130,46 @@ export function registerPostStatusReport(api: typeof statusReportsApi) {
.returning()
.get();
+ if (!_newStatusReport.pageId) {
+ throw new OpenStatusApiError({
+ code: "BAD_REQUEST",
+ message: "Page ID is required",
+ });
+ }
+
if (input.monitorIds?.length) {
- await db
- .insert(monitorsToStatusReport)
- .values(
- input.monitorIds.map((id) => {
- return {
- monitorId: id,
- statusReportId: _newStatusReport.id,
- };
- }),
+ // Find matching page_components for the monitors on this page
+ const components = await db
+ .select({ id: pageComponent.id })
+ .from(pageComponent)
+ .where(
+ and(
+ inArray(pageComponent.monitorId, input.monitorIds),
+ eq(pageComponent.pageId, _newStatusReport.pageId),
+ eq(pageComponent.type, "monitor"),
+ ),
)
- .returning();
- // Sync to page components
- await syncStatusReportToMonitorInsertMany(
- db,
- _newStatusReport.id,
- input.monitorIds,
- );
+ .all();
+
+ // Insert to statusReportsToPageComponents (primary table)
+ if (components.length > 0) {
+ await db
+ .insert(statusReportsToPageComponents)
+ .values(
+ components.map((c) => ({
+ statusReportId: _newStatusReport.id,
+ pageComponentId: c.id,
+ })),
+ )
+ .run();
+
+ // Sync to legacy table for backwards compatibility
+ await syncStatusReportToPageComponentInsertMany(
+ db,
+ _newStatusReport.id,
+ components.map((c) => c.id),
+ );
+ }
}
if (limits["status-subscribers"] && _newStatusReport.pageId) {
@@ -164,21 +187,11 @@ export function registerPostStatusReport(api: typeof statusReportsApi) {
const pageInfo = await db.query.page.findFirst({
where: eq(page.id, _newStatusReport.pageId),
- with: {
- monitorsToPages: {
- with: {
- monitor: true,
- },
- },
- },
});
const _statusReport = await db.query.statusReport.findFirst({
where: eq(statusReport.id, _newStatusReport.id),
with: {
- monitorsToStatusReports: {
- with: { monitor: true },
- },
statusReportsToPageComponents: {
with: { pageComponent: true },
},
diff --git a/apps/server/src/routes/v1/statusReports/subscriber-filtering.integration.test.ts b/apps/server/src/routes/v1/statusReports/subscriber-filtering.integration.test.ts
index 98d065d63..034b33fcf 100644
--- a/apps/server/src/routes/v1/statusReports/subscriber-filtering.integration.test.ts
+++ b/apps/server/src/routes/v1/statusReports/subscriber-filtering.integration.test.ts
@@ -196,6 +196,10 @@ describe("Subscriber state transitions", () => {
where: eq(pageSubscriber.email, "[email protected]"),
});
+ if (!unsubscribedSub) {
+ throw new Error("Unsubscribed subscriber not found");
+ }
+
expect(unsubscribedSub?.unsubscribedAt).not.toBeNull();
// Simulate re-subscription by clearing unsubscribedAt
diff --git a/apps/server/src/routes/v1/statusReports/update/post.ts b/apps/server/src/routes/v1/statusReports/update/post.ts
index e946b4e50..96df7e439 100644
--- a/apps/server/src/routes/v1/statusReports/update/post.ts
+++ b/apps/server/src/routes/v1/statusReports/update/post.ts
@@ -1,5 +1,6 @@
import { env } from "@/env";
import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";
+import { notEmpty } from "@/utils/not-empty";
import { createRoute } from "@hono/zod-openapi";
import { and, db, eq, isNotNull } from "@openstatus/db";
import {
@@ -142,7 +143,11 @@ export function registerStatusReportUpdateRoutes(api: typeof statusReportsApi) {
where: eq(statusReport.id, Number(id)),
with: {
statusReportUpdates: true,
- monitorsToStatusReports: true,
+ statusReportsToPageComponents: {
+ with: {
+ pageComponent: true,
+ },
+ },
},
});
@@ -158,9 +163,9 @@ export function registerStatusReportUpdateRoutes(api: typeof statusReportsApi) {
statusReportUpdateIds: fullStatusReport.statusReportUpdates.map(
(u) => u.id,
),
- monitorIds: fullStatusReport.monitorsToStatusReports.map(
- (m) => m.monitorId,
- ),
+ monitorIds: fullStatusReport.statusReportsToPageComponents
+ .map((m) => m.pageComponent.monitorId)
+ .filter(notEmpty),
});
return c.json(data, 200);
diff --git a/apps/server/src/utils/page-component.ts b/apps/server/src/utils/page-component.ts
new file mode 100644
index 000000000..f16c0536a
--- /dev/null
+++ b/apps/server/src/utils/page-component.ts
@@ -0,0 +1,21 @@
+import type { PageComponentType } from "@openstatus/db/src/schema";
+
+/**
+ * Type guard to check if a pageComponent is a monitor type with a valid monitor relation
+ * Filters out static components and ensures the monitor is active and not deleted
+ */
+export function isMonitorComponent(component: {
+ type: PageComponentType;
+ monitor?: { active: boolean | null; deletedAt: Date | null } | null;
+}): component is {
+ type: "monitor";
+ monitor: { active: true; deletedAt: null };
+} {
+ return (
+ component.type === "monitor" &&
+ component.monitor !== null &&
+ component.monitor !== undefined &&
+ component.monitor.active === true &&
+ component.monitor.deletedAt === null
+ );
+}
diff --git a/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/[type]/route.ts b/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/[type]/route.ts
index ce43a7a84..c4731fd31 100644
--- a/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/[type]/route.ts
+++ b/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/[type]/route.ts
@@ -25,7 +25,7 @@ export async function GET(
if (!["rss", "atom"].includes(type)) return notFound();
const _page = await queryClient.fetchQuery(
- trpc.page.getPageBySlug.queryOptions({ slug: domain }),
+ trpc.statusPage.getLight.queryOptions({ slug: domain }),
);
if (!_page) return notFound();
diff --git a/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/json/route.ts b/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/json/route.ts
index 5ae6cedc6..b842bddf4 100644
--- a/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/json/route.ts
+++ b/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/json/route.ts
@@ -13,7 +13,7 @@ export async function GET(
const { domain } = await props.params;
const _page = await queryClient.fetchQuery(
- trpc.page.getPageBySlug.queryOptions({ slug: domain }),
+ trpc.statusPage.getLight.queryOptions({ slug: domain }),
);
if (!_page) return notFound();
diff --git a/apps/web/src/app/api/og/page/route.tsx b/apps/web/src/app/api/og/page/route.tsx
index 21777606e..2e1b98b78 100644
--- a/apps/web/src/app/api/og/page/route.tsx
+++ b/apps/web/src/app/api/og/page/route.tsx
@@ -21,7 +21,7 @@ export async function GET(req: Request) {
const slug = searchParams.has("slug") ? searchParams.get("slug") : undefined;
- const page = await api.page.getPageBySlug.query({ slug: slug || "" });
+ const page = await api.statusPage.getLight.query({ slug: slug || "" });
const _protected = page?.accessType !== "public";
const title = page ? page.title : TITLE;
const description = page ? "" : DESCRIPTION;
diff --git a/apps/web/src/content/pages/product/status-page.mdx b/apps/web/src/content/pages/product/status-page.mdx
index 00f57086b..89c92dfd6 100644
--- a/apps/web/src/content/pages/product/status-page.mdx
+++ b/apps/web/src/content/pages/product/status-page.mdx
@@ -31,11 +31,15 @@ A status page is a dedicated webpage that provides real-time information about t
We provide you with a good **mix of customization and opinionated options**.
-### Monitors (or Components)
+### Page Components
You can attach specific monitors to a status page. You can either populate the data from the **aggregated uptime** data **or manually** manage them. Read more [about uptime monitoring](/uptime-monitoring).
-You can **group monitors** by their services, locations,... and they will be collabsible.
+Page components provide a **flexible structure** that supports both:
+- **Monitors**: Automatically synced with your uptime monitoring data
+- **External Services**: Manually managed components for third-party services or systems you don't directly monitor
+
+You can **group page components** by their services, locations, or any logical grouping, and they will be collapsible for better organization.
### Customization
@@ -59,11 +63,10 @@ We support following communication channels:
- **Emails**
- **RSS/Atom feeds**
+- **JSON**
[Contact us](mailto:[email protected]) if you are looking for specific a channel.
-### Visibility
-
-You can **password protect** your status page. By default, a status page is for the broad public, but if you want to share it internally or with clients, a password helps you from unwanted visitors.
+### Audience
-The RSS feed will still work. Append your `?pw=` to the URL **search params** to share private pages.
+By default, your status page is public. For internal or client-specific pages, you can protect access using **password protection** or **magic link** authentication to control who can view your updates.
diff --git a/apps/web/src/content/pages/unrelated/pricing.mdx b/apps/web/src/content/pages/unrelated/pricing.mdx
index f48599e71..efadeb215 100644
--- a/apps/web/src/content/pages/unrelated/pricing.mdx
+++ b/apps/web/src/content/pages/unrelated/pricing.mdx
@@ -28,6 +28,7 @@ category: "Company"
["Number of on-demand checks", "30/mo.", "100/mo.", "300/mo."],
[<a href="/status-page"><strong>Status Pages</strong></a>, "", "", ""],
["Number of status pages", "1", "1 +$20/mo./each", "5 +$20/mo./each"],
+ ["Number of components", "3", "20", "50"],
["Maintenance status", "+", "+", "+"],
["Toggle numbers visibility", "+", "+", "+"],
["Subscribers", "", "+", "+"],
diff --git a/packages/analytics/src/events.ts b/packages/analytics/src/events.ts
index df3b6b9c6..20f6143e2 100644
--- a/packages/analytics/src/events.ts
+++ b/packages/analytics/src/events.ts
@@ -60,6 +60,14 @@ export const Events = {
name: "page_deleted",
channel: "page",
},
+ DeletePageComponent: {
+ name: "page_component_deleted",
+ channel: "page",
+ },
+ UpdatePageComponentOrder: {
+ name: "page_component_order_updated",
+ channel: "page",
+ },
SubscribePage: {
name: "user_subscribed",
channel: "page",
diff --git a/packages/api/src/router/email/index.ts b/packages/api/src/router/email/index.ts
index b75038525..00893d48a 100644
--- a/packages/api/src/router/email/index.ts
+++ b/packages/api/src/router/email/index.ts
@@ -42,11 +42,6 @@ export const emailRouter = createTRPCRouter({
pageSubscribers: {
where: isNotNull(pageSubscriber.acceptedAt),
},
- monitorsToPages: {
- with: {
- monitor: true,
- },
- },
},
},
},
diff --git a/packages/api/src/router/maintenance.ts b/packages/api/src/router/maintenance.ts
index 33536e5a5..936650a90 100644
--- a/packages/api/src/router/maintenance.ts
+++ b/packages/api/src/router/maintenance.ts
@@ -72,7 +72,6 @@ export const maintenanceRouter = createTRPCRouter({
? asc(maintenance.createdAt)
: desc(maintenance.createdAt),
with: {
- maintenancesToMonitors: true,
maintenancesToPageComponents: { with: { pageComponent: true } },
},
});
@@ -87,7 +86,6 @@ export const maintenanceRouter = createTRPCRouter({
.parse(
result.map((m) => ({
...m,
- monitors: m.maintenancesToMonitors.map((m) => m.monitorId),
pageComponents: m.maintenancesToPageComponents.map(
({ pageComponent }) => pageComponent,
),
diff --git a/packages/api/src/router/monitor.ts b/packages/api/src/router/monitor.ts
index 292ed1943..c083f63c7 100644
--- a/packages/api/src/router/monitor.ts
+++ b/packages/api/src/router/monitor.ts
@@ -22,9 +22,7 @@ import {
inArray,
isNull,
syncMaintenanceToMonitorDeleteByMonitors,
- syncMonitorsToPageDelete,
syncMonitorsToPageDeleteByMonitors,
- syncMonitorsToPageInsertMany,
syncStatusReportToMonitorDeleteByMonitors,
} from "@openstatus/db";
import {
@@ -39,14 +37,11 @@ import {
monitorsToStatusReport,
notification,
notificationsToMonitors,
- page,
privateLocationToMonitors,
selectIncidentSchema,
- selectMaintenanceSchema,
selectMonitorSchema,
selectMonitorTagSchema,
selectNotificationSchema,
- selectPageSchema,
selectPrivateLocationSchema,
} from "@openstatus/db/src/schema";
@@ -240,15 +235,9 @@ export const monitorRouter = createTRPCRouter({
monitorsToNotifications: {
with: { notification: true },
},
- monitorsToPages: {
- with: { page: true },
- },
monitorTagsToMonitors: {
with: { monitorTag: true },
},
- maintenancesToMonitors: {
- with: { maintenance: true },
- },
incidents: true,
privateLocationToMonitors: {
with: { privateLocation: true },
@@ -261,9 +250,7 @@ export const monitorRouter = createTRPCRouter({
return selectMonitorSchema
.extend({
notifications: z.array(selectNotificationSchema).prefault([]),
- pages: z.array(selectPageSchema).prefault([]),
tags: z.array(selectMonitorTagSchema).prefault([]),
- maintenances: z.array(selectMaintenanceSchema).prefault([]),
incidents: z.array(selectIncidentSchema).prefault([]),
privateLocations: z.array(selectPrivateLocationSchema).prefault([]),
})
@@ -272,9 +259,7 @@ export const monitorRouter = createTRPCRouter({
notifications: data.monitorsToNotifications.map(
(m) => m.notification,
),
- pages: data.monitorsToPages.map((p) => p.page),
tags: data.monitorTagsToMonitors.map((t) => t.monitorTag),
- maintenances: data.maintenancesToMonitors.map((m) => m.maintenance),
incidents: data.incidents,
privateLocations: data.privateLocationToMonitors.map(
(p) => p.privateLocation,
@@ -555,88 +540,6 @@ export const monitorRouter = createTRPCRouter({
});
}),
- updateStatusPages: protectedProcedure
- .meta({ track: Events.UpdateMonitor })
- .input(
- z.object({
- id: z.number(),
- statusPages: z.array(z.number()),
- description: z.string().optional(),
- externalName: z.string().optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const allPages = await ctx.db.query.page.findMany({
- where: and(
- eq(page.workspaceId, ctx.workspace.id),
- inArray(page.id, input.statusPages),
- ),
- });
-
- if (allPages.length !== input.statusPages.length) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You don't have access to this status page.",
- });
- }
-
- await ctx.db.transaction(async (tx) => {
- // REMINDER: why do we need to do this complex logic instead of just deleting and inserting?
- // Because we need to preserve the group information when updating the status pages.
-
- const existingEntries = await tx.query.monitorsToPages.findMany({
- where: eq(monitorsToPages.monitorId, input.id),
- });
-
- const existingPageIds = new Set(
- existingEntries.map((entry) => entry.pageId),
- );
- const inputPageIds = new Set(input.statusPages);
-
- const pageIdsToDelete = existingEntries
- .filter((entry) => !inputPageIds.has(entry.pageId))
- .map((entry) => entry.pageId);
-
- const pageIdsToInsert = input.statusPages.filter(
- (pageId) => !existingPageIds.has(pageId),
- );
-
- if (pageIdsToDelete.length > 0) {
- await tx
- .delete(monitorsToPages)
- .where(
- and(
- eq(monitorsToPages.monitorId, input.id),
- inArray(monitorsToPages.pageId, pageIdsToDelete),
- ),
- );
- // Sync delete to page components
- for (const pageId of pageIdsToDelete) {
- await syncMonitorsToPageDelete(tx, { monitorId: input.id, pageId });
- }
- }
-
- if (pageIdsToInsert.length > 0) {
- const values = pageIdsToInsert.map((pageId) => ({
- monitorId: input.id,
- pageId,
- }));
- await tx.insert(monitorsToPages).values(values);
- // Sync to page components
- await syncMonitorsToPageInsertMany(tx, values);
- }
-
- await tx
- .update(monitor)
- .set({
- description: input.description,
- externalName: input.externalName,
- updatedAt: new Date(),
- })
- .where(and(eq(monitor.id, input.id)));
- });
- }),
-
updateGeneral: protectedProcedure
.meta({ track: Events.UpdateMonitor })
.input(
diff --git a/packages/api/src/router/page.test.ts b/packages/api/src/router/page.test.ts
deleted file mode 100644
index 75ed681fe..000000000
--- a/packages/api/src/router/page.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { expect, test } from "bun:test";
-
-import { edgeRouter } from "../edge";
-import { createInnerTRPCContext } from "../trpc";
-
-test("Get Test Page", async () => {
- const ctx = createInnerTRPCContext({
- req: undefined,
- // @ts-expect-error
- auth: {
- userId: "1",
- sessionId: "1",
- },
- });
-
- const caller = edgeRouter.createCaller(ctx);
- const result = await caller.page.getPageBySlug({ slug: "status" });
- expect(result).toMatchObject({
- createdAt: expect.any(Date),
- customDomain: expect.any(String),
- description: expect.any(String),
- icon: expect.any(String),
- statusReports: expect.any(Array),
- monitors: expect.any(Array),
- incidents: expect.any(Array),
- maintenances: expect.any(Array),
- published: expect.any(Boolean),
- slug: expect.any(String),
- title: expect.any(String),
- updatedAt: expect.any(Date),
- });
-});
-
-test("No Page", async () => {
- const ctx = createInnerTRPCContext({
- req: undefined,
- // @ts-expect-error
- auth: {
- userId: "1",
- sessionId: "1",
- },
- });
-
- const caller = edgeRouter.createCaller(ctx);
- const result = await caller.page.getPageBySlug({ slug: "Dont Exist" });
- expect(result).toBeUndefined();
-});
diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.ts
index 39dedaf4a..3bf727508 100644
--- a/packages/api/src/router/page.ts
+++ b/packages/api/src/router/page.ts
@@ -9,37 +9,24 @@ import {
inArray,
isNull,
sql,
- syncMonitorGroupDeleteMany,
- syncMonitorGroupInsert,
- syncMonitorsToPageDelete,
- syncMonitorsToPageUpsertMany,
syncPageComponentToMonitorsToPageInsertMany,
} from "@openstatus/db";
import {
- incidentTable,
insertPageSchema,
- legacy_selectPublicPageSchemaWithRelation,
- maintenance,
monitor,
- monitorGroup,
- monitorsToPages,
page,
pageAccessTypes,
pageComponent,
selectMaintenanceSchema,
- selectMonitorGroupSchema,
- selectMonitorSchema,
selectPageComponentGroupSchema,
selectPageComponentSchema,
selectPageSchema,
- statusReport,
subdomainSafeList,
- workspace,
} from "@openstatus/db/src/schema";
import { Events } from "@openstatus/analytics";
import { env } from "../env";
-import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
+import { createTRPCRouter, protectedProcedure } from "../trpc";
if (process.env.NODE_ENV === "test") {
require("../test/preload");
@@ -200,116 +187,6 @@ export const pageRouter = createTRPCRouter({
.where(and(...whereConditions))
.run();
}),
- // public if we use trpc hooks to get the page from the url
- getPageBySlug: publicProcedure
- .input(z.object({ slug: z.string().toLowerCase() }))
- .output(legacy_selectPublicPageSchemaWithRelation.nullish())
- .query(async (opts) => {
- if (!opts.input.slug) return;
-
- const result = await opts.ctx.db
- .select()
- .from(page)
- .where(
- sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
- )
- .get();
-
- if (!result) return;
-
- const [workspaceResult, monitorsToPagesResult] = await Promise.all([
- opts.ctx.db
- .select()
- .from(workspace)
- .where(eq(workspace.id, result.workspaceId))
- .get(),
- opts.ctx.db
- .select()
- .from(monitorsToPages)
- .leftJoin(monitor, eq(monitorsToPages.monitorId, monitor.id))
- .where(
- // make sur only active monitors are returned!
- and(
- eq(monitorsToPages.pageId, result.id),
- eq(monitor.active, true),
- ),
- )
- .all(),
- ]);
-
- // FIXME: There is probably a better way to do this
-
- const monitorsId = monitorsToPagesResult.map(
- ({ monitors_to_pages }) => monitors_to_pages.monitorId,
- );
-
- const statusReports = await opts.ctx.db.query.statusReport.findMany({
- where: eq(statusReport.pageId, result.id),
- with: {
- statusReportUpdates: {
- orderBy: (reports, { desc }) => desc(reports.date),
- },
- monitorsToStatusReports: { with: { monitor: true } },
- },
- });
-
- const monitorQuery =
- monitorsId.length > 0
- ? opts.ctx.db
- .select()
- .from(monitor)
- .where(
- and(
- inArray(monitor.id, monitorsId),
- eq(monitor.active, true),
- isNull(monitor.deletedAt),
- ), // REMINDER: this is hardcoded
- )
- .all()
- : [];
-
- const maintenancesQuery = opts.ctx.db.query.maintenance.findMany({
- where: eq(maintenance.pageId, result.id),
- with: { maintenancesToMonitors: { with: { monitor: true } } },
- orderBy: (maintenances, { desc }) => desc(maintenances.from),
- });
-
- const incidentsQuery =
- monitorsId.length > 0
- ? await opts.ctx.db
- .select()
- .from(incidentTable)
- .where(inArray(incidentTable.monitorId, monitorsId))
- .all()
- : [];
- // TODO: monitorsToPagesResult has the result already, no need to query again
- const [monitors, maintenances, incidents] = await Promise.all([
- monitorQuery,
- maintenancesQuery,
- incidentsQuery,
- ]);
-
- return legacy_selectPublicPageSchemaWithRelation.parse({
- ...result,
- // TODO: improve performance and move into SQLite query
- monitors: monitors.sort((a, b) => {
- const aIndex =
- monitorsToPagesResult.find((m) => m.monitor?.id === a.id)
- ?.monitors_to_pages.order || 0;
- const bIndex =
- monitorsToPagesResult.find((m) => m.monitor?.id === b.id)
- ?.monitors_to_pages.order || 0;
- return aIndex - bIndex;
- }),
- incidents,
- statusReports,
- maintenances: maintenances.map((m) => ({
- ...m,
- monitors: m.maintenancesToMonitors.map((m) => m.monitorId),
- })),
- workspacePlan: workspaceResult?.plan,
- });
- }),
getSlugUniqueness: protectedProcedure
.input(z.object({ slug: z.string().toLowerCase() }))
@@ -384,7 +261,6 @@ export const pageRouter = createTRPCRouter({
const data = await opts.ctx.db.query.page.findFirst({
where: and(...whereConditions),
with: {
- monitorsToPages: { with: { monitor: true, monitorGroup: true } },
maintenances: true,
pageComponents: true,
pageComponentGroups: true,
@@ -393,16 +269,6 @@ export const pageRouter = createTRPCRouter({
return selectPageSchema
.extend({
- monitors: z
- .array(
- selectMonitorSchema.extend({
- order: z.number().prefault(0),
- groupOrder: z.number().prefault(0),
- groupId: z.number().nullable(),
- }),
- )
- .prefault([]),
- monitorGroups: z.array(selectMonitorGroupSchema).prefault([]),
pageComponentGroups: z
.array(selectPageComponentGroupSchema)
.prefault([]),
@@ -411,19 +277,6 @@ export const pageRouter = createTRPCRouter({
})
.parse({
...data,
- monitors: data?.monitorsToPages.map((m) => ({
- ...m.monitor,
- order: m.order,
- groupId: m.monitorGroupId,
- groupOrder: m.groupOrder,
- })),
- monitorGroups: Array.from(
- new Map(
- data?.monitorsToPages
- .filter((m) => m.monitorGroup)
- .map((m) => [m.monitorGroup?.id, m.monitorGroup]),
- ).values(),
- ),
pageComponentGroups: data?.pageComponentGroups ?? [],
maintenances: data?.maintenances,
pageComponents: data?.pageComponents,
@@ -804,175 +657,4 @@ export const pageRouter = createTRPCRouter({
.where(and(...whereConditions))
.run();
}),
-
- updateMonitors: protectedProcedure
- .meta({ track: Events.UpdatePage })
- .input(
- z.object({
- id: z.number(),
- monitors: z.array(z.object({ id: z.number(), order: z.number() })),
- groups: z.array(
- z.object({
- // id: z.number(), // we dont need it as we are deleting and adding
- order: z.number(),
- name: z.string(),
- monitors: z.array(z.object({ id: z.number(), order: z.number() })),
- }),
- ),
- }),
- )
- .mutation(async (opts) => {
- const monitorIds = opts.input.monitors.map((m) => m.id);
- const groupMonitorIds = opts.input.groups.flatMap((g) =>
- g.monitors.map((m) => m.id),
- );
-
- const allMonitorIds = [...new Set([...monitorIds, ...groupMonitorIds])];
- // check if the monitors are in the workspace
- const monitors = await opts.ctx.db.query.monitor.findMany({
- where: and(
- inArray(monitor.id, allMonitorIds),
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- ),
- });
-
- if (monitors.length !== allMonitorIds.length) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You don't have access to all the monitors.",
- });
- }
-
- await opts.ctx.db.transaction(async (tx) => {
- // Get existing state
- const existingMonitorsToPages = await tx
- .select()
- .from(monitorsToPages)
- .where(eq(monitorsToPages.pageId, opts.input.id))
- .all();
-
- const existingGroups = await tx.query.monitorGroup.findMany({
- where: eq(monitorGroup.pageId, opts.input.id),
- });
- const existingGroupIds = existingGroups.map((g) => g.id);
-
- // Calculate what monitors are in the new input vs existing
- const existingMonitorIds = existingMonitorsToPages.map(
- (m) => m.monitorId,
- );
-
- // Find monitors that are being removed (in DB but not in input)
- const removedMonitorIds = existingMonitorIds.filter(
- (id) => !allMonitorIds.includes(id),
- );
-
- // Delete removed monitors from monitorsToPages and page components
- if (removedMonitorIds.length > 0) {
- await tx
- .delete(monitorsToPages)
- .where(
- and(
- eq(monitorsToPages.pageId, opts.input.id),
- inArray(monitorsToPages.monitorId, removedMonitorIds),
- ),
- );
-
- // Sync delete to page components
- for (const monitorId of removedMonitorIds) {
- await syncMonitorsToPageDelete(tx, {
- monitorId,
- pageId: opts.input.id,
- });
- }
- }
-
- // Clear monitorGroupId from all monitorsToPages before deleting groups
- // This prevents foreign key constraint errors
- if (existingGroupIds.length > 0) {
- await tx
- .update(monitorsToPages)
- .set({ monitorGroupId: null })
- .where(
- and(
- eq(monitorsToPages.pageId, opts.input.id),
- inArray(monitorsToPages.monitorGroupId, existingGroupIds),
- ),
- );
- }
-
- // Handle groups: delete old groups and create new ones
- if (existingGroupIds.length > 0) {
- await tx
- .delete(monitorGroup)
- .where(eq(monitorGroup.pageId, opts.input.id));
-
- // Sync delete page component groups
- await syncMonitorGroupDeleteMany(tx, existingGroupIds);
- }
-
- // Create new monitor groups
- let monitorGroups: Array<{ id: number; name: string }> = [];
- if (opts.input.groups.length > 0) {
- monitorGroups = await tx
- .insert(monitorGroup)
- .values(
- opts.input.groups.map((g) => ({
- workspaceId: opts.ctx.workspace.id,
- pageId: opts.input.id,
- name: g.name,
- })),
- )
- .returning();
-
- // Sync new monitor groups to page component groups
- for (const group of monitorGroups) {
- await syncMonitorGroupInsert(tx, {
- id: group.id,
- workspaceId: opts.ctx.workspace.id,
- pageId: opts.input.id,
- name: group.name,
- });
- }
- }
-
- // Prepare values for upsert - both grouped and ungrouped monitors
- const groupMonitorValues = opts.input.groups.flatMap((g, i) =>
- g.monitors.map((m) => ({
- pageId: opts.input.id,
- monitorId: m.id,
- order: g.order,
- monitorGroupId: monitorGroups[i].id,
- groupOrder: m.order,
- })),
- );
-
- const monitorValues = opts.input.monitors.map((m) => ({
- pageId: opts.input.id,
- monitorId: m.id,
- order: m.order,
- monitorGroupId: null as number | null,
- groupOrder: 0,
- }));
-
- const allValues = [...groupMonitorValues, ...monitorValues];
-
- // Upsert all monitors (update existing, insert new)
- if (allValues.length > 0) {
- await tx
- .insert(monitorsToPages)
- .values(allValues)
- .onConflictDoUpdate({
- target: [monitorsToPages.monitorId, monitorsToPages.pageId],
- set: {
- order: sql.raw("excluded.`order`"),
- monitorGroupId: sql.raw("excluded.`monitor_group_id`"),
- groupOrder: sql.raw("excluded.`group_order`"),
- },
- });
-
- // Sync upsert to page components (updates existing, inserts new)
- await syncMonitorsToPageUpsertMany(tx, allValues);
- }
- });
- }),
});
diff --git a/packages/api/src/router/pageComponent.ts b/packages/api/src/router/pageComponent.ts
index 7b7431b48..614b362c4 100644
--- a/packages/api/src/router/pageComponent.ts
+++ b/packages/api/src/router/pageComponent.ts
@@ -2,11 +2,16 @@ import { z } from "zod";
import { type SQL, and, asc, desc, eq, inArray, sql } from "@openstatus/db";
import {
- page,
pageComponent,
pageComponentGroup,
+ selectMaintenanceSchema,
+ selectMonitorSchema,
+ selectPageComponentGroupSchema,
+ selectPageComponentSchema,
+ selectStatusReportSchema,
} from "@openstatus/db/src/schema";
+import { Events } from "@openstatus/analytics";
import { TRPCError } from "@trpc/server";
import { createTRPCRouter, protectedProcedure } from "../trpc";
@@ -29,7 +34,7 @@ export const pageComponentRouter = createTRPCRouter({
whereConditions.push(eq(pageComponent.pageId, opts.input.pageId));
}
- const query = opts.ctx.db.query.pageComponent.findMany({
+ const result = await opts.ctx.db.query.pageComponent.findMany({
where: and(...whereConditions),
orderBy:
opts.input?.order === "desc"
@@ -38,15 +43,49 @@ export const pageComponentRouter = createTRPCRouter({
with: {
monitor: true,
group: true,
+ statusReportsToPageComponents: {
+ with: {
+ statusReport: true,
+ },
+ orderBy: (statusReportsToPageComponents, { desc }) =>
+ desc(statusReportsToPageComponents.createdAt),
+ },
+ maintenancesToPageComponents: {
+ with: {
+ maintenance: true,
+ },
+ orderBy: (maintenancesToPageComponents, { desc }) =>
+ desc(maintenancesToPageComponents.createdAt),
+ },
},
});
- const result = await query;
-
- return result;
+ // Transform and parse the result to flatten the junction tables
+ return selectPageComponentSchema
+ .extend({
+ monitor: selectMonitorSchema.nullish(),
+ group: selectPageComponentGroupSchema.nullish(),
+ statusReports: z.array(selectStatusReportSchema).default([]),
+ maintenances: z.array(selectMaintenanceSchema).default([]),
+ })
+ .array()
+ .parse(
+ result.map((component) => ({
+ ...component,
+ statusReports:
+ component.statusReportsToPageComponents?.map(
+ (sr) => sr.statusReport,
+ ) ?? [],
+ maintenances:
+ component.maintenancesToPageComponents?.map(
+ (m) => m.maintenance,
+ ) ?? [],
+ })),
+ );
}),
delete: protectedProcedure
+ .meta({ track: Events.DeletePageComponent, trackProps: ["id"] })
.input(z.object({ id: z.number() }))
.mutation(async (opts) => {
return await opts.ctx.db
@@ -60,85 +99,8 @@ export const pageComponentRouter = createTRPCRouter({
.returning();
}),
- new: protectedProcedure
- .input(
- z.object({
- pageId: z.number(),
- name: z.string().min(1),
- description: z.string().optional(),
- type: z.enum(["external", "monitor"]).default("monitor"),
- monitorId: z.number().optional(),
- order: z.number().optional(),
- groupId: z.number().optional(),
- }),
- )
- .mutation(async (opts) => {
- const _page = await opts.ctx.db.query.page.findFirst({
- where: and(
- eq(page.id, opts.input.pageId),
- eq(page.workspaceId, opts.ctx.workspace.id),
- ),
- });
-
- if (!_page) {
- throw new TRPCError({ code: "NOT_FOUND", message: "Page not found" });
- }
-
- const newPageComponent = await opts.ctx.db
- .insert(pageComponent)
- .values({
- pageId: opts.input.pageId,
- workspaceId: opts.ctx.workspace.id,
- name: opts.input.name,
- description: opts.input.description,
- type: opts.input.type,
- monitorId: opts.input.monitorId,
- order: opts.input.order,
- groupId: opts.input.groupId,
- })
- .returning()
- .get();
-
- return newPageComponent;
- }),
-
- update: protectedProcedure
- .input(
- z.object({
- id: z.number(),
- name: z.string().min(1),
- description: z.string().optional(),
- type: z.enum(["external", "monitor"]).optional(),
- monitorId: z.number().optional(),
- order: z.number().optional(),
- groupId: z.number().optional(),
- }),
- )
- .mutation(async (opts) => {
- const whereConditions: SQL[] = [
- eq(pageComponent.id, opts.input.id),
- eq(pageComponent.workspaceId, opts.ctx.workspace.id),
- ];
-
- const _pageComponent = await opts.ctx.db
- .update(pageComponent)
- .set({
- name: opts.input.name,
- description: opts.input.description,
- type: opts.input.type,
- monitorId: opts.input.monitorId,
- order: opts.input.order,
- groupId: opts.input.groupId,
- updatedAt: new Date(),
- })
- .where(and(...whereConditions))
- .returning()
- .get();
-
- return _pageComponent;
- }),
-
updateOrder: protectedProcedure
+ .meta({ track: Events.UpdatePageComponentOrder, trackProps: ["pageId"] })
.input(
z.object({
pageId: z.number(),
@@ -149,7 +111,7 @@ export const pageComponentRouter = createTRPCRouter({
order: z.number(),
name: z.string(),
description: z.string().nullish(),
- type: z.enum(["monitor", "external"]),
+ type: z.enum(["monitor", "static"]),
}),
),
groups: z.array(
@@ -163,7 +125,7 @@ export const pageComponentRouter = createTRPCRouter({
order: z.number(),
name: z.string(),
description: z.string().nullish(),
- type: z.enum(["monitor", "external"]),
+ type: z.enum(["monitor", "static"]),
}),
),
}),
@@ -172,6 +134,8 @@ export const pageComponentRouter = createTRPCRouter({
)
.mutation(async (opts) => {
await opts.ctx.db.transaction(async (tx) => {
+ const pageComponentLimit = opts.ctx.workspace.limits["page-components"];
+
// Get existing state
const existingComponents = await tx
.select()
@@ -184,6 +148,13 @@ export const pageComponentRouter = createTRPCRouter({
)
.all();
+ if (existingComponents.length >= pageComponentLimit) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You reached your page component limits.",
+ });
+ }
+
const existingGroups = await tx
.select()
.from(pageComponentGroup)
@@ -209,22 +180,22 @@ export const pageComponentRouter = createTRPCRouter({
),
] as number[];
- // Collect IDs for external components that have IDs in input
- const inputExternalComponentIds = [
+ // Collect IDs for static components that have IDs in input
+ const inputStaticComponentIds = [
...opts.input.components
- .filter((c) => c.type === "external" && c.id)
+ .filter((c) => c.type === "static" && c.id)
.map((c) => c.id),
...opts.input.groups.flatMap((g) =>
g.components
- .filter((c) => c.type === "external" && c.id)
+ .filter((c) => c.type === "static" && c.id)
.map((c) => c.id),
),
] as number[];
// Find components that are being removed
// For monitor components: those with monitorIds not in the input
- // For external components with IDs: those with IDs not in the input
- // For external components without IDs in input: delete all existing external components
+ // For static components with IDs: those with IDs not in the input
+ // For static components without IDs in input: delete all existing static components
const removedMonitorComponents = existingComponents.filter(
(c) =>
c.type === "monitor" &&
@@ -232,32 +203,32 @@ export const pageComponentRouter = createTRPCRouter({
!inputMonitorIds.includes(c.monitorId),
);
- const hasExternalComponentsInInput =
- opts.input.components.some((c) => c.type === "external") ||
+ const hasStaticComponentsInInput =
+ opts.input.components.some((c) => c.type === "static") ||
opts.input.groups.some((g) =>
- g.components.some((c) => c.type === "external"),
+ g.components.some((c) => c.type === "static"),
);
- // If input has external components but they don't have IDs, we need to delete old ones
- // If input has external components with IDs, only delete those not in input
- const removedExternalComponents = existingComponents.filter((c) => {
- if (c.type !== "external") return false;
- // If we have external components in input
- if (hasExternalComponentsInInput) {
+ // If input has static components but they don't have IDs, we need to delete old ones
+ // If input has static components with IDs, only delete those not in input
+ const removedStaticComponents = existingComponents.filter((c) => {
+ if (c.type !== "static") return false;
+ // If we have static components in input
+ if (hasStaticComponentsInInput) {
// If the input has IDs, only remove those not in the list
- if (inputExternalComponentIds.length > 0) {
- return !inputExternalComponentIds.includes(c.id);
+ if (inputStaticComponentIds.length > 0) {
+ return !inputStaticComponentIds.includes(c.id);
}
- // If input doesn't have IDs, remove all existing external components
+ // If input doesn't have IDs, remove all existing static components
return true;
}
- // If no external components in input at all, remove existing ones
+ // If no static components in input at all, remove existing ones
return true;
});
const removedComponentIds = [
...removedMonitorComponents.map((c) => c.id),
- ...removedExternalComponents.map((c) => c.id),
+ ...removedStaticComponents.map((c) => c.id),
];
// Delete removed components
@@ -350,12 +321,12 @@ export const pageComponentRouter = createTRPCRouter({
...standaloneComponentValues,
];
- // Separate monitor and external components for different upsert strategies
+ // Separate monitor and static components for different upsert strategies
const monitorComponents = allComponentValues.filter(
(c) => c.type === "monitor" && c.monitorId,
);
- const externalComponents = allComponentValues.filter(
- (c) => c.type === "external",
+ const staticComponents = allComponentValues.filter(
+ (c) => c.type === "static",
);
// Upsert monitor components using SQL-level conflict resolution
@@ -377,11 +348,11 @@ export const pageComponentRouter = createTRPCRouter({
});
}
- // Handle external components
+ // Handle static components
// If they have IDs, update them; otherwise insert new ones
- for (const componentValue of externalComponents) {
+ for (const componentValue of staticComponents) {
if (componentValue.id) {
- // Update existing external component (preserves ID and relationships)
+ // Update existing static component (preserves ID and relationships)
await tx
.update(pageComponent)
.set({
@@ -402,7 +373,7 @@ export const pageComponentRouter = createTRPCRouter({
),
);
} else {
- // Insert new external component
+ // Insert new static component
await tx.insert(pageComponent).values({
pageId: componentValue.pageId,
workspaceId: componentValue.workspaceId,
diff --git a/packages/api/src/router/statusPage.e2e.test.ts b/packages/api/src/router/statusPage.e2e.test.ts
index d69fb0b01..0074729b2 100644
--- a/packages/api/src/router/statusPage.e2e.test.ts
+++ b/packages/api/src/router/statusPage.e2e.test.ts
@@ -829,7 +829,7 @@ describe("statusPage.get endpoint validation", () => {
expect(tracker.component).toHaveProperty("name");
expect(tracker.component).toHaveProperty("status");
expect(tracker.component).toHaveProperty("type");
- expect(["monitor", "external"]).toContain(tracker.component.type);
+ expect(["monitor", "static"]).toContain(tracker.component.type);
expect(["success", "degraded", "error", "info"]).toContain(
tracker.component.status,
);
diff --git a/packages/api/src/router/statusPage.ts b/packages/api/src/router/statusPage.ts
index 3e8327193..602b6089f 100644
--- a/packages/api/src/router/statusPage.ts
+++ b/packages/api/src/router/statusPage.ts
@@ -10,6 +10,7 @@ import {
selectMaintenancePageSchema,
selectPageComponentWithMonitorRelation,
selectPublicMonitorSchema,
+ selectPublicPageLightSchemaWithRelation,
selectPublicPageSchemaWithRelation,
selectStatusReportPageSchema,
selectWorkspaceSchema,
@@ -125,7 +126,7 @@ export const statusPageRouter = createTRPCRouter({
const monitorComponents = pageComponents.filter(isMonitorComponent);
- // Transform all page components (both monitor and external types)
+ // Transform all page components (both monitor and static types)
const components = pageComponents.map((c) => {
const events = getEvents({
maintenances: _page.maintenances,
@@ -139,8 +140,8 @@ export const statusPageRouter = createTRPCRouter({
// Calculate status based on component type
let status: "success" | "degraded" | "error" | "info";
- if (c.type === "external") {
- // External: only reports and maintenances affect status
+ if (c.type === "static") {
+ // Static: only reports and maintenances affect status
status = events.some((e) => e.type === "report" && !e.to)
? "degraded"
: events.some(
@@ -348,7 +349,6 @@ export const statusPageRouter = createTRPCRouter({
const whiteLabel = ws.data?.limits["white-label"] ?? false;
- // Transform statusReports to include monitorsToStatusReports format
const statusReports = _page.statusReports.sort((a, b) => {
// Sort reports without updates to the beginning
if (
@@ -388,6 +388,81 @@ export const statusPageRouter = createTRPCRouter({
});
}),
+ getLight: publicProcedure
+ .input(z.object({ slug: z.string().toLowerCase() }))
+ .query(async (opts) => {
+ if (!opts.input.slug) return null;
+
+ // Single query with all relations
+ const _page = await opts.ctx.db.query.page.findFirst({
+ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,
+ with: {
+ workspace: true,
+ statusReports: {
+ with: {
+ statusReportUpdates: {
+ orderBy: (reports, { desc }) => desc(reports.date),
+ },
+ statusReportsToPageComponents: { with: { pageComponent: true } },
+ },
+ },
+ maintenances: {
+ with: {
+ maintenancesToPageComponents: { with: { pageComponent: true } },
+ },
+ orderBy: (maintenances, { desc }) => desc(maintenances.from),
+ },
+ pageComponents: {
+ with: {
+ monitor: { with: { incidents: true } },
+ group: true,
+ },
+ orderBy: (pageComponents, { asc }) => asc(pageComponents.order),
+ },
+ pageComponentGroups: true,
+ },
+ });
+
+ if (!_page) return null;
+
+ // Extract monitor components for backwards compatibility
+ const monitorComponents = _page.pageComponents.filter(
+ (c) =>
+ c.type === "monitor" &&
+ c.monitor &&
+ c.monitor.active &&
+ !c.monitor.deletedAt,
+ );
+
+ // Build legacy monitors array (sorted by order)
+ const monitors = monitorComponents
+ .map((c) => ({
+ ...c.monitor,
+ name: c.monitor?.externalName ?? c.monitor?.name ?? "",
+ }))
+ .sort((a, b) => {
+ const aComp = monitorComponents.find((m) => m.monitor?.id === a.id);
+ const bComp = monitorComponents.find((m) => m.monitor?.id === b.id);
+ return (aComp?.order ?? 0) - (bComp?.order ?? 0);
+ });
+
+ // Extract all incidents from monitor components
+ const incidents = monitorComponents.flatMap(
+ (c) => c.monitor?.incidents ?? [],
+ );
+
+ return selectPublicPageLightSchemaWithRelation.parse({
+ ..._page,
+ monitors,
+ incidents,
+ statusReports: _page.statusReports,
+ maintenances: _page.maintenances,
+ pageComponents: _page.pageComponents,
+ pageComponentGroups: _page.pageComponentGroups,
+ workspacePlan: _page.workspace.plan,
+ });
+ }),
+
getMaintenance: publicProcedure
.input(z.object({ slug: z.string().toLowerCase(), id: z.number() }))
.query(async (opts) => {
@@ -555,7 +630,7 @@ export const statusPageRouter = createTRPCRouter({
lookbackPeriod,
);
} else {
- // External components, manual mode, or NOOP mode: use synthetic data
+ // Static components, manual mode, or NOOP mode: use synthetic data
filledData = fillStatusDataFor45DaysNoop({
errorDays: [],
degradedDays: [],
@@ -563,11 +638,11 @@ export const statusPageRouter = createTRPCRouter({
});
}
- // External components always use manual mode since they don't have real monitoring data
+ // Static components always use manual mode since they don't have real monitoring data
const effectiveBarType =
- c.type === "external" ? "manual" : opts.input.barType;
+ c.type === "static" ? "manual" : opts.input.barType;
const effectiveCardType =
- c.type === "external" ? "manual" : opts.input.cardType;
+ c.type === "static" ? "manual" : opts.input.cardType;
const processedData = setDataByType({
events,
diff --git a/packages/api/src/router/statusPage.utils.test.ts b/packages/api/src/router/statusPage.utils.test.ts
index 596c20aec..328ed7fbd 100644
--- a/packages/api/src/router/statusPage.utils.test.ts
+++ b/packages/api/src/router/statusPage.utils.test.ts
@@ -915,7 +915,7 @@ describe("getEvents - pageComponent filtering", () => {
id,
workspaceId: 1,
pageId: 1,
- type: monitorId ? ("monitor" as const) : ("external" as const),
+ type: monitorId ? ("monitor" as const) : ("static" as const),
monitorId: monitorId ?? null,
name: `Component ${id}`,
description: null,
@@ -1060,14 +1060,14 @@ describe("getEvents - pageComponent filtering", () => {
expect(reportEvents.map((e) => e.id).sort()).toEqual([1, 3]);
});
- it("should exclude incidents for external components", () => {
+ it("should exclude incidents for static components", () => {
const incidents = [createMockIncident(1, 10), createMockIncident(2, 20)];
const events = getEvents({
maintenances: [],
incidents,
reports: [],
- componentType: "external",
+ componentType: "static",
pastDays: 365,
});
diff --git a/packages/api/src/router/statusPage.utils.ts b/packages/api/src/router/statusPage.utils.ts
index 7071d17d0..bc383a0ee 100644
--- a/packages/api/src/router/statusPage.utils.ts
+++ b/packages/api/src/router/statusPage.utils.ts
@@ -2,6 +2,7 @@ import type {
Incident,
Maintenance,
PageComponent,
+ PageComponentType,
PageComponentWithMonitorRelation,
StatusReport,
StatusReportUpdate,
@@ -243,7 +244,7 @@ export function getEvents({
})[];
pageComponentId?: number;
monitorId?: number;
- componentType?: "monitor" | "external";
+ componentType?: PageComponentType;
pastDays?: number;
}): Event[] {
const events: Event[] = [];
@@ -278,8 +279,8 @@ export function getEvents({
});
// Filter incidents - only for monitor-type components
- // External components don't have incidents
- if (componentType !== "external") {
+ // Static components don't have incidents
+ if (componentType !== "static") {
incidents
.filter((incident) =>
monitorId ? incident.monitorId === monitorId : true,
diff --git a/packages/api/src/router/sync.test.ts b/packages/api/src/router/sync.test.ts
index 207ce66ed..c1594c72d 100644
--- a/packages/api/src/router/sync.test.ts
+++ b/packages/api/src/router/sync.test.ts
@@ -16,6 +16,7 @@ import {
statusReportsToPageComponents,
} from "@openstatus/db/src/schema";
import { flyRegions } from "@openstatus/db/src/schema/constants";
+import { syncMonitorsToPageInsert } from "@openstatus/db/src/sync";
import { appRouter } from "../root";
import { createInnerTRPCContext } from "../trpc";
@@ -192,180 +193,27 @@ afterAll(async () => {
.where(eq(monitor.name, `${TEST_PREFIX}-deletable-monitor`));
});
-describe("Sync: monitors_to_pages -> page_component", () => {
- test("Creating monitor-to-page relation syncs to page_component", async () => {
- const ctx = getTestContext();
- const caller = appRouter.createCaller(ctx);
-
- // Update monitor to add it to the test page
- await caller.monitor.updateStatusPages({
- id: testMonitorId,
- statusPages: [testPageId],
- });
-
- // Verify monitors_to_pages was created
- const monitorToPage = await db.query.monitorsToPages.findFirst({
- where: and(
- eq(monitorsToPages.monitorId, testMonitorId),
- eq(monitorsToPages.pageId, testPageId),
- ),
- });
- expect(monitorToPage).toBeDefined();
-
- // Verify page_component was synced
- const component = await db.query.pageComponent.findFirst({
- where: and(
- eq(pageComponent.monitorId, testMonitorId),
- eq(pageComponent.pageId, testPageId),
- ),
- });
- expect(component).toBeDefined();
- expect(component?.type).toBe("monitor");
- expect(component?.workspaceId).toBe(1);
- });
-
- test("Removing monitor-to-page relation syncs delete to page_component", async () => {
- const ctx = getTestContext();
- const caller = appRouter.createCaller(ctx);
-
- // First add the monitor to page if not already
- await caller.monitor.updateStatusPages({
- id: testMonitorId,
- statusPages: [testPageId],
- });
-
- // Verify page_component exists
- let component = await db.query.pageComponent.findFirst({
- where: and(
- eq(pageComponent.monitorId, testMonitorId),
- eq(pageComponent.pageId, testPageId),
- ),
- });
- expect(component).toBeDefined();
-
- // Remove monitor from page
- await caller.monitor.updateStatusPages({
- id: testMonitorId,
- statusPages: [],
- });
-
- // Verify page_component was deleted
- component = await db.query.pageComponent.findFirst({
- where: and(
- eq(pageComponent.monitorId, testMonitorId),
- eq(pageComponent.pageId, testPageId),
- ),
- });
- expect(component).toBeUndefined();
- });
-});
-
-describe("Sync: page.updateMonitors -> page_component and page_component_groups", () => {
- test("Adding monitors with groups syncs to page_component and page_component_groups", async () => {
- const ctx = getTestContext();
- const caller = appRouter.createCaller(ctx);
-
- // Update page with monitor in a group
- await caller.page.updateMonitors({
- id: testPageId,
- monitors: [],
- groups: [
- {
- name: `${TEST_PREFIX}-group`,
- order: 0,
- monitors: [{ id: testMonitorId, order: 0 }],
- },
- ],
- });
-
- // Verify monitor_group was created
- const group = await db.query.monitorGroup.findFirst({
- where: and(
- eq(monitorGroup.pageId, testPageId),
- eq(monitorGroup.name, `${TEST_PREFIX}-group`),
- ),
- });
- expect(group).toBeDefined();
-
- if (!group) {
- throw new Error("Group not found");
- }
-
- // Verify page_component_groups was synced
- const componentGroup = await db.query.pageComponentGroup.findFirst({
- where: eq(pageComponentGroup.id, group.id),
- });
- expect(componentGroup).toBeDefined();
- expect(componentGroup?.name).toBe(`${TEST_PREFIX}-group`);
- expect(componentGroup?.pageId).toBe(testPageId);
-
- // Verify page_component was synced with group reference
- const component = await db.query.pageComponent.findFirst({
- where: and(
- eq(pageComponent.monitorId, testMonitorId),
- eq(pageComponent.pageId, testPageId),
- ),
- });
- expect(component).toBeDefined();
- expect(component?.groupId).toBe(group.id);
- });
-
- test("Updating page monitors syncs changes to page_component", async () => {
- const ctx = getTestContext();
- const caller = appRouter.createCaller(ctx);
-
- // First, set up with a group
- await caller.page.updateMonitors({
- id: testPageId,
- monitors: [],
- groups: [
- {
- name: `${TEST_PREFIX}-group`,
- order: 0,
- monitors: [{ id: testMonitorId, order: 0 }],
- },
- ],
- });
-
- // Now update to remove the group and add monitor directly
- await caller.page.updateMonitors({
- id: testPageId,
- monitors: [{ id: testMonitorId, order: 0 }],
- groups: [],
- });
-
- // Verify monitor_group was deleted
- const group = await db.query.monitorGroup.findFirst({
- where: and(
- eq(monitorGroup.pageId, testPageId),
- eq(monitorGroup.name, `${TEST_PREFIX}-group`),
- ),
- });
- expect(group).toBeUndefined();
-
- // Verify page_component still exists but without group
- const component = await db.query.pageComponent.findFirst({
- where: and(
- eq(pageComponent.monitorId, testMonitorId),
- eq(pageComponent.pageId, testPageId),
- ),
- });
- expect(component).toBeDefined();
- expect(component?.groupId).toBeNull();
- });
-});
+describe("Sync: monitors_to_pages -> page_component", () => {});
describe("Sync: maintenance_to_monitor -> maintenance_to_page_component", () => {
let testMaintenanceId: number;
beforeAll(async () => {
- const ctx = getTestContext();
- const caller = appRouter.createCaller(ctx);
-
- // Ensure monitor is on the page first
- await caller.monitor.updateStatusPages({
- id: testMonitorId,
- statusPages: [testPageId],
+ // Ensure monitor is on the page first - use manual db call
+ await db
+ .insert(monitorsToPages)
+ .values({
+ monitorId: testMonitorId,
+ pageId: testPageId,
+ order: 0,
+ })
+ .onConflictDoNothing();
+
+ // Sync to page_component
+ await syncMonitorsToPageInsert(db, {
+ monitorId: testMonitorId,
+ pageId: testPageId,
+ order: 0,
});
});
@@ -477,12 +325,23 @@ describe("Sync: status_report_to_monitors -> status_report_to_page_component", (
beforeAll(async () => {
const ctx = getTestContext();
- const caller = appRouter.createCaller(ctx);
+ const _caller = appRouter.createCaller(ctx);
// Ensure monitor is on the page first
- await caller.monitor.updateStatusPages({
- id: testMonitorId,
- statusPages: [testPageId],
+ await db
+ .insert(monitorsToPages)
+ .values({
+ monitorId: testMonitorId,
+ pageId: testPageId,
+ order: 0,
+ })
+ .onConflictDoNothing();
+
+ // Sync to page_component
+ await syncMonitorsToPageInsert(db, {
+ monitorId: testMonitorId,
+ pageId: testPageId,
+ order: 0,
});
});
@@ -608,9 +467,20 @@ describe("Sync: monitor deletion cascades to page_component tables", () => {
deletableMonitorId = deletableMonitor.id;
// Add monitor to page
- await caller.monitor.updateStatusPages({
- id: deletableMonitorId,
- statusPages: [testPageId],
+ await db
+ .insert(monitorsToPages)
+ .values({
+ monitorId: deletableMonitorId,
+ pageId: testPageId,
+ order: 0,
+ })
+ .onConflictDoNothing();
+
+ // Sync to page_component
+ await syncMonitorsToPageInsert(db, {
+ monitorId: deletableMonitorId,
+ pageId: testPageId,
+ order: 0,
});
});
diff --git a/packages/api/src/router/workspace.ts b/packages/api/src/router/workspace.ts
index bb7d5a09a..0cbe32146 100644
--- a/packages/api/src/router/workspace.ts
+++ b/packages/api/src/router/workspace.ts
@@ -26,7 +26,11 @@ export const workspaceRouter = createTRPCRouter({
const result = await opts.ctx.db.query.workspace.findFirst({
where: and(...whereConditions),
with: {
- pages: true,
+ pages: {
+ with: {
+ pageComponents: true,
+ },
+ },
monitors: {
where: isNull(monitor.deletedAt),
},
@@ -40,6 +44,8 @@ export const workspaceRouter = createTRPCRouter({
monitors: result?.monitors?.length || 0,
notifications: result?.notifications?.length || 0,
pages: result?.pages?.length || 0,
+ pageComponents:
+ result?.pages?.flatMap((page) => page.pageComponents)?.length || 0,
// checks: result?.checks?.length || 0,
checks: 0,
},
diff --git a/packages/db/drizzle/0055_spicy_bastion.sql b/packages/db/drizzle/0055_spicy_bastion.sql
new file mode 100644
index 000000000..d032fecbc
--- /dev/null
+++ b/packages/db/drizzle/0055_spicy_bastion.sql
@@ -0,0 +1,26 @@
+PRAGMA foreign_keys=OFF;--> statement-breakpoint
+CREATE TABLE `__new_page_component` (
+ `id` integer PRIMARY KEY NOT NULL,
+ `workspace_id` integer NOT NULL,
+ `page_id` integer NOT NULL,
+ `type` text DEFAULT 'monitor' NOT NULL,
+ `monitor_id` integer,
+ `name` text NOT NULL,
+ `description` text,
+ `order` integer DEFAULT 0,
+ `group_id` integer,
+ `group_order` integer DEFAULT 0,
+ `created_at` integer DEFAULT (strftime('%s', 'now')),
+ `updated_at` integer DEFAULT (strftime('%s', 'now')),
+ FOREIGN KEY (`workspace_id`) REFERENCES `workspace`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`page_id`) REFERENCES `page`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`monitor_id`) REFERENCES `monitor`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`group_id`) REFERENCES `page_component_groups`(`id`) ON UPDATE no action ON DELETE set null,
+ CONSTRAINT "page_component_type_check" CHECK("__new_page_component"."type" = 'monitor' AND "__new_page_component"."monitor_id" IS NOT NULL OR "__new_page_component"."type" = 'static' AND "__new_page_component"."monitor_id" IS NULL)
+);
+--> statement-breakpoint
+INSERT INTO `__new_page_component`("id", "workspace_id", "page_id", "type", "monitor_id", "name", "description", "order", "group_id", "group_order", "created_at", "updated_at") SELECT "id", "workspace_id", "page_id", "type", "monitor_id", "name", "description", "order", "group_id", "group_order", "created_at", "updated_at" FROM `page_component`;--> statement-breakpoint
+DROP TABLE `page_component`;--> statement-breakpoint
+ALTER TABLE `__new_page_component` RENAME TO `page_component`;--> statement-breakpoint
+PRAGMA foreign_keys=ON;--> statement-breakpoint
+CREATE UNIQUE INDEX `page_component_page_id_monitor_id_unique` ON `page_component` (`page_id`,`monitor_id`);
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0055_snapshot.json b/packages/db/drizzle/meta/0055_snapshot.json
new file mode 100644
index 000000000..052451621
--- /dev/null
+++ b/packages/db/drizzle/meta/0055_snapshot.json
@@ -0,0 +1,3459 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "4f344b53-2e8a-400d-be39-8018d77ff0a9",
+ "prevId": "fa90adb7-69d9-419c-baf9-3a73922e9e43",
+ "tables": {
+ "workspace": {
+ "name": "workspace",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripe_id": {
+ "name": "stripe_id",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "plan": {
+ "name": "plan",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ends_at": {
+ "name": "ends_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "paid_until": {
+ "name": "paid_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limits": {
+ "name": "limits",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "workspace_slug_unique": {
+ "name": "workspace_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "workspace_stripe_id_unique": {
+ "name": "workspace_stripe_id_unique",
+ "columns": [
+ "stripe_id"
+ ],
+ "isUnique": true
+ },
+ "workspace_id_dsn_unique": {
+ "name": "workspace_id_dsn_unique",
+ "columns": [
+ "id",
+ "dsn"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "account": {
+ "name": "account",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_account_id": {
+ "name": "provider_account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_state": {
+ "name": "session_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "account_provider_provider_account_id_pk": {
+ "columns": [
+ "provider",
+ "provider_account_id"
+ ],
+ "name": "account_provider_provider_account_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session": {
+ "name": "session",
+ "columns": {
+ "session_token": {
+ "name": "session_token",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user": {
+ "name": "user",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tenant_id": {
+ "name": "tenant_id",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_name": {
+ "name": "first_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "last_name": {
+ "name": "last_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "photo_url": {
+ "name": "photo_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "user_tenant_id_unique": {
+ "name": "user_tenant_id_unique",
+ "columns": [
+ "tenant_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users_to_workspaces": {
+ "name": "users_to_workspaces",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "users_to_workspaces_user_id_user_id_fk": {
+ "name": "users_to_workspaces_user_id_user_id_fk",
+ "tableFrom": "users_to_workspaces",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "users_to_workspaces_workspace_id_workspace_id_fk": {
+ "name": "users_to_workspaces_workspace_id_workspace_id_fk",
+ "tableFrom": "users_to_workspaces",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "users_to_workspaces_user_id_workspace_id_pk": {
+ "columns": [
+ "user_id",
+ "workspace_id"
+ ],
+ "name": "users_to_workspaces_user_id_workspace_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "verification_token": {
+ "name": "verification_token",
+ "columns": {
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "verification_token_identifier_token_pk": {
+ "columns": [
+ "identifier",
+ "token"
+ ],
+ "name": "verification_token_identifier_token_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "status_report_to_monitors": {
+ "name": "status_report_to_monitors",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status_report_id": {
+ "name": "status_report_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_to_monitors_monitor_id_monitor_id_fk": {
+ "name": "status_report_to_monitors_monitor_id_monitor_id_fk",
+ "tableFrom": "status_report_to_monitors",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "status_report_to_monitors_status_report_id_status_report_id_fk": {
+ "name": "status_report_to_monitors_status_report_id_status_report_id_fk",
+ "tableFrom": "status_report_to_monitors",
+ "tableTo": "status_report",
+ "columnsFrom": [
+ "status_report_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "status_report_to_monitors_monitor_id_status_report_id_pk": {
+ "columns": [
+ "monitor_id",
+ "status_report_id"
+ ],
+ "name": "status_report_to_monitors_monitor_id_status_report_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "status_report": {
+ "name": "status_report",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_workspace_id_workspace_id_fk": {
+ "name": "status_report_workspace_id_workspace_id_fk",
+ "tableFrom": "status_report",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "status_report_page_id_page_id_fk": {
+ "name": "status_report_page_id_page_id_fk",
+ "tableFrom": "status_report",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "status_report_update": {
+ "name": "status_report_update",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status_report_id": {
+ "name": "status_report_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_update_status_report_id_status_report_id_fk": {
+ "name": "status_report_update_status_report_id_status_report_id_fk",
+ "tableFrom": "status_report_update",
+ "tableTo": "status_report",
+ "columnsFrom": [
+ "status_report_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "integration": {
+ "name": "integration",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "credential": {
+ "name": "credential",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "external_id": {
+ "name": "external_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "data": {
+ "name": "data",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "integration_workspace_id_workspace_id_fk": {
+ "name": "integration_workspace_id_workspace_id_fk",
+ "tableFrom": "integration",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "page": {
+ "name": "page",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "custom_domain": {
+ "name": "custom_domain",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "published": {
+ "name": "published",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "force_theme": {
+ "name": "force_theme",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'system'"
+ },
+ "password": {
+ "name": "password",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password_protected": {
+ "name": "password_protected",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "access_type": {
+ "name": "access_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'public'"
+ },
+ "auth_email_domains": {
+ "name": "auth_email_domains",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "homepage_url": {
+ "name": "homepage_url",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "contact_url": {
+ "name": "contact_url",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "legacy_page": {
+ "name": "legacy_page",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "configuration": {
+ "name": "configuration",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "show_monitor_values": {
+ "name": "show_monitor_values",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "page_slug_unique": {
+ "name": "page_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "page_workspace_id_workspace_id_fk": {
+ "name": "page_workspace_id_workspace_id_fk",
+ "tableFrom": "page",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor": {
+ "name": "monitor",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'http'"
+ },
+ "periodicity": {
+ "name": "periodicity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'other'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "active": {
+ "name": "active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "regions": {
+ "name": "regions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "url": {
+ "name": "url",
+ "type": "text(2048)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "external_name": {
+ "name": "external_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'GET'"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "timeout": {
+ "name": "timeout",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 45000
+ },
+ "degraded_after": {
+ "name": "degraded_after",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "assertions": {
+ "name": "assertions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "otel_endpoint": {
+ "name": "otel_endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "otel_headers": {
+ "name": "otel_headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "public": {
+ "name": "public",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "retry": {
+ "name": "retry",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 3
+ },
+ "follow_redirects": {
+ "name": "follow_redirects",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_workspace_id_workspace_id_fk": {
+ "name": "monitor_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitors_to_pages": {
+ "name": "monitors_to_pages",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ },
+ "monitor_group_id": {
+ "name": "monitor_group_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "group_order": {
+ "name": "group_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitors_to_pages_monitor_id_monitor_id_fk": {
+ "name": "monitors_to_pages_monitor_id_monitor_id_fk",
+ "tableFrom": "monitors_to_pages",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitors_to_pages_page_id_page_id_fk": {
+ "name": "monitors_to_pages_page_id_page_id_fk",
+ "tableFrom": "monitors_to_pages",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitors_to_pages_monitor_group_id_monitor_group_id_fk": {
+ "name": "monitors_to_pages_monitor_group_id_monitor_group_id_fk",
+ "tableFrom": "monitors_to_pages",
+ "tableTo": "monitor_group",
+ "columnsFrom": [
+ "monitor_group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "monitors_to_pages_monitor_id_page_id_pk": {
+ "columns": [
+ "monitor_id",
+ "page_id"
+ ],
+ "name": "monitors_to_pages_monitor_id_page_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "page_subscriber": {
+ "name": "page_subscriber",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "unsubscribed_at": {
+ "name": "unsubscribed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "page_subscriber_page_id_page_id_fk": {
+ "name": "page_subscriber_page_id_page_id_fk",
+ "tableFrom": "page_subscriber",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "notification": {
+ "name": "notification",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "data": {
+ "name": "data",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "notification_workspace_id_workspace_id_fk": {
+ "name": "notification_workspace_id_workspace_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "notification_trigger": {
+ "name": "notification_trigger",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "notification_id": {
+ "name": "notification_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cron_timestamp": {
+ "name": "cron_timestamp",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "notification_id_monitor_id_crontimestampe": {
+ "name": "notification_id_monitor_id_crontimestampe",
+ "columns": [
+ "notification_id",
+ "monitor_id",
+ "cron_timestamp"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "notification_trigger_monitor_id_monitor_id_fk": {
+ "name": "notification_trigger_monitor_id_monitor_id_fk",
+ "tableFrom": "notification_trigger",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notification_trigger_notification_id_notification_id_fk": {
+ "name": "notification_trigger_notification_id_notification_id_fk",
+ "tableFrom": "notification_trigger",
+ "tableTo": "notification",
+ "columnsFrom": [
+ "notification_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "notifications_to_monitors": {
+ "name": "notifications_to_monitors",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "notification_id": {
+ "name": "notification_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "notifications_to_monitors_monitor_id_monitor_id_fk": {
+ "name": "notifications_to_monitors_monitor_id_monitor_id_fk",
+ "tableFrom": "notifications_to_monitors",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notifications_to_monitors_notification_id_notification_id_fk": {
+ "name": "notifications_to_monitors_notification_id_notification_id_fk",
+ "tableFrom": "notifications_to_monitors",
+ "tableTo": "notification",
+ "columnsFrom": [
+ "notification_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "notifications_to_monitors_monitor_id_notification_id_pk": {
+ "columns": [
+ "monitor_id",
+ "notification_id"
+ ],
+ "name": "notifications_to_monitors_monitor_id_notification_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor_status": {
+ "name": "monitor_status",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "region": {
+ "name": "region",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "monitor_status_idx": {
+ "name": "monitor_status_idx",
+ "columns": [
+ "monitor_id",
+ "region"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "monitor_status_monitor_id_monitor_id_fk": {
+ "name": "monitor_status_monitor_id_monitor_id_fk",
+ "tableFrom": "monitor_status",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "monitor_status_monitor_id_region_pk": {
+ "columns": [
+ "monitor_id",
+ "region"
+ ],
+ "name": "monitor_status_monitor_id_region_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "invitation": {
+ "name": "invitation",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "incident": {
+ "name": "incident",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'triage'"
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "acknowledged_at": {
+ "name": "acknowledged_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "acknowledged_by": {
+ "name": "acknowledged_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_by": {
+ "name": "resolved_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "incident_screenshot_url": {
+ "name": "incident_screenshot_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recovery_screenshot_url": {
+ "name": "recovery_screenshot_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "auto_resolved": {
+ "name": "auto_resolved",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "incident_monitor_id_started_at_unique": {
+ "name": "incident_monitor_id_started_at_unique",
+ "columns": [
+ "monitor_id",
+ "started_at"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incident_monitor_id_monitor_id_fk": {
+ "name": "incident_monitor_id_monitor_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set default",
+ "onUpdate": "no action"
+ },
+ "incident_workspace_id_workspace_id_fk": {
+ "name": "incident_workspace_id_workspace_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "incident_acknowledged_by_user_id_fk": {
+ "name": "incident_acknowledged_by_user_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "user",
+ "columnsFrom": [
+ "acknowledged_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "incident_resolved_by_user_id_fk": {
+ "name": "incident_resolved_by_user_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "user",
+ "columnsFrom": [
+ "resolved_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor_tag": {
+ "name": "monitor_tag",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_tag_workspace_id_workspace_id_fk": {
+ "name": "monitor_tag_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor_tag",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor_tag_to_monitor": {
+ "name": "monitor_tag_to_monitor",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "monitor_tag_id": {
+ "name": "monitor_tag_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_tag_to_monitor_monitor_id_monitor_id_fk": {
+ "name": "monitor_tag_to_monitor_monitor_id_monitor_id_fk",
+ "tableFrom": "monitor_tag_to_monitor",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk": {
+ "name": "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk",
+ "tableFrom": "monitor_tag_to_monitor",
+ "tableTo": "monitor_tag",
+ "columnsFrom": [
+ "monitor_tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk": {
+ "columns": [
+ "monitor_id",
+ "monitor_tag_id"
+ ],
+ "name": "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "application": {
+ "name": "application",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "application_dsn_unique": {
+ "name": "application_dsn_unique",
+ "columns": [
+ "dsn"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "application_workspace_id_workspace_id_fk": {
+ "name": "application_workspace_id_workspace_id_fk",
+ "tableFrom": "application",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "maintenance": {
+ "name": "maintenance",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "from": {
+ "name": "from",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "to": {
+ "name": "to",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "maintenance_workspace_id_workspace_id_fk": {
+ "name": "maintenance_workspace_id_workspace_id_fk",
+ "tableFrom": "maintenance",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "maintenance_page_id_page_id_fk": {
+ "name": "maintenance_page_id_page_id_fk",
+ "tableFrom": "maintenance",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "maintenance_to_monitor": {
+ "name": "maintenance_to_monitor",
+ "columns": {
+ "maintenance_id": {
+ "name": "maintenance_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "maintenance_to_monitor_maintenance_id_maintenance_id_fk": {
+ "name": "maintenance_to_monitor_maintenance_id_maintenance_id_fk",
+ "tableFrom": "maintenance_to_monitor",
+ "tableTo": "maintenance",
+ "columnsFrom": [
+ "maintenance_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "maintenance_to_monitor_monitor_id_monitor_id_fk": {
+ "name": "maintenance_to_monitor_monitor_id_monitor_id_fk",
+ "tableFrom": "maintenance_to_monitor",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "maintenance_to_monitor_maintenance_id_monitor_id_pk": {
+ "columns": [
+ "maintenance_id",
+ "monitor_id"
+ ],
+ "name": "maintenance_to_monitor_maintenance_id_monitor_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "check": {
+ "name": "check",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "regions": {
+ "name": "regions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "url": {
+ "name": "url",
+ "type": "text(4096)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'GET'"
+ },
+ "count_requests": {
+ "name": "count_requests",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 1
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "check_workspace_id_workspace_id_fk": {
+ "name": "check_workspace_id_workspace_id_fk",
+ "tableFrom": "check",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor_run": {
+ "name": "monitor_run",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "runned_at": {
+ "name": "runned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_run_workspace_id_workspace_id_fk": {
+ "name": "monitor_run_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor_run",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "monitor_run_monitor_id_monitor_id_fk": {
+ "name": "monitor_run_monitor_id_monitor_id_fk",
+ "tableFrom": "monitor_run",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "private_location": {
+ "name": "private_location",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "private_location_workspace_id_workspace_id_fk": {
+ "name": "private_location_workspace_id_workspace_id_fk",
+ "tableFrom": "private_location",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "private_location_to_monitor": {
+ "name": "private_location_to_monitor",
+ "columns": {
+ "private_location_id": {
+ "name": "private_location_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "private_location_to_monitor_private_location_id_private_location_id_fk": {
+ "name": "private_location_to_monitor_private_location_id_private_location_id_fk",
+ "tableFrom": "private_location_to_monitor",
+ "tableTo": "private_location",
+ "columnsFrom": [
+ "private_location_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "private_location_to_monitor_monitor_id_monitor_id_fk": {
+ "name": "private_location_to_monitor_monitor_id_monitor_id_fk",
+ "tableFrom": "private_location_to_monitor",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "monitor_group": {
+ "name": "monitor_group",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_group_workspace_id_workspace_id_fk": {
+ "name": "monitor_group_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor_group",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitor_group_page_id_page_id_fk": {
+ "name": "monitor_group_page_id_page_id_fk",
+ "tableFrom": "monitor_group",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "viewer": {
+ "name": "viewer",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "viewer_email_unique": {
+ "name": "viewer_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "viewer_accounts": {
+ "name": "viewer_accounts",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "providerAccountId": {
+ "name": "providerAccountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_state": {
+ "name": "session_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "viewer_accounts_user_id_viewer_id_fk": {
+ "name": "viewer_accounts_user_id_viewer_id_fk",
+ "tableFrom": "viewer_accounts",
+ "tableTo": "viewer",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "viewer_accounts_provider_providerAccountId_pk": {
+ "columns": [
+ "provider",
+ "providerAccountId"
+ ],
+ "name": "viewer_accounts_provider_providerAccountId_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "viewer_session": {
+ "name": "viewer_session",
+ "columns": {
+ "session_token": {
+ "name": "session_token",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "viewer_session_user_id_viewer_id_fk": {
+ "name": "viewer_session_user_id_viewer_id_fk",
+ "tableFrom": "viewer_session",
+ "tableTo": "viewer",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "api_key": {
+ "name": "api_key",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hashed_token": {
+ "name": "hashed_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by_id": {
+ "name": "created_by_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "api_key_prefix_unique": {
+ "name": "api_key_prefix_unique",
+ "columns": [
+ "prefix"
+ ],
+ "isUnique": true
+ },
+ "api_key_hashed_token_unique": {
+ "name": "api_key_hashed_token_unique",
+ "columns": [
+ "hashed_token"
+ ],
+ "isUnique": true
+ },
+ "api_key_prefix_idx": {
+ "name": "api_key_prefix_idx",
+ "columns": [
+ "prefix"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "api_key_workspace_id_workspace_id_fk": {
+ "name": "api_key_workspace_id_workspace_id_fk",
+ "tableFrom": "api_key",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "api_key_created_by_id_user_id_fk": {
+ "name": "api_key_created_by_id_user_id_fk",
+ "tableFrom": "api_key",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "maintenance_to_page_component": {
+ "name": "maintenance_to_page_component",
+ "columns": {
+ "maintenance_id": {
+ "name": "maintenance_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_component_id": {
+ "name": "page_component_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "maintenance_to_page_component_maintenance_id_maintenance_id_fk": {
+ "name": "maintenance_to_page_component_maintenance_id_maintenance_id_fk",
+ "tableFrom": "maintenance_to_page_component",
+ "tableTo": "maintenance",
+ "columnsFrom": [
+ "maintenance_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "maintenance_to_page_component_page_component_id_page_component_id_fk": {
+ "name": "maintenance_to_page_component_page_component_id_page_component_id_fk",
+ "tableFrom": "maintenance_to_page_component",
+ "tableTo": "page_component",
+ "columnsFrom": [
+ "page_component_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "maintenance_to_page_component_maintenance_id_page_component_id_pk": {
+ "columns": [
+ "maintenance_id",
+ "page_component_id"
+ ],
+ "name": "maintenance_to_page_component_maintenance_id_page_component_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "page_component": {
+ "name": "page_component",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'monitor'"
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "group_order": {
+ "name": "group_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "page_component_page_id_monitor_id_unique": {
+ "name": "page_component_page_id_monitor_id_unique",
+ "columns": [
+ "page_id",
+ "monitor_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "page_component_workspace_id_workspace_id_fk": {
+ "name": "page_component_workspace_id_workspace_id_fk",
+ "tableFrom": "page_component",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_component_page_id_page_id_fk": {
+ "name": "page_component_page_id_page_id_fk",
+ "tableFrom": "page_component",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_component_monitor_id_monitor_id_fk": {
+ "name": "page_component_monitor_id_monitor_id_fk",
+ "tableFrom": "page_component",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_component_group_id_page_component_groups_id_fk": {
+ "name": "page_component_group_id_page_component_groups_id_fk",
+ "tableFrom": "page_component",
+ "tableTo": "page_component_groups",
+ "columnsFrom": [
+ "group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {
+ "page_component_type_check": {
+ "name": "page_component_type_check",
+ "value": "\"page_component\".\"type\" = 'monitor' AND \"page_component\".\"monitor_id\" IS NOT NULL OR \"page_component\".\"type\" = 'static' AND \"page_component\".\"monitor_id\" IS NULL"
+ }
+ }
+ },
+ "status_report_to_page_component": {
+ "name": "status_report_to_page_component",
+ "columns": {
+ "status_report_id": {
+ "name": "status_report_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_component_id": {
+ "name": "page_component_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_to_page_component_status_report_id_status_report_id_fk": {
+ "name": "status_report_to_page_component_status_report_id_status_report_id_fk",
+ "tableFrom": "status_report_to_page_component",
+ "tableTo": "status_report",
+ "columnsFrom": [
+ "status_report_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "status_report_to_page_component_page_component_id_page_component_id_fk": {
+ "name": "status_report_to_page_component_page_component_id_page_component_id_fk",
+ "tableFrom": "status_report_to_page_component",
+ "tableTo": "page_component",
+ "columnsFrom": [
+ "page_component_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "status_report_to_page_component_status_report_id_page_component_id_pk": {
+ "columns": [
+ "status_report_id",
+ "page_component_id"
+ ],
+ "name": "status_report_to_page_component_status_report_id_page_component_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "page_component_groups": {
+ "name": "page_component_groups",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "page_component_groups_workspace_id_workspace_id_fk": {
+ "name": "page_component_groups_workspace_id_workspace_id_fk",
+ "tableFrom": "page_component_groups",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_component_groups_page_id_page_id_fk": {
+ "name": "page_component_groups_page_id_page_id_fk",
+ "tableFrom": "page_component_groups",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index f19843fd0..7a7bb2637 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -386,6 +386,13 @@
"when": 1768564852930,
"tag": "0054_bitter_lilandra",
"breakpoints": true
+ },
+ {
+ "idx": 55,
+ "version": "6",
+ "when": 1769675142003,
+ "tag": "0055_spicy_bastion",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema/page_components/constants.ts b/packages/db/src/schema/page_components/constants.ts
new file mode 100644
index 000000000..42f7f5eaa
--- /dev/null
+++ b/packages/db/src/schema/page_components/constants.ts
@@ -0,0 +1,3 @@
+export const pageComponentTypes = ["static", "monitor"] as const;
+
+export type PageComponentType = (typeof pageComponentTypes)[number];
diff --git a/packages/db/src/schema/page_components/index.ts b/packages/db/src/schema/page_components/index.ts
index b23cc46fc..25fbf3ccb 100644
--- a/packages/db/src/schema/page_components/index.ts
+++ b/packages/db/src/schema/page_components/index.ts
@@ -1,2 +1,3 @@
export * from "./page_components";
export * from "./validation";
+export * from "./constants";
diff --git a/packages/db/src/schema/page_components/page_components.ts b/packages/db/src/schema/page_components/page_components.ts
index c79422895..769bf1502 100644
--- a/packages/db/src/schema/page_components/page_components.ts
+++ b/packages/db/src/schema/page_components/page_components.ts
@@ -14,8 +14,7 @@ import { pageComponentGroup } from "../page_component_groups";
import { page } from "../pages";
import { statusReport } from "../status_reports";
import { workspace } from "../workspaces";
-
-export const pageComponentTypes = ["external", "monitor"] as const;
+import { pageComponentTypes } from "./constants";
export const pageComponent = sqliteTable(
"page_component",
@@ -55,8 +54,8 @@ export const pageComponent = sqliteTable(
),
check(
"page_component_type_check",
- // NOTE: This check ensures that either the component is a monitor or an external component, but not both.
- sql`${t.type} = 'monitor' AND ${t.monitorId} IS NOT NULL OR ${t.type} = 'external' AND ${t.monitorId} IS NULL`,
+ // NOTE: This check ensures that either the component is a monitor or a static component, but not both.
+ sql`${t.type} = 'monitor' AND ${t.monitorId} IS NOT NULL OR ${t.type} = 'static' AND ${t.monitorId} IS NULL`,
),
],
);
diff --git a/packages/db/src/schema/page_components/validation.ts b/packages/db/src/schema/page_components/validation.ts
index a7f2e6dbe..7b85497ce 100644
--- a/packages/db/src/schema/page_components/validation.ts
+++ b/packages/db/src/schema/page_components/validation.ts
@@ -1,6 +1,5 @@
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
import type { z } from "zod";
-
import { pageComponent } from "./page_components";
export const selectPageComponentSchema = createSelectSchema(pageComponent);
@@ -13,15 +12,15 @@ export const insertPageComponentSchema = createInsertSchema(pageComponent, {
if (data.type === "monitor" && !data.monitorId) {
return false;
}
- // monitorId must be null when type='external'
- if (data.type === "external" && data.monitorId) {
+ // monitorId must be null when type='static'
+ if (data.type === "static" && data.monitorId) {
return false;
}
return true;
},
{
message:
- "monitorId must be set when type is 'monitor' and must be null when type is 'external'",
+ "monitorId must be set when type is 'monitor' and must be null when type is 'static'",
},
);
diff --git a/packages/db/src/schema/plan/config.ts b/packages/db/src/schema/plan/config.ts
index 91c534e6c..a7a86cb53 100644
--- a/packages/db/src/schema/plan/config.ts
+++ b/packages/db/src/schema/plan/config.ts
@@ -38,6 +38,7 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
"max-regions": 6,
"data-retention": "14 days",
"status-pages": 1,
+ "page-components": 3,
maintenance: true,
"monitor-values-visibility": true,
"response-logs": false,
@@ -110,6 +111,7 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
"max-regions": 6,
"data-retention": "3 months",
"status-pages": 1,
+ "page-components": 20,
maintenance: true,
"monitor-values-visibility": true,
"response-logs": true,
@@ -182,6 +184,7 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
"max-regions": AVAILABLE_REGIONS.length,
"data-retention": "12 months",
"status-pages": 5,
+ "page-components": 50,
maintenance: true,
"monitor-values-visibility": true,
"response-logs": true,
diff --git a/packages/db/src/schema/plan/schema.ts b/packages/db/src/schema/plan/schema.ts
index e421e1b3c..ba7f12014 100644
--- a/packages/db/src/schema/plan/schema.ts
+++ b/packages/db/src/schema/plan/schema.ts
@@ -27,6 +27,7 @@ export const limitsSchema = z.object({
* Status page limits
*/
"status-pages": z.number().prefault(1),
+ "page-components": z.number().prefault(3),
maintenance: z.boolean().prefault(true),
"monitor-values-visibility": z.boolean().prefault(true),
"status-subscribers": z.boolean().prefault(false),
diff --git a/packages/db/src/schema/shared.ts b/packages/db/src/schema/shared.ts
index 53c8e46f6..6e985360b 100644
--- a/packages/db/src/schema/shared.ts
+++ b/packages/db/src/schema/shared.ts
@@ -54,30 +54,12 @@ export const selectMaintenancePageSchema = selectMaintenanceSchema.extend({
)
.prefault([]),
});
-// TODO: it would be nice to automatically add the monitor relation here
-// .refine((data) => ({ monitors: data.maintenancesToMonitors.map((m) => m.monitorId) }));
export const selectPageSchemaWithRelation = selectPageSchema.extend({
monitors: z.array(selectMonitorSchema),
statusReports: z.array(selectStatusReportPageSchema),
});
-export const selectPageSchemaWithMonitorsRelation = selectPageSchema.extend({
- monitorsToPages: z.array(
- z.object({
- monitorId: z.number(),
- pageId: z.number(),
- order: z.number().prefault(0).optional(),
- monitor: selectMonitorSchema,
- }),
- ),
- maintenances: selectMaintenanceSchema.array().prefault([]),
- statusReports: selectStatusReportSchema
- .extend({ statusReportUpdates: selectStatusReportUpdateSchema.array() })
- .array()
- .prefault([]),
-});
-
export const legacy_selectPublicPageSchemaWithRelation = selectPageSchema
.extend({
monitors: z.array(selectPublicMonitorSchema).prefault([]),
@@ -172,6 +154,24 @@ export type PageComponentWithMonitorRelation = z.infer<
typeof selectPageComponentWithMonitorRelation
>;
+export const selectPublicPageLightSchemaWithRelation = selectPageSchema
+ .extend({
+ monitors: z.array(selectPublicMonitorSchema).prefault([]),
+ statusReports: z.array(selectStatusReportPageSchema).prefault([]),
+ incidents: z.array(selectIncidentSchema).prefault([]),
+ maintenances: z.array(selectMaintenancePageSchema).prefault([]),
+ workspacePlan: workspacePlanSchema
+ .nullable()
+ .prefault("free")
+ .transform((val) => val ?? "free"),
+ // NEW: Include pageComponents for modern consumers
+ pageComponents: selectPageComponentWithMonitorRelation.array().prefault([]),
+ pageComponentGroups: selectPageComponentGroupSchema.array().prefault([]),
+ })
+ .omit({
+ id: true,
+ });
+
export const selectPublicPageSchemaWithRelation = selectPageSchema.extend({
monitorGroups: selectMonitorGroupSchema.array().prefault([]),
// TODO: include status of the monitor
@@ -192,20 +192,6 @@ export const selectPublicPageSchemaWithRelation = selectPageSchema.extend({
whiteLabel: z.boolean().prefault(false),
});
-export const selectPublicStatusReportSchemaWithRelation =
- selectStatusReportSchema.extend({
- monitorsToStatusReports: z
- .array(
- z.object({
- monitorId: z.number(),
- statusReportId: z.number(),
- monitor: selectPublicMonitorSchema,
- }),
- )
- .prefault([]),
- statusReportUpdates: z.array(selectStatusReportUpdateSchema),
- });
-
export type StatusReportWithUpdates = z.infer<
typeof selectStatusReportPageSchema
>;
diff --git a/packages/db/src/schema/workspaces/validation.ts b/packages/db/src/schema/workspaces/validation.ts
index 4d4d51b26..5d9deb0bc 100644
--- a/packages/db/src/schema/workspaces/validation.ts
+++ b/packages/db/src/schema/workspaces/validation.ts
@@ -55,6 +55,7 @@ export const selectWorkspaceSchema = createSelectSchema(workspace)
monitors: z.number().prefault(0),
notifications: z.number().prefault(0),
pages: z.number().prefault(0),
+ pageComponents: z.number().prefault(0),
// checks: z.number().default(0),
})
.nullish(),
diff --git a/packages/db/src/sync.ts b/packages/db/src/sync.ts
index e9c3d2cd6..8ff232ecb 100644
--- a/packages/db/src/sync.ts
+++ b/packages/db/src/sync.ts
@@ -258,6 +258,24 @@ export async function syncMonitorsToPageDelete(
);
}
+/**
+ * REVERSE SYNC: Syncs a page_component delete to monitors_to_pages
+ * Used when pageComponent is the primary table and monitorsToPages is kept for backwards compatibility
+ */
+export async function syncPageComponentToMonitorsToPageDelete(
+ db: DB | Transaction,
+ data: { monitorId: number; pageId: number },
+) {
+ await db
+ .delete(monitorsToPages)
+ .where(
+ and(
+ eq(monitorsToPages.monitorId, data.monitorId),
+ eq(monitorsToPages.pageId, data.pageId),
+ ),
+ );
+}
+
/**
* Syncs monitors_to_pages deletes for a specific page to page_component
*/
@@ -479,7 +497,7 @@ export async function syncStatusReportToPageComponentInsertMany(
if (pageComponentIds.length === 0) return;
// Find monitor IDs from the page components
- // Only get components that have a monitorId (not external components)
+ // Only get components that have a monitorId (not static components)
const components = await db
.select({ monitorId: pageComponent.monitorId })
.from(pageComponent)
@@ -691,7 +709,7 @@ export async function syncMaintenanceToPageComponentInsertMany(
if (pageComponentIds.length === 0) return;
// Find monitor IDs from the page components
- // Only get components that have a monitorId (not external components)
+ // Only get components that have a monitorId (not static components)
const components = await db
.select({ monitorId: pageComponent.monitorId })
.from(pageComponent)