Skip to content

Commit

Permalink
Housekeeping
Browse files Browse the repository at this point in the history
  • Loading branch information
davestewart committed Apr 18, 2023
1 parent 8a31102 commit 55ff83e
Show file tree
Hide file tree
Showing 13 changed files with 85 additions and 100 deletions.
9 changes: 5 additions & 4 deletions src/build/sockets/setup.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { Server } from 'http'
import { listen } from 'listhen'
import { useNuxt } from '@nuxt/kit'
import { Callback, SocketInstance, Handler } from '../../types'
import { Callback, SocketInstance } from '../../types'
import { createWebSocket } from './factory'
import { log } from '../../runtime/utils'
import { isObject, log } from '../../runtime/utils'

type SocketServer = ReturnType<typeof createWebSocket>

function isObject (data: any) {
return data && typeof data === 'object' && !Array.isArray(data)
type Handler = {
channel: string
callback: Callback
}

function makeChannelBroker (ws: SocketServer) {
Expand Down
67 changes: 36 additions & 31 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,42 @@ import * as Path from 'path'
import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'
import { MountOptions } from '@nuxt/content'
import { Nuxt } from '@nuxt/schema'
import type { SourceManager } from './runtime/assets/source'
import {
log,
list,
isImage,
makeIgnores,
matchTokens,
removeFolder,
toPath,
} from './runtime/utils'
import { defaults } from './runtime/options'
import { moduleKey, moduleName } from './runtime/config'
import { log, list, isImage, makeIgnores, matchTokens, removeFolder, toPath } from './runtime/utils'
import { setupSocketServer } from './build/sockets/setup'
import { makeSourceManager } from './runtime/assets/source'
import { makeAssetsManager } from './runtime/assets/public'
import { rewriteContent } from './runtime/content/parsed'
import { ImageSize } from './types'
import type { ImageSize } from './types'

const resolve = createResolver(import.meta.url).resolve

const meta = {
moduleName: 'nuxt-content-assets',
moduleKey: 'contentAssets',
compatibility: {
nuxt: '^3.0.0'
}
}

const defaults: ModuleOptions = {
// inject image size into the rendered html
imageSize: 'style',

// treat these extensions as content
contentExtensions: 'md csv ya?ml json',

// output debug messages
debug: false,
}

export interface ModuleOptions {
imageSize?: string | string[] | false
contentExtensions: string | string[],
contentExtensions?: string | string[],
debug?: boolean
}

export default defineNuxtModule<ModuleOptions>({
meta: {
name: moduleName,
configKey: moduleKey,
compatibility: {
nuxt: '^3.0.0'
}
},
meta,

defaults,

Expand Down Expand Up @@ -67,14 +69,17 @@ export default defineNuxtModule<ModuleOptions>({
// options
// ---------------------------------------------------------------------------------------------------------------------

// @ts-ignore
// set up content ignores
nuxt.options.content ||= {}
if (nuxt.options.content) {
nuxt.options.content.ignores ||= []
const { contentExtensions } = options
if (contentExtensions) {
// @ts-ignore
nuxt.options.content ||= {}
if (nuxt.options.content) {
nuxt.options.content.ignores ||= []
}
const ignores = makeIgnores(contentExtensions)
nuxt.options.content?.ignores.push(ignores)
}
const ignores = makeIgnores(options.contentExtensions)
nuxt.options.content?.ignores.push(ignores)

// convert image size hints to array
const imageFlags: ImageSize = matchTokens(options.imageSize) as ImageSize
Expand Down Expand Up @@ -132,7 +137,7 @@ export default defineNuxtModule<ModuleOptions>({
? assets.getAsset(absTrg)
: null

// 1. the new asset; this HAS to go second, as it overwrites image size
// 2. the new asset; this HAS to go second, as it overwrites image size
const newAsset = assets.setAsset(absTrg)

// sizes
Expand Down Expand Up @@ -182,11 +187,11 @@ export default defineNuxtModule<ModuleOptions>({
: null

// ---------------------------------------------------------------------------------------------------------------------
// sources setup
// sources
// ---------------------------------------------------------------------------------------------------------------------

// create source managers
const managers: Record<string, SourceManager> = {}
const managers: Record<string, ReturnType<typeof makeSourceManager>> = {}
for (const [key, source] of Object.entries(sources)) {
// debug
if (options.debug) {
Expand Down Expand Up @@ -240,7 +245,7 @@ export default defineNuxtModule<ModuleOptions>({

// make config available to nitro
config.virtual ||= {}
config.virtual[`#${moduleName}`] = () => {
config.virtual[`#${meta.moduleName}`] = () => {
return virtualConfig
}

Expand Down
25 changes: 7 additions & 18 deletions src/runtime/assets/source.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,12 @@
import * as Path from 'path'
import { createStorage, WatchEvent, Storage } from 'unstorage'
import { MountOptions } from '@nuxt/content'
import githubDriver, { GithubOptions } from 'unstorage/drivers/github'
import fsDriver, { FSStorageOptions } from 'unstorage/drivers/fs'
import { MountOptions } from '@nuxt/content'
import {
warn,
isAsset,
toPath,
removeFile,
copyFile,
writeBlob,
writeFile,
deKey,
isExcluded,
} from '../utils'
import { createStorage, WatchEvent, Storage } from 'unstorage'
import { warn, isAsset, toPath, removeFile, copyFile, writeBlob, writeFile, deKey, isExcluded } from '../utils'

/**
* Helper function to determine valid ids
* @param id
*/
function isAssetId (id: string) {
const path = toPath(id)
Expand Down Expand Up @@ -84,19 +73,19 @@ export function makeSourceManager (key: string, source: MountOptions, publicPath
}

// relative source file path from key
function getRelSrc(key: string) {
function getRelSrc (key: string) {
return toPath(key)
.replace(/\w+/, '')
.replace(source.prefix || '', '')
}

// absolute source file path from key
function getAbsSrc(key: string) {
function getAbsSrc (key: string) {
return Path.join(source.base, getRelSrc(key))
}

// relative target file path from key
function getRelTrg(key: string) {
function getRelTrg (key: string) {
return Path.join(source.prefix || '', toPath(deKey(key)))
}

Expand Down Expand Up @@ -167,7 +156,7 @@ export function makeSourceManager (key: string, source: MountOptions, publicPath
const keys = await getKeys()
const paths: string[] = []

// copy assets to temp path
// copy assets to public path
for (const key of keys) {
const path = await copyItem(key)
paths.push(path)
Expand Down
2 changes: 0 additions & 2 deletions src/runtime/config.ts

This file was deleted.

1 change: 0 additions & 1 deletion src/runtime/content/parsed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ export function rewriteContent (path: string, asset: AssetConfig): ParsedContent
const { tag, props } = node
if (tag === 'img' && props?.src?.startsWith(srcAttr)) {
props.src = buildQuery(srcAttr, `time=${Date.now()}`)
console.log(props.src)
if (props.width) {
props.width = width
}
Expand Down
22 changes: 0 additions & 22 deletions src/runtime/options.ts

This file was deleted.

8 changes: 1 addition & 7 deletions src/runtime/sockets/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import { defineNuxtPlugin, refreshNuxtData, useRuntimeConfig } from '#imports'

interface AssetMessage {
event: string
src: string
width?: string
height?: string
}
import { AssetMessage } from '../../types'

/**
* Clientside plugin to receive socket messages
Expand Down
21 changes: 21 additions & 0 deletions src/runtime/utils/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { matchTokens } from './string'

/**
* Common extensions
*/
export const extensions = {
// used to get image size
image: matchTokens('png jpg jpeg gif svg webp ico'),

// unused for now
media: matchTokens('mp3 m4a wav mp4 mov webm ogg avi flv avchd'),
}

/**
* Create a Nuxt Content ignore string
*/
export function makeIgnores (extensions: string | string[]): string {
const matched = matchTokens(extensions)
const ignored = matched.join('|')
return `[^:]+\\.(?!(${ignored})$)`
}
1 change: 1 addition & 0 deletions src/runtime/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from './build'
export * from './fs'
export * from './string'
export * from './object'
export { makeIgnores } from './config'
5 changes: 4 additions & 1 deletion src/runtime/utils/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function walk (node: any, callback: WalkCallback, filter?: WalkFilter): v
visit(value, callback, node, index)
})
}
else if (typeof node === 'object' && node !== null) {
else if (isObject(node)) {
Object.keys(node).forEach(key => {
visit(node[key], callback, node, key)
})
Expand All @@ -43,3 +43,6 @@ export function walk (node: any, callback: WalkCallback, filter?: WalkFilter): v
visit(node, callback, { node }, 'node')
}

export function isObject (data: any) {
return data && typeof data === 'object' && !Array.isArray(data)
}
3 changes: 2 additions & 1 deletion src/runtime/utils/path.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Path from 'path'
import { extensions } from '../options'

import { extensions } from './config'

/**
* Parses the query string from a path
Expand Down
8 changes: 0 additions & 8 deletions src/runtime/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,3 @@ export function deKey (path: string) {
return path.replace(/^[^:]+:/, '')
}

/**
* Create a Nuxt Content ignore string
*/
export function makeIgnores (extensions: string | string[]): string {
const matched = matchTokens(extensions)
const ignored = matched.join('|')
return `[^:]+\\.(?!(${ignored})$)`
}
13 changes: 8 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
export type Callback = (data: any) => void

export type Handler = {
channel: string
callback: Callback
}

export interface SocketInstance {
send: (data: any) => SocketInstance
addHandler: (handler: Callback) => SocketInstance
Expand All @@ -19,6 +14,14 @@ export type AssetConfig = {
height?: number
}


export interface AssetMessage {
event: 'update' | 'remove' | 'refresh'
src?: string
width?: string
height?: string
}

export interface ParsedContent {
/**
* The storage id of the file
Expand Down

0 comments on commit 55ff83e

Please sign in to comment.