so now we're on fly.io
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
import { OUR_DOMAIN } from "./env"
|
||||
|
||||
export const logout = () => {
|
||||
const url = new URL(`${location.protocol}//${OUR_DOMAIN}/api/logout`)
|
||||
if (location.host !== OUR_DOMAIN) {
|
||||
url.searchParams.set(
|
||||
"next",
|
||||
`${location.protocol}//${location.host}/api/logout`
|
||||
)
|
||||
}
|
||||
location.href = url.href
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { User, Membership } from "~/lib/db.server"
|
||||
import { prismaRead } from "./db.server"
|
||||
import dayjs from "dayjs"
|
||||
import Cookie, { CookieSerializeOptions } from "cookie"
|
||||
import { AUTH_COOKIE_NAME } from "./env.server"
|
||||
import { IS_PROD } from "./constants"
|
||||
import { IncomingMessage } from "http"
|
||||
import { OUR_DOMAIN } from "./env"
|
||||
|
||||
export type AuthUser = User & {
|
||||
memberships: Membership[]
|
||||
}
|
||||
|
||||
export const getAuthTokenFromRequest = (request: IncomingMessage) => {
|
||||
let token = request.headers.authorization?.replace(/[Bb]earer\s/, "")
|
||||
if (!token) {
|
||||
const cookieHeader = request.headers.cookie
|
||||
if (cookieHeader) {
|
||||
const value = Cookie.parse(cookieHeader)[AUTH_COOKIE_NAME]
|
||||
token = value
|
||||
}
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
const findUserFromToken = async (token: string) => {
|
||||
const accessToken = await prismaRead.accessToken.findUnique({
|
||||
where: {
|
||||
token,
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
include: {
|
||||
memberships: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
return accessToken?.user
|
||||
}
|
||||
|
||||
export const getAuthUser = async <TRequireAuth extends boolean | undefined>(
|
||||
request: IncomingMessage,
|
||||
requireAuth?: TRequireAuth
|
||||
) => {
|
||||
const token = getAuthTokenFromRequest(request)
|
||||
|
||||
let user: AuthUser | null | undefined = null
|
||||
|
||||
if (token) {
|
||||
user = await findUserFromToken(token)
|
||||
}
|
||||
|
||||
if (!user && requireAuth) {
|
||||
throw new Error("require auth")
|
||||
}
|
||||
|
||||
return user as TRequireAuth extends true
|
||||
? AuthUser
|
||||
: AuthUser | null | undefined
|
||||
}
|
||||
|
||||
export const getAuthCookieOptions = ({
|
||||
domain,
|
||||
clearCookie,
|
||||
}: {
|
||||
domain?: string
|
||||
clearCookie?: boolean
|
||||
}): CookieSerializeOptions => {
|
||||
return {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
expires: clearCookie ? new Date() : dayjs().add(6, "month").toDate(),
|
||||
secure: IS_PROD,
|
||||
domain: IS_PROD ? `.${domain || OUR_DOMAIN}` : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export const generateCookie = (
|
||||
options:
|
||||
| { type: "clear"; domain?: string }
|
||||
| { type: "auth"; token: string; domain?: string }
|
||||
) => {
|
||||
if (options.type === "clear") {
|
||||
return Cookie.serialize(
|
||||
AUTH_COOKIE_NAME,
|
||||
"",
|
||||
getAuthCookieOptions({ domain: options.domain, clearCookie: true })
|
||||
)
|
||||
}
|
||||
return Cookie.serialize(
|
||||
AUTH_COOKIE_NAME,
|
||||
options.token,
|
||||
getAuthCookieOptions({ domain: options.domain })
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export const IS_BROWSER = typeof document !== "undefined"
|
||||
|
||||
export const IS_PROD = IS_BROWSER
|
||||
? !location.hostname.endsWith("localhost")
|
||||
: process.env.NODE_ENV === "production"
|
||||
@@ -0,0 +1,8 @@
|
||||
import dayjs from "dayjs"
|
||||
|
||||
export const formatDate = (
|
||||
date: string | Date,
|
||||
format: "MMM D" | "MMM D, YYYY" | "YYYY" = "MMM D, YYYY"
|
||||
) => {
|
||||
return dayjs(date).format(format)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { PrismaClient, type Prisma } from "@prisma/client"
|
||||
import { IS_BROWSER, IS_PROD } from "./constants"
|
||||
import { singleton } from "./singleton.server"
|
||||
|
||||
const logLevel: Prisma.LogLevel[] = IS_PROD
|
||||
? ["info", "error", "warn"]
|
||||
: ["info", "warn", "error", "query"]
|
||||
|
||||
const createPrisma = (readonly: boolean) => {
|
||||
if (!IS_PROD && !IS_BROWSER) {
|
||||
for (const k in require.cache) {
|
||||
if (k.includes("prisma")) {
|
||||
delete require.cache[k]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let url = process.env.DATABASE_URL
|
||||
|
||||
// DATABASE_URL is not set during production build in docker
|
||||
// But Prisma is actually used there, so just return a fake one
|
||||
// It's weird that @__PURE__ doesn't work for Next.js
|
||||
if (!url) return {} as PrismaClient
|
||||
|
||||
if (url && readonly && IS_PROD) {
|
||||
url = url.replace(":5432", ":5433")
|
||||
}
|
||||
|
||||
console.log("connecting to", url)
|
||||
|
||||
const client = new PrismaClient({
|
||||
log: logLevel,
|
||||
datasources: url
|
||||
? {
|
||||
db: {
|
||||
url,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
|
||||
client.$use(async (params, next) => {
|
||||
const now = Date.now()
|
||||
const result = await next(params)
|
||||
const end = Date.now()
|
||||
const duration = Math.floor(end - now)
|
||||
console.log("query took", duration, "ms")
|
||||
// See results here
|
||||
return result
|
||||
})
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
export const prismaPrimary = /* @__PURE__ */ singleton("prisma-primary", () =>
|
||||
createPrisma(false)
|
||||
)
|
||||
|
||||
export const prismaRead = /* @__PURE__ */ singleton("prisma-read", () =>
|
||||
createPrisma(true)
|
||||
)
|
||||
|
||||
export * from "@prisma/client"
|
||||
@@ -0,0 +1,9 @@
|
||||
export const R2_API_TOKEN = process.env.R2_API_TOKEN
|
||||
export const MAILGUN_APIKEY = process.env.MAILGUN_APIKEY
|
||||
export const MAILGUN_DOMAIN = process.env.MAILGUN_DOMAIN
|
||||
export const ENCRYPT_SECRET = process.env.ENCRYPT_SECRET
|
||||
|
||||
export const AUTH_COOKIE_NAME = process.env.AUTH_COOKIE_NAME
|
||||
export const PRIMARY_REGION = process.env.PRIMARY_REGION
|
||||
export const FLY_REGION = process.env.FLY_REGION || "local"
|
||||
export const IS_PRIMARY_REGION = FLY_REGION === PRIMARY_REGION
|
||||
@@ -0,0 +1,6 @@
|
||||
import { IS_PROD } from "./constants"
|
||||
|
||||
export const APP_NAME = process.env.NEXT_PUBLIC_APP_NAME
|
||||
export const OUR_DOMAIN = process.env.NEXT_PUBLIC_OUR_DOMAIN
|
||||
export const SITE_URL = `${IS_PROD ? "https" : "http"}://${OUR_DOMAIN}`
|
||||
export const R2_URL = process.env.NEXT_PUBLIC_R2_URL
|
||||
@@ -0,0 +1,126 @@
|
||||
import { MembershipRole, type Site, type Page } from "~/lib/db.server"
|
||||
import type { AuthUser } from "./auth.server"
|
||||
import { PageVisibilityEnum } from "./types"
|
||||
|
||||
type Action =
|
||||
| {
|
||||
type: "can-delete-page"
|
||||
/** The site id this page belongs to */
|
||||
siteId: string
|
||||
}
|
||||
| {
|
||||
type: "can-list-page"
|
||||
visibility: PageVisibilityEnum
|
||||
siteId: string
|
||||
}
|
||||
| {
|
||||
type: "can-create-page"
|
||||
siteId: string
|
||||
}
|
||||
| {
|
||||
type: "can-read-page"
|
||||
page: Page
|
||||
}
|
||||
| {
|
||||
type: "can-update-site"
|
||||
site: Site
|
||||
}
|
||||
| {
|
||||
type: "can-notify-site-subscribers"
|
||||
site: Site
|
||||
}
|
||||
export const createGate = <TRequiredAuth extends boolean | undefined>({
|
||||
user,
|
||||
}: {
|
||||
user: AuthUser | null | undefined
|
||||
}) => {
|
||||
const isSiteMember = (siteId: string, roles: MembershipRole[]) => {
|
||||
if (!user) return false
|
||||
return user.memberships.some(
|
||||
(m) => m.siteId === siteId && roles.includes(m.role)
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
getUser<TRequiredAuth extends boolean | undefined>(
|
||||
requireAuth?: TRequiredAuth
|
||||
) {
|
||||
if (requireAuth && !user) {
|
||||
throw new Error("unauthorized")
|
||||
}
|
||||
return user as TRequiredAuth extends true
|
||||
? AuthUser
|
||||
: AuthUser | null | undefined
|
||||
},
|
||||
|
||||
hasRoles(siteId: string, roles: MembershipRole[]) {
|
||||
return isSiteMember(siteId, roles)
|
||||
},
|
||||
|
||||
isOwnerOrAdmin(siteId: string) {
|
||||
return this.hasRoles(siteId, [MembershipRole.OWNER, MembershipRole.ADMIN])
|
||||
},
|
||||
|
||||
allows(action: Action): boolean {
|
||||
if (action.type === "can-delete-page") {
|
||||
return isSiteMember(action.siteId, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
if (action.type === "can-list-page") {
|
||||
if (action.visibility === PageVisibilityEnum.Published) {
|
||||
return true
|
||||
}
|
||||
return isSiteMember(action.siteId, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
if (action.type === "can-create-page") {
|
||||
return isSiteMember(action.siteId, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
if (action.type === "can-read-page") {
|
||||
const isPublished =
|
||||
action.page.published &&
|
||||
action.page.publishedAt &&
|
||||
action.page.publishedAt <= new Date()
|
||||
|
||||
return isPublished
|
||||
? !action.page.deletedAt
|
||||
: !action.page.deletedAt &&
|
||||
isSiteMember(action.page.siteId, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
if (action.type === "can-update-site") {
|
||||
return isSiteMember(action.site.id, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
if (action.type === "can-notify-site-subscribers") {
|
||||
return isSiteMember(action.site.id, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
permissionError(message = "not allowed") {
|
||||
return new Error(message)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export type Gate = ReturnType<typeof createGate>
|
||||
@@ -0,0 +1,15 @@
|
||||
import { IS_PROD } from "./constants"
|
||||
import { OUR_DOMAIN } from "./env"
|
||||
|
||||
export const getSiteLink = ({
|
||||
subdomain,
|
||||
noProtocol,
|
||||
}: {
|
||||
subdomain: string
|
||||
noProtocol?: boolean
|
||||
}) => {
|
||||
if (noProtocol) {
|
||||
return `${subdomain}.${OUR_DOMAIN}`
|
||||
}
|
||||
return `${IS_PROD ? "https" : "http"}://${subdomain}.${OUR_DOMAIN}`
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import Mailgun from "mailgun.js"
|
||||
import FormData from "form-data"
|
||||
import { singleton } from "./singleton.server"
|
||||
import {
|
||||
ENCRYPT_SECRET,
|
||||
MAILGUN_APIKEY,
|
||||
MAILGUN_DOMAIN,
|
||||
} from "~/lib/env.server"
|
||||
import type { MailgunMessageData } from "mailgun.js/interfaces/Messages"
|
||||
import { IS_PROD } from "./constants"
|
||||
import { APP_NAME, OUR_DOMAIN, SITE_URL } from "./env"
|
||||
import { SubscribeFormData } from "./types"
|
||||
import { getSite } from "~/models/site.model"
|
||||
import { type Site } from "~/lib/db.server"
|
||||
import Iron from "@hapi/iron"
|
||||
|
||||
const enableMailgun = Boolean(MAILGUN_APIKEY && MAILGUN_DOMAIN)
|
||||
|
||||
const getClient = () =>
|
||||
singleton("mailgun", () => {
|
||||
const mg = new Mailgun(FormData)
|
||||
const client = mg.client({
|
||||
username: "api",
|
||||
key: MAILGUN_APIKEY,
|
||||
timeout: 60000,
|
||||
})
|
||||
return client
|
||||
})
|
||||
|
||||
const sendEmail = async (message: MailgunMessageData) => {
|
||||
console.log(message)
|
||||
|
||||
if (!enableMailgun) {
|
||||
console.error(
|
||||
"not sending email because no mailgun apikey or domain configured"
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const client = getClient()
|
||||
|
||||
await client.messages.create(MAILGUN_DOMAIN, message).then(console.log)
|
||||
}
|
||||
|
||||
export const sendLoginEmail = async (payload: {
|
||||
token: string
|
||||
email: string
|
||||
url: string
|
||||
subscribeForm?: SubscribeFormData
|
||||
}) => {
|
||||
const { protocol, host, pathname } = new URL(payload.url)
|
||||
const query = new URLSearchParams([
|
||||
["token", payload.token],
|
||||
["next", `${protocol}//${host}${pathname}`],
|
||||
])
|
||||
if (payload.subscribeForm) {
|
||||
query.append("subscribe", JSON.stringify(payload.subscribeForm))
|
||||
}
|
||||
const loginLink = `${
|
||||
IS_PROD ? "https" : "http"
|
||||
}://${OUR_DOMAIN}/api/login?${query.toString()}`
|
||||
|
||||
let subject = `Sign in to ${APP_NAME}`
|
||||
|
||||
let html = `
|
||||
<p>Hello,</p>
|
||||
|
||||
<p>We received a request to sign in to ${APP_NAME} using this email address, please click the link below to sign in:</p>
|
||||
|
||||
<a href="${loginLink}">Sign in to ${APP_NAME}</a>
|
||||
|
||||
<p>This link will expire in 10 minutes. If you did not request this link, you can safely ignore this email.</p>
|
||||
|
||||
<p>Thanks,</p>
|
||||
|
||||
<p>Your Proselog Team</p>
|
||||
`
|
||||
|
||||
if (payload.subscribeForm) {
|
||||
const site = await getSite(payload.subscribeForm.siteId)
|
||||
subject = `Confirm your subscription to ${site.name}`
|
||||
html = `
|
||||
<p>Please confirm your subscription to ${site.name} by clicking the link below:</p>
|
||||
|
||||
<a href="${loginLink}">confirm</a>
|
||||
|
||||
<p>This link will expire in 10 minutes.</p>`
|
||||
}
|
||||
|
||||
const message: MailgunMessageData = {
|
||||
from: `${APP_NAME} <hi@proselog.com>`,
|
||||
to: payload.email,
|
||||
subject,
|
||||
html,
|
||||
}
|
||||
|
||||
await sendEmail(message)
|
||||
}
|
||||
|
||||
export const sendEmailForNewPost = async (payload: {
|
||||
post: { slug: string; title: string; content: string }
|
||||
site: Site
|
||||
subscribers: { id: string; email: string }[]
|
||||
}) => {
|
||||
try {
|
||||
const from = `${payload.site.name} <updates@${payload.site.subdomain}.proselog.com>`
|
||||
const subject = `${payload.post.title} - ${payload.site.name}`
|
||||
const html = `
|
||||
|
||||
<h2>${payload.post.title}</h2>
|
||||
<div>
|
||||
${payload.post.content}
|
||||
</div>
|
||||
<p>
|
||||
<a href="${SITE_URL}/api/unsubscribe?token=%recipient.unsubscribeToken%">Unsubscribe (no login required)</a>
|
||||
</p>`
|
||||
|
||||
const recipientVariables: {
|
||||
[email in string]: { unsubscribeToken: string }
|
||||
} = {}
|
||||
|
||||
await Promise.allSettled(
|
||||
payload.subscribers.map(async (sub) => {
|
||||
const unsubscribeToken = await Iron.seal(
|
||||
{
|
||||
userId: sub.id,
|
||||
siteId: payload.site.id,
|
||||
},
|
||||
ENCRYPT_SECRET,
|
||||
Iron.defaults
|
||||
)
|
||||
recipientVariables[sub.email] = {
|
||||
unsubscribeToken,
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
const message: MailgunMessageData = {
|
||||
from,
|
||||
subject,
|
||||
html,
|
||||
to: Object.keys(recipientVariables),
|
||||
"recipient-variables": JSON.stringify(recipientVariables),
|
||||
}
|
||||
|
||||
await sendEmail(message)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import Markdown from "markdown-it"
|
||||
import Prism from "prismjs"
|
||||
import loadLanguages from "prismjs/components/index"
|
||||
import { getUserContentsUrl } from "./user-contents"
|
||||
|
||||
const isExternLink = (url: string) => /^https?:\/\//.test(url)
|
||||
|
||||
const handleImages = (md: Markdown) => {
|
||||
const imageRule = md.renderer.rules.image!
|
||||
md.renderer.rules.image = (tokens, idx, options, env, self) => {
|
||||
const token = tokens[idx]
|
||||
const url = token.attrGet("src")
|
||||
|
||||
// Don't allow images from other domains.
|
||||
if (!url || isExternLink(url)) {
|
||||
return ""
|
||||
}
|
||||
|
||||
token.attrSet("src", getUserContentsUrl(url))
|
||||
return imageRule(tokens, idx, options, env, self)
|
||||
}
|
||||
}
|
||||
|
||||
const codeBlock = (md: Markdown) => {
|
||||
const highlight = (code: string, lang: string) => {
|
||||
if (lang === "vue" || lang === "svelte") {
|
||||
lang = "html"
|
||||
}
|
||||
loadLanguages(lang)
|
||||
const grammer = Prism.languages[lang]
|
||||
const html = grammer
|
||||
? `<pre><code>${Prism.highlight(code, grammer, lang)}</code></pre>`
|
||||
: `<pre><code>${md.utils.escapeHtml(code)}</code></pre>`
|
||||
|
||||
return html
|
||||
}
|
||||
|
||||
md.renderer.rules.fence = (tokens, idx, options, env, self) => {
|
||||
const token = tokens[idx]
|
||||
const code = highlight(token.content, token.info)
|
||||
return `<div class="code" data-lang="${token.info}">${code}</div>`
|
||||
}
|
||||
}
|
||||
|
||||
export const renderPageContent = async (content: string) => {
|
||||
const md = new Markdown({
|
||||
html: false,
|
||||
linkify: true,
|
||||
})
|
||||
|
||||
md.use(handleImages)
|
||||
md.use(codeBlock)
|
||||
|
||||
const html = md.render(content)
|
||||
return { html }
|
||||
}
|
||||
|
||||
const stripHTML = (html: string) => {
|
||||
return html.replace(/<(?:.|\n)*?>/gm, "")
|
||||
}
|
||||
|
||||
export const getAutoExcerpt = (content: string) => {
|
||||
const indexOfMore = content.indexOf("<!--more-->")
|
||||
const md = new Markdown({
|
||||
html: false,
|
||||
linkify: true,
|
||||
})
|
||||
if (indexOfMore > -1) {
|
||||
content = content.substring(0, indexOfMore)
|
||||
return stripHTML(md.render(content))
|
||||
}
|
||||
return stripHTML(md.render(content)).slice(0, 400)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import dayjs from "dayjs"
|
||||
import { useMemo } from "react"
|
||||
import { PageVisibilityEnum } from "./types"
|
||||
|
||||
export const usePageVisibility = ({
|
||||
published,
|
||||
publishedAt,
|
||||
}: {
|
||||
published: boolean
|
||||
publishedAt: string | Date | null
|
||||
}) => {
|
||||
const visibility = useMemo<
|
||||
Omit<PageVisibilityEnum, PageVisibilityEnum.All>
|
||||
>(() => {
|
||||
return getPageVisibility({ published, publishedAt })
|
||||
}, [published, publishedAt])
|
||||
|
||||
return visibility
|
||||
}
|
||||
|
||||
export const getPageVisibility = ({
|
||||
published,
|
||||
publishedAt,
|
||||
}: {
|
||||
published: boolean
|
||||
publishedAt: string | Date | null
|
||||
}) => {
|
||||
if (!published) {
|
||||
return PageVisibilityEnum.Draft
|
||||
}
|
||||
if (published && publishedAt && dayjs(publishedAt).isBefore(new Date())) {
|
||||
return PageVisibilityEnum.Published
|
||||
}
|
||||
return PageVisibilityEnum.Scheduled
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export const promiseAll = (obj: Record<string, Promise<any>>) => {}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { GetServerSidePropsContext, GetServerSideProps } from "next"
|
||||
|
||||
class Redirect extends Error {
|
||||
constructor(public url: string) {
|
||||
super("")
|
||||
}
|
||||
}
|
||||
|
||||
class NotFound extends Error {}
|
||||
|
||||
export const redirect = (url: string) => new Redirect(url)
|
||||
|
||||
export const notFound = (message?: string) => new NotFound(message)
|
||||
|
||||
export const isNotFoundError = (error: unknown) => error instanceof NotFound
|
||||
|
||||
export const serverSidePropsHandler = <TProps extends object>(
|
||||
fn: (
|
||||
ctx: GetServerSidePropsContext
|
||||
) => Promise<{ props: TProps } | Redirect | NotFound>
|
||||
): GetServerSideProps => {
|
||||
return async (ctx) => {
|
||||
try {
|
||||
const result = await fn(ctx)
|
||||
if (result instanceof Redirect) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: result.url,
|
||||
permanent: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
if (result instanceof NotFound) {
|
||||
return {
|
||||
notFound: true,
|
||||
}
|
||||
}
|
||||
return result
|
||||
} catch (error: any) {
|
||||
console.log("serverSidePropsHandler error", error)
|
||||
const actualError = error.cause || error
|
||||
if (actualError instanceof Redirect) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: actualError.url,
|
||||
permanent: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
if (actualError instanceof NotFound) {
|
||||
return {
|
||||
notFound: true,
|
||||
}
|
||||
}
|
||||
ctx.res.statusCode = 500
|
||||
return {
|
||||
props: {
|
||||
error: error.message,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// @ts-nocheck
|
||||
globalThis._singletons = globalThis._singletons || {}
|
||||
|
||||
export const singleton = <T>(id: string, factory: () => T): T => {
|
||||
if (!globalThis._singletons[id]) {
|
||||
globalThis._singletons[id] = factory()
|
||||
}
|
||||
return globalThis._singletons[id]
|
||||
}
|
||||
|
||||
export const singletonAsync = <T>(
|
||||
id: string,
|
||||
factory: () => Promise<T>,
|
||||
enableSingleton = true
|
||||
): { readonly value: T; wait: Promise<void> } => {
|
||||
if (globalThis._singletons[id] && enableSingleton) {
|
||||
return {
|
||||
wait: Promise.resolve(),
|
||||
|
||||
get value() {
|
||||
return globalThis._singletons[id]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let ready = false
|
||||
|
||||
const wait = factory().then((value) => {
|
||||
ready = true
|
||||
globalThis._singletons[id] = value
|
||||
})
|
||||
|
||||
return {
|
||||
wait,
|
||||
|
||||
get value() {
|
||||
if (!ready) {
|
||||
throw new Error(`please await .wait before using the value of '${id}'`)
|
||||
}
|
||||
return globalThis._singletons[id]
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import create, { StoreApi } from "zustand"
|
||||
import createContext from "zustand/context"
|
||||
|
||||
export type Store = {
|
||||
loginModalOpened: boolean
|
||||
setLoginModalOpened: (open: boolean) => void
|
||||
|
||||
subscribeModalOpened: boolean
|
||||
setSubscribeModalOpened: (open: boolean) => void
|
||||
}
|
||||
|
||||
const { Provider, useStore } = createContext<StoreApi<Store>>()
|
||||
|
||||
export { useStore }
|
||||
|
||||
export const StoreProvider = Provider
|
||||
|
||||
export const createStore = () =>
|
||||
create<Store>((set) => ({
|
||||
loginModalOpened: false,
|
||||
setLoginModalOpened(open) {
|
||||
set({ loginModalOpened: open })
|
||||
},
|
||||
|
||||
subscribeModalOpened: false,
|
||||
setSubscribeModalOpened(open) {
|
||||
set({ subscribeModalOpened: open })
|
||||
},
|
||||
}))
|
||||
@@ -0,0 +1,28 @@
|
||||
import { OUR_DOMAIN } from "./env"
|
||||
|
||||
export const getTenant = (request: Request, search: URLSearchParams) => {
|
||||
const host = request.headers.get("host")
|
||||
|
||||
if (!OUR_DOMAIN) {
|
||||
throw new Error("missing OUR_DOMAIN env")
|
||||
}
|
||||
|
||||
if (search.has("tenant")) {
|
||||
return search.get("tenant")
|
||||
}
|
||||
|
||||
const OUR_DOMAIN_SUFFIX = `.${OUR_DOMAIN}`
|
||||
if (host) {
|
||||
if (host.endsWith(".fly.dev")) {
|
||||
return
|
||||
}
|
||||
if (host.endsWith(OUR_DOMAIN_SUFFIX)) {
|
||||
const subdomain = host.replace(OUR_DOMAIN_SUFFIX, "")
|
||||
return subdomain
|
||||
}
|
||||
if (host !== OUR_DOMAIN) {
|
||||
return host
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as trpc from "@trpc/server"
|
||||
import { IncomingMessage } from "http"
|
||||
import { AuthUser, getAuthUser } from "./auth.server"
|
||||
import { createGate, Gate } from "./gate.server"
|
||||
|
||||
export type TRPCContext = { user: AuthUser | null | undefined; gate: Gate }
|
||||
|
||||
export const getTRPCContext = async ({
|
||||
req,
|
||||
}: {
|
||||
req: IncomingMessage
|
||||
}): Promise<TRPCContext> => {
|
||||
const user = await getAuthUser(req)
|
||||
const gate = createGate({ user })
|
||||
return {
|
||||
user,
|
||||
gate,
|
||||
}
|
||||
}
|
||||
|
||||
export const createRouter = () => {
|
||||
return trpc.router<TRPCContext>()
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createReactQueryHooks } from "@trpc/react"
|
||||
import { withTRPC } from "@trpc/next"
|
||||
import type { AppRouter } from "~/router"
|
||||
|
||||
export const trpc = createReactQueryHooks<AppRouter>()
|
||||
|
||||
export const wrapTrpc = ({ ssr }: { ssr?: boolean } = {}) => {
|
||||
return withTRPC({
|
||||
config() {
|
||||
const url = "/api/trpc"
|
||||
|
||||
return {
|
||||
url,
|
||||
fetch(url, init) {
|
||||
return fetch(url, {
|
||||
...init,
|
||||
credentials: "same-origin",
|
||||
})
|
||||
},
|
||||
}
|
||||
},
|
||||
ssr,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
export type Site = {
|
||||
id: string
|
||||
name: string
|
||||
subdomain: string
|
||||
icon?: string | null
|
||||
}
|
||||
|
||||
export type SiteSubscription = {
|
||||
email?: boolean
|
||||
telegram?: boolean
|
||||
}
|
||||
|
||||
export type Viewer = {
|
||||
id: string
|
||||
name: string
|
||||
username: string
|
||||
email: string
|
||||
avatar?: string | null
|
||||
}
|
||||
|
||||
export enum PageVisibilityEnum {
|
||||
All = "all",
|
||||
Published = "published",
|
||||
Scheduled = "scheduled",
|
||||
Draft = "draft",
|
||||
}
|
||||
|
||||
export type PostOnSiteHome = {
|
||||
id: string
|
||||
title: string
|
||||
excerpt?: string | null
|
||||
autoExcerpt?: string | null
|
||||
slug: string
|
||||
publishedAt: string | Date
|
||||
}
|
||||
|
||||
export type Paginated<T> = {
|
||||
nodes: T[]
|
||||
total: number
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
export type Page = {
|
||||
id: string
|
||||
title: string
|
||||
contentHTML: string
|
||||
excerpt: string
|
||||
permalink: string
|
||||
publishedAt: Date
|
||||
published: boolean
|
||||
}
|
||||
|
||||
export type PostOnArchivesPage = {
|
||||
id: string
|
||||
title: string
|
||||
slug: string
|
||||
publishedAt: string | Date
|
||||
}
|
||||
|
||||
/**
|
||||
* The subscribe form data to store in loginToken
|
||||
*/
|
||||
export type SubscribeFormData = {
|
||||
email?: boolean
|
||||
telegram?: boolean
|
||||
siteId: string
|
||||
}
|
||||
|
||||
export type SiteNavigationItem = {
|
||||
id: string
|
||||
label: string
|
||||
url: string
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { R2_URL } from "./env"
|
||||
|
||||
export function getUserContentsUrl(filename: string): string
|
||||
export function getUserContentsUrl(filename: undefined | null): undefined
|
||||
export function getUserContentsUrl<T extends string | undefined | null>(
|
||||
filename: T
|
||||
): T
|
||||
export function getUserContentsUrl(filename: string | undefined | null) {
|
||||
if (!filename) return undefined
|
||||
return `${R2_URL}/${filename}`
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { IS_PROD } from "./constants"
|
||||
import { OUR_DOMAIN } from "./env"
|
||||
|
||||
type Truthy<T> = T extends false | "" | 0 | null | undefined ? never : T // from lodash
|
||||
|
||||
export function truthy<T>(value: T): value is Truthy<T> {
|
||||
return Boolean(value)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { validate } from "uuid"
|
||||
|
||||
export const isUUID = (id: string) => validate(id)
|
||||
Reference in New Issue
Block a user