Skip to content

Commit

Permalink
fix: pass event to useRuntimeConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Nov 15, 2024
1 parent 8eb79a5 commit f507ba7
Show file tree
Hide file tree
Showing 13 changed files with 107 additions and 109 deletions.
107 changes: 52 additions & 55 deletions modules/runtime/server/_social/bluesky.get.ts
Original file line number Diff line number Diff line change
@@ -1,73 +1,70 @@
import { AppBskyEmbedImages, AppBskyFeedPost, AtpAgent } from '@atproto/api'
import MagicString from 'magic-string'

export default defineLazyEventHandler(async () => {
const { identifier, password } = useRuntimeConfig().social.networks.bluesky
export default defineEventHandler(async event => {
const agent = new AtpAgent({ service: 'https://bsky.social' })
const { identifier, password } = useRuntimeConfig(event).social.networks.bluesky

await agent.login({
identifier,
password,
})

return defineEventHandler(async () => {
const posts = await agent.getAuthorFeed({ actor: identifier })
return Promise.all(
posts.data.feed
.filter(p => AppBskyFeedPost.isRecord(p.post.record) && p.post.author.handle === identifier && !p.reply && (!p.post.embed || AppBskyEmbedImages.isMain(p.post.embed)))
.map(p => {
const post = p.post.record as AppBskyFeedPost.Record
const embed = AppBskyEmbedImages.isMain(p.post.embed) ? p.post.embed : undefined
const text = new MagicString(post.text)
for (const facet of post.facets || []) {
const startIndex = [...post.text].findIndex(
(_, i) =>
Buffer.byteLength(post.text.slice(0, i + 1))
> facet.index.byteStart,
)
const endIndex = [...post.text].findIndex(
(_, i) =>
Buffer.byteLength(post.text.slice(0, i + 1))
>= facet.index.byteEnd,
)
for (const feature of facet.features) {
if (feature.$type === 'app.bsky.richtext.facet#link') {
text.appendRight(startIndex, `<a href="${feature.uri}">`)
text.appendLeft(endIndex === -1 ? post.text.length : endIndex + 1, '</a>')
continue
}
const posts = await agent.getAuthorFeed({ actor: identifier })
return Promise.all(
posts.data.feed
.filter(p => AppBskyFeedPost.isRecord(p.post.record) && p.post.author.handle === identifier && !p.reply && (!p.post.embed || AppBskyEmbedImages.isMain(p.post.embed)))
.map(p => {
const post = p.post.record as AppBskyFeedPost.Record
const embed = AppBskyEmbedImages.isMain(p.post.embed) ? p.post.embed : undefined
const text = new MagicString(post.text)
for (const facet of post.facets || []) {
const startIndex = [...post.text].findIndex(
(_, i) =>
Buffer.byteLength(post.text.slice(0, i + 1))
> facet.index.byteStart,
)
const endIndex = [...post.text].findIndex(
(_, i) =>
Buffer.byteLength(post.text.slice(0, i + 1))
>= facet.index.byteEnd,
)
for (const feature of facet.features) {
if (feature.$type === 'app.bsky.richtext.facet#link') {
text.appendRight(startIndex, `<a href="${feature.uri}">`)
text.appendLeft(endIndex === -1 ? post.text.length : endIndex + 1, '</a>')
continue
}
}
}

text.replaceAll(/[<>&]/g, r => ({
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
}[r]!))
text.replaceAll(/[<>&]/g, r => ({
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
}[r]!))

for (const match of post.text.matchAll(/\n\n/g)) {
text.overwrite(match.index!, match.index! + 2, '</p><p>')
}
for (const match of post.text.matchAll(/\n\n/g)) {
text.overwrite(match.index!, match.index! + 2, '</p><p>')
}

text.prepend('<p>')
text.append('</p>')
text.prepend('<p>')
text.append('</p>')

return {
network: 'bluesky' as const,
accountLink: `https://staging.bsky.app/profile/${p.post.author.handle}`,
avatar: p.post.author.avatar,
handle: p.post.author.displayName,
createdAt: post.createdAt,
permalink:
return {
network: 'bluesky' as const,
accountLink: `https://staging.bsky.app/profile/${p.post.author.handle}`,
avatar: p.post.author.avatar,
handle: p.post.author.displayName,
createdAt: post.createdAt,
permalink:
`https://staging.bsky.app/profile/${p.post.author.handle}/post`
+ p.post.uri.match(/(\/[^/]+)$/)?.[1],
html: text.toString().replace(/\n/g, '<br>'),
media: embed?.images?.map(i => ({
url: i.fullsize,
alt: i.alt,
})),
}
}),
)
})
html: text.toString().replace(/\n/g, '<br>'),
media: embed?.images?.map(i => ({
url: i.fullsize,
alt: i.alt,
})),
}
}),
)
})
67 changes: 32 additions & 35 deletions modules/runtime/server/_social/mastodon.get.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { createRestAPIClient } from 'masto'
import { parseURL, withProtocol } from 'ufo'

export default defineLazyEventHandler(async () => {
const acct = useRuntimeConfig().social.networks.mastodon.identifier
export default defineEventHandler(async event => {
const acct = useRuntimeConfig(event).social.networks.mastodon.identifier

const server = acct.split('@')[1]
if (!server) throw createError('Invalid Mastodon account identifier')
Expand All @@ -21,38 +21,35 @@ export default defineLazyEventHandler(async () => {
url: withProtocol(host!, protocol!),
})
const { id } = await client.v1.accounts.lookup({ acct })

return defineEventHandler(async () => {
const posts = await client.v1.accounts
.$select(id)
.statuses.list({ limit: 200 })
return Promise.all(
posts
.filter(p => p.content && !p.inReplyToId)
.map(p => ({
network: 'mastodon' as const,
accountLink: `https://elk.zone/${host}/@${p.account.acct}`,
avatar: p.account.avatar,
handle: p.account.displayName.replace(
/:([a-z-]+):/g,
(string, shortcode) => {
const emoji = p.account.emojis.find(
e => e.shortcode === shortcode,
)
if (!emoji) return string
return `<img src="${emoji.url}" style="height:1em" alt="${shortcode} emoji" />`
},
),
createdAt: p.createdAt,
permalink: p.url?.replace('https://', 'https://elk.zone/') ?? p.uri,
media: p.mediaAttachments.map(m => ({
url: m.url,
width: m.meta?.original?.width,
height: m.meta?.original?.height,
alt: m.description,
})),
html: p.content,
const posts = await client.v1.accounts
.$select(id)
.statuses.list({ limit: 200 })
return Promise.all(
posts
.filter(p => p.content && !p.inReplyToId)
.map(p => ({
network: 'mastodon' as const,
accountLink: `https://elk.zone/${host}/@${p.account.acct}`,
avatar: p.account.avatar,
handle: p.account.displayName.replace(
/:([a-z-]+):/g,
(string, shortcode) => {
const emoji = p.account.emojis.find(
e => e.shortcode === shortcode,
)
if (!emoji) return string
return `<img src="${emoji.url}" style="height:1em" alt="${shortcode} emoji" />`
},
),
createdAt: p.createdAt,
permalink: p.url?.replace('https://', 'https://elk.zone/') ?? p.uri,
media: p.mediaAttachments.map(m => ({
url: m.url,
width: m.meta?.original?.width,
height: m.meta?.original?.height,
alt: m.description,
})),
)
})
html: p.content,
})),
)
})
2 changes: 1 addition & 1 deletion modules/runtime/server/auth/github/[slug].ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { RuntimeConfig } from 'nuxt/schema'

export default defineEventHandler(async event => {
const config = useRuntimeConfig()
const config = useRuntimeConfig(event)
const slug = getRouterParam(event, 'slug')
const repo = slug && config.invites?.map?.[slug as keyof RuntimeConfig['invites']['map']]
if (!repo) {
Expand Down
2 changes: 1 addition & 1 deletion server/api/feedback.post.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export default defineEventHandler(async event => {
const config = useRuntimeConfig()
const config = useRuntimeConfig(event)
const { feedback } = await readBody(event)
if (!feedback) {
throw createError({ statusCode: 400, statusMessage: 'Missing feedback' })
Expand Down
1 change: 1 addition & 0 deletions server/api/idea.post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export default defineEventHandler(async event => {
}
const { idea } = await readBody(event)
await sendEmail(
event,
'Idea from website',
[`Idea from ${payload.name}:`, '', idea].join('\n'),
)
Expand Down
2 changes: 1 addition & 1 deletion server/api/question.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ export default defineEventHandler(async event => {
const { question } = await readBody(event)
if (!question) throw createError({ statusCode: 422 })
event.waitUntil(createTypefullyDraft(event, question).catch(console.error))
await sendEmail('Anonymous question', question)
await sendEmail(event, 'Anonymous question', question)
return null
})
4 changes: 2 additions & 2 deletions server/api/sponsors.get.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { getSponsors } from '../utils/sponsors'

export default defineCachedEventHandler(
async () => {
async event => {
if (import.meta.test) return []

const sponsors = await getSponsors()
const sponsors = await getSponsors(event)
return sponsors
.map(s => s.avatarUrl?.replace(/(\?|%3Fu).*$/, ''))
.filter((r): r is string => !!r)
Expand Down
4 changes: 2 additions & 2 deletions server/api/streams.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export default defineCachedEventHandler(async () => {
export default defineCachedEventHandler(async event => {
if (import.meta.test) return []

const config = useRuntimeConfig()
const config = useRuntimeConfig(event)
const token = await $fetch<TwitchTokenResponse>(
'https://id.twitch.tv/oauth2/token',
{
Expand Down
4 changes: 2 additions & 2 deletions server/routes/auth/[...provider].get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default defineEventHandler(async event => {
})
}

const config = useRuntimeConfig()
const config = useRuntimeConfig(event)
const { access_token } = await $fetch<{ access_token: string }>(
'https://github.com/login/oauth/access_token',
{
Expand Down Expand Up @@ -38,7 +38,7 @@ export default defineEventHandler(async event => {
console.error('viewer', err)
return {}
}),
getSponsors()
getSponsors(event)
.then(r => r.map(s => s.id))
.catch(err => {
console.error('sponsor', err)
Expand Down
2 changes: 1 addition & 1 deletion server/routes/v/[slug].ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export default defineEventHandler(async event => {
const config = useRuntimeConfig()
const config = useRuntimeConfig(event)
const slug = getRouterParam(event, 'slug')
if (!slug || !/^[\da-z]+$/.test(slug)) {
throw createError({ statusCode: 400, statusMessage: 'Missing slug' })
Expand Down
6 changes: 4 additions & 2 deletions server/utils/email.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
export function sendEmail (subject: string, body: string) {
import type { H3Event } from 'h3'

export function sendEmail (event: H3Event, subject: string, body: string) {
return $fetch('https://api.resend.com/email', {
method: 'POST',
headers: {
Authorization: `Bearer ${useRuntimeConfig().resendApiKey}`,
Authorization: `Bearer ${useRuntimeConfig(event).resendApiKey}`,
},
body: {
subject,
Expand Down
6 changes: 3 additions & 3 deletions server/utils/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface SessionData {
}

export function getUserSession (event: H3Event) {
const config = useRuntimeConfig()
const config = useRuntimeConfig(event)
return getSession<SessionData>(event, {
password: config.sessionPassword,
name: 'token',
Expand All @@ -17,7 +17,7 @@ export function getUserSession (event: H3Event) {
}

export function setUserSession (event: H3Event, data: any) {
const config = useRuntimeConfig()
const config = useRuntimeConfig(event)
return updateSession<SessionData>(
event,
{
Expand All @@ -30,7 +30,7 @@ export function setUserSession (event: H3Event, data: any) {
}

export function clearUserSession (event: H3Event) {
const config = useRuntimeConfig()
const config = useRuntimeConfig(event)
return clearSession(event, {
password: config.sessionPassword,
name: 'token',
Expand Down
9 changes: 5 additions & 4 deletions server/utils/sponsors.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { H3Event } from 'h3'
import { query } from './github'

interface Sponsor {
Expand All @@ -12,8 +13,8 @@ interface CacheEntry {
mtime: number
}

export async function getSponsors (): Promise<Sponsor[]> {
if (!useRuntimeConfig().github.token) return []
export async function getSponsors (event: H3Event): Promise<Sponsor[]> {
if (!useRuntimeConfig(event).github.token) return []
const entry: CacheEntry = ((await useStorage().getItem('sponsors')) as any) || {}

const ttl = 60
Expand All @@ -22,12 +23,12 @@ export async function getSponsors (): Promise<Sponsor[]> {
const expired = Date.now() - (entry.mtime || 0) > ttl
if (!entry.value || expired) {
entry.value = await query(
useRuntimeConfig().github.token,
useRuntimeConfig(event).github.token,
sponsorQuery,
).then(r => r.data?.user.sponsors.edges.map((e: any) => e.node) || [])

// my ID
entry.value.push({ id: useRuntimeConfig().github.id })
entry.value.push({ id: useRuntimeConfig(event).github.id })

// NuxtLabs
entry.value.push({
Expand Down

0 comments on commit f507ba7

Please sign in to comment.