chore: more clean up + ts issues

This commit is contained in:
Carl-Gerhard Lindesvärd
2025-02-11 21:50:51 +01:00
parent 3205ea0a31
commit cfd7fd9c5e
7 changed files with 12 additions and 233 deletions

View File

@@ -4,30 +4,19 @@ import { RocketIcon } from 'lucide-react';
import type { IServiceClient } from '@openpanel/db';
import CopyInput from '../forms/copy-input';
import { Label } from '../ui/label';
type Props = IServiceClient;
export function CreateClientSuccess({ id, secret, cors }: Props) {
export function CreateClientSuccess({ id, secret }: Props) {
return (
<div className="grid gap-4">
<CopyInput label="Client ID" value={id} />
{secret && (
<div className="w-full">
<CopyInput label="Secret" value={secret} />
{cors && (
<p className="mt-1 text-sm text-muted-foreground">
You will only need the secret if you want to send server events.
</p>
)}
</div>
)}
{cors && (
<div className="text-left">
<Label>CORS settings</Label>
<div className="font-mono flex items-center justify-between rounded border-input bg-def-200 p-2 px-3 ">
{cors}
</div>
<p className="mt-1 text-sm text-muted-foreground">
You will only need the secret if you want to send server events.
</p>
</div>
)}
<Alert>

View File

@@ -1,22 +1,17 @@
'use client';
import AnimateHeight from '@/components/animate-height';
import { CreateClientSuccess } from '@/components/clients/create-client-success';
import TagInput from '@/components/forms/tag-input';
import { Button, buttonVariants } from '@/components/ui/button';
import { CheckboxInput } from '@/components/ui/checkbox';
import { Combobox } from '@/components/ui/combobox';
import { DialogFooter } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { useAppParams } from '@/hooks/useAppParams';
import { api, handleError } from '@/trpc/client';
import { cn } from '@/utils/cn';
import { zodResolver } from '@hookform/resolvers/zod';
import { SaveIcon } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import type { SubmitHandler } from 'react-hook-form';
import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';

View File

@@ -1,12 +1,10 @@
import { ButtonContainer } from '@/components/button-container';
import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';
import TagInput from '@/components/forms/tag-input';
import { InputWithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
import { CheckboxInput } from '@/components/ui/checkbox';
import { api, handleError } from '@/trpc/client';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { Controller, useForm } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
@@ -20,18 +18,11 @@ type EditClientProps = IServiceClient;
const validator = z.object({
id: z.string().min(1),
name: z.string().min(1),
cors: z.string().nullable(),
crossDomain: z.boolean().optional(),
});
type IForm = z.infer<typeof validator>;
export default function EditClient({
id,
name,
cors,
crossDomain,
}: EditClientProps) {
export default function EditClient({ id, name }: EditClientProps) {
const router = useRouter();
const { register, handleSubmit, reset, formState, control, setError } =
useForm<IForm>({
@@ -39,8 +30,6 @@ export default function EditClient({
defaultValues: {
id,
name,
cors,
crossDomain,
},
});
@@ -59,81 +48,8 @@ export default function EditClient({
return (
<ModalContent>
<ModalHeader title="Edit client" />
<form
onSubmit={handleSubmit((values) => {
if (!values.cors) {
return setError('cors', {
type: 'required',
message: 'Please add a domain',
});
}
mutation.mutate(values);
})}
>
<div className="flex flex-col gap-4">
<InputWithLabel
label="Name"
placeholder="Name"
{...register('name')}
/>
<Controller
name="cors"
control={control}
render={({ field }) => (
<WithLabel
label="Domain(s)"
error={formState.errors.cors?.message}
>
<TagInput
{...field}
error={formState.errors.cors?.message}
placeholder="Add a domain"
value={field.value?.split(',') ?? []}
renderTag={(tag) => (tag === '*' ? 'Allow all domains' : tag)}
onChange={(newValue) => {
field.onChange(
newValue
.map((item) => {
const trimmed = item.trim();
if (
trimmed.startsWith('http://') ||
trimmed.startsWith('https://') ||
trimmed === '*'
) {
return trimmed;
}
return `https://${trimmed}`;
})
.join(','),
);
}}
/>
</WithLabel>
)}
/>
<Controller
name="crossDomain"
control={control}
render={({ field }) => {
return (
<CheckboxInput
ref={field.ref}
onBlur={field.onBlur}
defaultChecked={field.value}
onCheckedChange={field.onChange}
>
<div>Enable cross domain support</div>
<div className="font-normal text-muted-foreground">
This will let you track users across multiple domains
</div>
</CheckboxInput>
);
}}
/>
</div>
<form onSubmit={handleSubmit((values) => mutation.mutate(values))}>
<InputWithLabel label="Name" placeholder="Name" {...register('name')} />
<ButtonContainer>
<Button type="button" variant="outline" onClick={() => popModal()}>
Cancel

View File

@@ -1,119 +1,3 @@
import {
chQuery,
db,
getClientByIdCached,
getProjectByIdCached,
} from '../index';
import { stripTrailingSlash } from '@openpanel/common';
const pickBestDomain = (domains: string[]): string | null => {
// Filter out invalid domains
const validDomains = domains.filter(
(domain) =>
domain &&
!domain.includes('*') &&
!domain.includes('localhost') &&
!domain.includes('127.0.0.1'),
);
if (validDomains.length === 0) return null;
// Score each domain
const scoredDomains = validDomains.map((domain) => {
let score = 0;
// Prefer https (highest priority)
if (domain.startsWith('https://')) score += 100;
// Penalize domains from common providers like vercel, netlify, etc.
if (
domain.includes('vercel.app') ||
domain.includes('netlify.app') ||
domain.includes('herokuapp.com') ||
domain.includes('github.io') ||
domain.includes('gitlab.io') ||
domain.includes('surge.sh') ||
domain.includes('cloudfront.net') ||
domain.includes('firebaseapp.com') ||
domain.includes('azurestaticapps.net') ||
domain.includes('pages.dev') ||
domain.includes('ngrok-free.app') ||
domain.includes('ngrok.app')
) {
score -= 50;
}
// Penalize subdomains
const domainParts = domain
.replace('https://', '')
.replace('http://', '')
.split('.');
if (domainParts.length <= 2) score += 50;
// Tiebreaker: prefer shorter domains
score -= domain.length;
return { domain, score };
});
// Sort by score (highest first) and return the best domain
const bestDomain = scoredDomains.sort((a, b) => b.score - a.score)[0];
return bestDomain?.domain || null;
};
export const up = async () => {
const projects = await db.project.findMany({
include: {
clients: true,
},
});
const matches = [];
for (const project of projects) {
if (project.cors.length > 0 || project.domain) {
continue;
}
if (project.clients.length === 0) {
continue;
}
const cors = [];
let crossDomain = false;
for (const client of project.clients) {
if (client.crossDomain) {
crossDomain = true;
}
cors.push(
...(client.cors?.split(',') ?? []).map((c) =>
stripTrailingSlash(c.trim()),
),
);
await getClientByIdCached.clear(client.id);
}
let domain = pickBestDomain(cors);
if (!domain) {
const res = await chQuery<{ origin: string }>(
`SELECT origin FROM events_distributed WHERE project_id = '${project.id}' and origin != ''`,
);
if (res.length) {
domain = pickBestDomain(res.map((r) => r.origin));
matches.push(domain);
}
}
await db.project.update({
where: { id: project.id },
data: {
cors,
crossDomain,
domain,
},
});
await getProjectByIdCached.clear(project.id);
}
// Deprecate migration
};

View File

@@ -196,7 +196,7 @@ export interface IServiceEventMinimal {
}
interface GetEventsOptions {
profile?: boolean | Prisma.ProfileSelect;
profile?: boolean;
meta?: boolean | Prisma.EventMetaSelect;
}

View File

@@ -15,8 +15,6 @@ export const clientRouter = createTRPCRouter({
z.object({
id: z.string(),
name: z.string(),
cors: z.string().nullable(),
crossDomain: z.boolean().optional(),
}),
)
.mutation(async ({ input, ctx }) => {
@@ -35,8 +33,6 @@ export const clientRouter = createTRPCRouter({
},
data: {
name: input.name,
cors: input.cors ?? null,
crossDomain: input.crossDomain,
},
});
}),

View File

@@ -2,8 +2,8 @@ import crypto from 'node:crypto';
import type { z } from 'zod';
import { stripTrailingSlash } from '@openpanel/common';
import { db, getId, getOrganizationBySlug, getUserById } from '@openpanel/db';
import type { ProjectType } from '@openpanel/db';
import { db, getId, getOrganizationBySlug, getUserById } from '@openpanel/db';
import { zOnboardingProject } from '@openpanel/validation';
import { hashPassword } from '@openpanel/common/server';
@@ -114,7 +114,6 @@ export const onboardingRouter = createTRPCRouter({
organizationId: organization.id,
projectId: project.id,
type: 'write',
cors: input.domain ? stripTrailingSlash(input.domain) : null,
secret: await hashPassword(secret),
},
});