Skip to content

Commit

Permalink
feat: add plugins folder feature
Browse files Browse the repository at this point in the history
  • Loading branch information
zardoy committed Dec 17, 2024
1 parent 69e2a72 commit 75dc7d1
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/lib/modules/pluginsFolder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import path from 'path'
import fs from 'fs'

let loadedPlugins: Record<string, any> = {}

export const player = function (player: Player, serv: Server) {
for (const plugin of Object.values(loadedPlugins)) {
plugin.player.call(plugin, player, serv)
}
}

export const entity = function (entity: Entity, serv: Server) {
for (const plugin of Object.values(loadedPlugins)) {
plugin.entity.call(plugin, entity, serv)
}
}

export const server = async function (serv: Server, settings: Options) {
loadedPlugins = {}
if (!settings.pluginsFolder || !settings.worldFolder) return
const plugins = fs.readdirSync(path.join(settings.worldFolder, 'plugins'))

for (const plugin of plugins) {
// match .js but not .disabled.js
if (plugin.match(/\.[js,mjs]$/) && !plugin.includes('.disabled.')) {
const pluginName = plugin.split('.').slice(0, -1).join('.')
const moduleContent = fs.readFileSync(path.join(settings.worldFolder, 'plugins', plugin), 'utf8')
const module = await loadPlugin(moduleContent)
loadedPlugins[pluginName] = module
serv.info(`Loading plugin: ${pluginName}`)
module.server.call(module, serv, settings)
}
}
}

const loadPlugin = (moduleContent: string) => {
// remove shebang
moduleContent = moduleContent.replace(/^#!.*\n/, '')
const blob = new Blob([moduleContent], { type: 'application/javascript' })
const moduleUrl = URL.createObjectURL(blob)

return import(moduleUrl).then(module => {
URL.revokeObjectURL(moduleUrl)
return module
})
}
1 change: 1 addition & 0 deletions src/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ declare global {
_client: Client
}
interface Options {
pluginsFolder: boolean
version: string
/**
* @deprecated will be reworked in the future
Expand Down

0 comments on commit 75dc7d1

Please sign in to comment.