@tylix/core 1.4.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,351 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { logger, LOG_LEVELS, plainLogFields } from './logger.js'
4
+
5
+ // Log channels, the way Laravel has them.
6
+ //
7
+ // import { Log } from '@tylix/core'
8
+ // Log.info('Invoice sent', { invoiceId: 12 })
9
+ // Log.channel('payments').error('Charge failed', { error })
10
+ // Log.stack(['daily', 'slack']).critical('Disk full')
11
+ //
12
+ // tylix.config:
13
+ //
14
+ // logging: {
15
+ // default: 'stack', // LOG_CHANNEL
16
+ // channels: {
17
+ // stack: { driver: 'stack', channels: ['console', 'daily'] }, // LOG_STACK
18
+ // single: { driver: 'single', path: 'storage/logs/tylix.log' },
19
+ // daily: { driver: 'daily', path: 'storage/logs/tylix.log', days: 14 },
20
+ // console: { driver: 'console' },
21
+ // null: { driver: 'null' },
22
+ // payments: { driver: 'daily', path: 'storage/logs/payments.log', level: 'warning' },
23
+ // slack: { driver: 'custom', via: (config) => ({ write(entry) { ... } }) },
24
+ // },
25
+ // }
26
+ //
27
+ // File channels write one line per entry, like Laravel:
28
+ //
29
+ // [2026-11-15 10:22:01] production.ERROR: Charge failed {"orderId":7} {"requestId":"..."}
30
+ //
31
+ // followed by the stack trace when the context holds an Error.
32
+
33
+ export const DEFAULT_LOG_PATH = 'storage/logs/tylix.log'
34
+
35
+ export const DEFAULT_LOG_CHANNELS = {
36
+ stack: { driver: 'stack', channels: ['console', 'daily'] },
37
+ single: { driver: 'single', path: DEFAULT_LOG_PATH },
38
+ daily: { driver: 'daily', path: DEFAULT_LOG_PATH, days: 14 },
39
+ console: { driver: 'console' },
40
+ stderr: { driver: 'console', stream: 'stderr' },
41
+ null: { driver: 'null' },
42
+ }
43
+
44
+ const pad = (n) => String(n).padStart(2, '0')
45
+ const localDate = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
46
+ const localTime = (d) => `${localDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
47
+
48
+ // Splits an entry's fields into the context the caller passed and the
49
+ // extras Tylix adds (requestId), so the line reads like Laravel's.
50
+ const EXTRA_KEYS = new Set(['requestId'])
51
+
52
+ export function formatLogLine(entry, environment = 'local') {
53
+ const context = {}
54
+ const extra = {}
55
+ const traces = []
56
+ for (const [key, value] of Object.entries(entry.fields ?? {})) {
57
+ if (value === undefined) continue
58
+ if (value instanceof Error && value.stack) traces.push(value.stack)
59
+ ;(EXTRA_KEYS.has(key) ? extra : context)[key] = value
60
+ }
61
+ const json = (fields) => (Object.keys(fields).length ? JSON.stringify(plainLogFields(fields)) : '[]')
62
+ let line = `[${localTime(entry.time)}] ${environment}.${entry.level === 'warn' ? 'WARNING' : entry.level.toUpperCase()}: ${entry.message} ${json(context)} ${json(extra)}\n`
63
+ for (const trace of traces) line += `[stacktrace]\n${trace}\n`
64
+ return line
65
+ }
66
+
67
+ // Appends to a file, batched once per turn of the event loop. What is left
68
+ // at exit is written synchronously, so no line is lost on a crash.
69
+ const pendingFiles = new Map()
70
+ let exitHookInstalled = false
71
+
72
+ function flushFile(file) {
73
+ const lines = pendingFiles.get(file)
74
+ if (!lines?.length) return
75
+ pendingFiles.set(file, [])
76
+ fs.mkdirSync(path.dirname(file), { recursive: true })
77
+ fs.appendFileSync(file, lines.join(''))
78
+ }
79
+
80
+ export function flushLogFiles() {
81
+ for (const file of pendingFiles.keys()) {
82
+ try {
83
+ flushFile(file)
84
+ } catch {
85
+ // the disk went away: nothing more to do at exit
86
+ }
87
+ }
88
+ }
89
+
90
+ function appendLine(file, text, onError) {
91
+ if (!exitHookInstalled) {
92
+ exitHookInstalled = true
93
+ process.on('exit', flushLogFiles)
94
+ }
95
+ let lines = pendingFiles.get(file)
96
+ if (!lines) pendingFiles.set(file, (lines = []))
97
+ lines.push(text)
98
+ if (lines.length === 1) {
99
+ setImmediate(() => {
100
+ try {
101
+ flushFile(file)
102
+ } catch (err) {
103
+ onError(err)
104
+ }
105
+ })
106
+ }
107
+ }
108
+
109
+ // Deletes app-YYYY-MM-DD.log files older than `days` days.
110
+ function pruneDailyFiles(basePath, days) {
111
+ if (!days || days < 1) return
112
+ const dir = path.dirname(basePath)
113
+ const ext = path.extname(basePath)
114
+ const stem = path.basename(basePath, ext)
115
+ const pattern = new RegExp(`^${stem.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}-(\\d{4}-\\d{2}-\\d{2})${ext.replace('.', '\\.')}$`)
116
+ const cutoff = new Date()
117
+ cutoff.setDate(cutoff.getDate() - days)
118
+ const oldest = localDate(cutoff)
119
+ let names = []
120
+ try {
121
+ names = fs.readdirSync(dir)
122
+ } catch {
123
+ return
124
+ }
125
+ for (const name of names) {
126
+ const match = pattern.exec(name)
127
+ if (match && match[1] <= oldest) {
128
+ try {
129
+ fs.unlinkSync(path.join(dir, name))
130
+ } catch {
131
+ // already gone
132
+ }
133
+ }
134
+ }
135
+ }
136
+
137
+ export function dailyLogPath(basePath, date = new Date()) {
138
+ const ext = path.extname(basePath)
139
+ return path.join(path.dirname(basePath), `${path.basename(basePath, ext)}-${localDate(date)}${ext}`)
140
+ }
141
+
142
+ function fileTransport(name, file, { environment, level, daily = false, days = 14, format = 'line' }) {
143
+ let lastDay = null
144
+ const transport = {
145
+ name,
146
+ level,
147
+ path: file,
148
+ daily,
149
+ write(entry) {
150
+ let target = file
151
+ if (daily) {
152
+ target = dailyLogPath(file, entry.time)
153
+ const day = localDate(entry.time)
154
+ if (day !== lastDay) {
155
+ lastDay = day
156
+ pruneDailyFiles(file, days)
157
+ }
158
+ }
159
+ const text =
160
+ format === 'json'
161
+ ? JSON.stringify({ time: entry.time.toISOString(), env: environment, level: entry.level, msg: entry.message, ...plainLogFields(entry.fields) }) + '\n'
162
+ : formatLogLine(entry, environment)
163
+ appendLine(target, text, (err) => reportFileFailure(name, target, err))
164
+ },
165
+ }
166
+ return transport
167
+ }
168
+
169
+ // A file that can't be written (read-only disk, no permission) is
170
+ // reported once on stderr; the app keeps running and other channels still
171
+ // get every entry.
172
+ const reportedFiles = new Set()
173
+ function reportFileFailure(channel, file, err) {
174
+ if (reportedFiles.has(file)) return
175
+ reportedFiles.add(file)
176
+ try {
177
+ process.stderr.write(`[tylix] log channel "${channel}" can't write ${file}: ${err?.message ?? err}\n`)
178
+ } catch {
179
+ // nowhere left to report it
180
+ }
181
+ }
182
+
183
+ const customDrivers = new Map()
184
+
185
+ function buildChannel(name, channels, context, seen = new Set()) {
186
+ const config = channels[name]
187
+ if (!config) throw new Error(`Log channel "${name}" is not defined. Add it to logging.channels in tylix.config, or use one of: ${Object.keys(channels).join(', ')}.`)
188
+ if (seen.has(name)) throw new Error(`Log channel "${name}" includes itself.`)
189
+ const level = config.level
190
+ if (level !== undefined && !(level in LOG_LEVELS)) throw new Error(`Log channel "${name}": unknown level "${level}".`)
191
+ const resolve = (file) => path.resolve(context.baseDir, file ?? DEFAULT_LOG_PATH)
192
+
193
+ switch (config.driver) {
194
+ case 'stack': {
195
+ const names = config.channels ?? []
196
+ const next = new Set(seen).add(name)
197
+ const members = names.flatMap((member) => buildChannel(member, channels, context, next))
198
+ return level ? members.map((t) => ({ ...t, write: t.write, level: maxLevel(t.level, level) })) : members
199
+ }
200
+ case 'single':
201
+ return [fileTransport(name, resolve(config.path), { environment: context.environment, level, format: config.format })]
202
+ case 'daily':
203
+ return [
204
+ fileTransport(name, resolve(config.path), {
205
+ environment: context.environment,
206
+ level,
207
+ daily: true,
208
+ days: config.days ?? 14,
209
+ format: config.format,
210
+ }),
211
+ ]
212
+ case 'console': {
213
+ const base = logger.consoleTransport
214
+ if (!level && config.stream !== 'stderr') return [base]
215
+ return [
216
+ {
217
+ name,
218
+ level,
219
+ write: (entry) => base.write(config.stream === 'stderr' ? { ...entry, toStderr: true } : entry),
220
+ },
221
+ ]
222
+ }
223
+ case 'null':
224
+ return []
225
+ case 'custom': {
226
+ if (typeof config.via !== 'function') throw new Error(`Log channel "${name}": a custom channel needs via: (config) => ({ write(entry) {} }).`)
227
+ return [wrapCustom(name, config.via(config, context), level)]
228
+ }
229
+ default: {
230
+ const factory = customDrivers.get(config.driver)
231
+ if (!factory) {
232
+ throw new Error(
233
+ `Log channel "${name}": unknown driver "${config.driver}". Use stack, single, daily, console, null or custom, or register one with Log.extend().`,
234
+ )
235
+ }
236
+ return [wrapCustom(name, factory(config, context), level)]
237
+ }
238
+ }
239
+ }
240
+
241
+ function maxLevel(a, b) {
242
+ if (!a) return b
243
+ return LOG_LEVELS[a] >= LOG_LEVELS[b] ? a : b
244
+ }
245
+
246
+ function wrapCustom(name, made, level) {
247
+ const write = typeof made === 'function' ? made : made?.write?.bind(made)
248
+ if (typeof write !== 'function') throw new Error(`Log channel "${name}" must return a function or { write(entry) }.`)
249
+ return { name, level: maxLevel(made?.level, level), write }
250
+ }
251
+
252
+ // The resolved logging settings, set by configureLogging().
253
+ const state = {
254
+ channels: DEFAULT_LOG_CHANNELS,
255
+ defaultChannel: null,
256
+ context: { baseDir: process.cwd(), environment: 'local' },
257
+ cache: new Map(),
258
+ }
259
+
260
+ function channelTransports(name) {
261
+ if (!state.cache.has(name)) state.cache.set(name, buildChannel(name, state.channels, state.context))
262
+ return state.cache.get(name)
263
+ }
264
+
265
+ // Reads config.logging and points the app logger at its default channel.
266
+ // Called by "tylix dev", "tylix start" and the workers. Until it runs, the
267
+ // logger writes to the console only.
268
+ export function configureLogging(settings = {}, { baseDir = process.cwd(), environment = 'local' } = {}) {
269
+ state.channels = { ...DEFAULT_LOG_CHANNELS, ...(settings.channels ?? {}) }
270
+ state.context = { baseDir, environment }
271
+ state.cache = new Map()
272
+ const defaultChannel = settings.default ?? 'stack'
273
+ if (settings.stack && state.channels.stack?.driver === 'stack' && !settings.channels?.stack) {
274
+ state.channels.stack = { ...state.channels.stack, channels: settings.stack }
275
+ }
276
+ state.defaultChannel = defaultChannel
277
+ logger.configure({ transports: channelTransports(defaultChannel) })
278
+ return { default: defaultChannel, transports: channelTransports(defaultChannel) }
279
+ }
280
+
281
+ // Every file the configured channels write to, for "tylix log:tail".
282
+ export function logFiles() {
283
+ const files = []
284
+ for (const name of Object.keys(state.channels)) {
285
+ let transports
286
+ try {
287
+ transports = channelTransports(name)
288
+ } catch {
289
+ continue
290
+ }
291
+ for (const t of transports) {
292
+ if (!t.path) continue
293
+ const file = t.daily ? dailyLogPath(t.path) : t.path
294
+ if (!files.some((f) => f.path === file)) files.push({ channel: t.name ?? name, path: file, base: t.path, daily: t.daily })
295
+ }
296
+ }
297
+ return files
298
+ }
299
+
300
+ export const Log = {
301
+ debug: (message, context) => logger.debug(message, context),
302
+ info: (message, context) => logger.info(message, context),
303
+ notice: (message, context) => logger.notice(message, context),
304
+ warning: (message, context) => logger.warning(message, context),
305
+ warn: (message, context) => logger.warn(message, context),
306
+ error: (message, context) => logger.error(message, context),
307
+ critical: (message, context) => logger.critical(message, context),
308
+ alert: (message, context) => logger.alert(message, context),
309
+ emergency: (message, context) => logger.emergency(message, context),
310
+ log: (level, message, context) => logger.log(level, message, context),
311
+
312
+ // A logger that writes to one named channel only.
313
+ channel(name) {
314
+ return logger.withTransports(channelTransports(name))
315
+ },
316
+
317
+ // A logger that writes to several channels at once.
318
+ stack(names) {
319
+ return logger.withTransports(names.flatMap((name) => channelTransports(name)))
320
+ },
321
+
322
+ // A logger for a channel defined on the spot:
323
+ // Log.build({ driver: 'single', path: 'storage/logs/import.log' })
324
+ build(config) {
325
+ const name = config.name ?? 'on-demand'
326
+ return logger.withTransports(buildChannel(name, { ...state.channels, [name]: config }, state.context))
327
+ },
328
+
329
+ // Fields added to every later entry, on every channel.
330
+ withContext(context) {
331
+ logger.withContext(context)
332
+ return Log
333
+ },
334
+ withoutContext(keys) {
335
+ logger.withoutContext(keys)
336
+ return Log
337
+ },
338
+
339
+ // Registers a driver: Log.extend('slack', (config) => ({ write(entry) {...} }))
340
+ // then logging.channels.alerts = { driver: 'slack', url: ... }.
341
+ extend(driver, factory) {
342
+ if (typeof factory !== 'function') throw new Error('Log.extend(driver, factory): factory must be a function.')
343
+ customDrivers.set(driver, factory)
344
+ state.cache = new Map()
345
+ if (state.defaultChannel) logger.configure({ transports: channelTransports(state.defaultChannel) })
346
+ return Log
347
+ },
348
+
349
+ // Writes pending file lines now (tests, before exiting a script).
350
+ flush: flushLogFiles,
351
+ }
@@ -0,0 +1,81 @@
1
+ import type { Router } from '../router/Router.js'
2
+ import type { Logger, LogEntry, LogTransport } from '../observability/index.js'
3
+
4
+ export type PluginHook = 'config' | 'register' | 'routes' | 'boot' | 'close'
5
+ export declare const PLUGIN_HOOKS: PluginHook[]
6
+
7
+ export interface PluginContext {
8
+ name: string
9
+ baseDir: string
10
+ config: Record<string, any>
11
+ production: boolean
12
+ /** The app router (routes registered here show in the dev banner). */
13
+ router: Router
14
+ /** Global middleware: router.use(). */
15
+ use(middleware: (req: any, res: any, next: () => unknown) => unknown): void
16
+ /** Wraps a handler so it needs a signed-in user. */
17
+ auth<H extends (...args: any[]) => any>(handler: H): H
18
+ /** A logger whose entries carry { plugin: name }. */
19
+ logger: Logger
20
+ addReadinessCheck(name: string, check: () => unknown | Promise<unknown>, options?: { timeoutMs?: number }): () => void
21
+ }
22
+
23
+ export interface PluginCommand {
24
+ description?: string
25
+ usage?: string
26
+ run(args: string[], context: { baseDir: string; config: Record<string, any> }): unknown | Promise<unknown>
27
+ }
28
+
29
+ export interface DeployAdapterContext {
30
+ baseDir: string
31
+ config: Record<string, any>
32
+ language: 'typescript' | 'javascript'
33
+ packageManager: string
34
+ appName: string
35
+ /** Static export (tylix export) instead of a Node server. */
36
+ static: boolean
37
+ }
38
+ export interface DeployAdapter {
39
+ name: string
40
+ label: string
41
+ /** Files to write, relative to the project root. */
42
+ files(context: DeployAdapterContext): Record<string, string> | Promise<Record<string, string>>
43
+ /** Printed after the files are written. */
44
+ nextSteps?(context: DeployAdapterContext): string[]
45
+ /** Hosts that only serve files: needs a static export. */
46
+ static?: boolean
47
+ }
48
+
49
+ export interface TylixPlugin {
50
+ name?: string
51
+ /** Change the config before the app starts. Return keys to merge, or change it in place. */
52
+ config?(config: Record<string, any>): void | Record<string, any> | Promise<void | Record<string, any>>
53
+ /** Before the app's routes: middleware, readiness checks, services. */
54
+ register?(context: PluginContext): unknown | Promise<unknown>
55
+ /** After the app's API routes, before pages. */
56
+ routes?(router: Router, context: PluginContext): unknown | Promise<unknown>
57
+ /** Once the app is built. */
58
+ boot?(app: any): unknown | Promise<unknown>
59
+ /** On shutdown, in reverse order. */
60
+ close?(): unknown | Promise<unknown>
61
+ logDrivers?: Record<string, (config: any, context: { baseDir: string; environment: string }) => LogTransport | ((entry: LogEntry) => void)>
62
+ commands?: Record<string, PluginCommand>
63
+ deployAdapters?: Record<string, DeployAdapter>
64
+ }
65
+
66
+ export interface LoadedPlugin extends TylixPlugin {
67
+ name: string
68
+ source: string
69
+ }
70
+
71
+ export declare function definePlugin<P extends TylixPlugin>(plugin: P): P
72
+ export declare function loadPlugins(baseDir: string, config?: { plugins?: unknown[] }): Promise<LoadedPlugin[]>
73
+ export declare function createPluginHost(plugins?: LoadedPlugin[]): {
74
+ plugins: LoadedPlugin[]
75
+ applyConfig<C extends Record<string, any>>(config: C): Promise<C>
76
+ run(hook: PluginHook, ...args: unknown[]): Promise<void>
77
+ runWith(hook: PluginHook, makeArgs: (plugin: LoadedPlugin) => unknown[]): Promise<void>
78
+ close(): Promise<void>
79
+ collect<K extends 'commands' | 'logDrivers' | 'deployAdapters'>(property: K): Map<string, { plugin: string; value: NonNullable<TylixPlugin[K]>[string] }>
80
+ describe(): Array<{ name: string; source: string; hooks: PluginHook[]; commands: string[]; logDrivers: string[]; deployAdapters: string[] }>
81
+ }
@@ -0,0 +1,200 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { createRequire } from 'node:module'
4
+ import { pathToFileURL } from 'node:url'
5
+
6
+ // Plugins add to an app without editing it: routes, middleware, log
7
+ // drivers, CLI commands, deployment adapters, config changes.
8
+ //
9
+ // // tylix.config
10
+ // import sentry from '@acme/tylix-sentry'
11
+ // export default defineConfig({
12
+ // plugins: [
13
+ // sentry({ dsn: process.env.SENTRY_DSN }), // an object or factory result
14
+ // '@acme/tylix-audit', // a package (default export)
15
+ // ['./plugins/banner.js', { text: 'Hi' }], // a file, with options
16
+ // ],
17
+ // })
18
+ //
19
+ // Files in app/plugins/ are loaded too, in name order (skip one with a
20
+ // leading underscore).
21
+ //
22
+ // import { definePlugin } from '@tylix/core'
23
+ // export default definePlugin({
24
+ // name: 'audit',
25
+ // config(config) { return { observability: { ...config.observability, slowRequestMs: 500 } } },
26
+ // register({ use, logger }) { use((req, res, next) => { ...; return next() }) },
27
+ // routes(router, { auth }) { router.get('/api/audit', auth(handler)) },
28
+ // boot(app) {},
29
+ // close() {},
30
+ // logDrivers: { slack: (config) => ({ write(entry) {} }) },
31
+ // commands: { 'audit:prune': { description: 'Delete old rows', run(args, ctx) {} } },
32
+ // deployAdapters: { fly: { name: 'fly', label: 'Fly.io', files(ctx) { return { 'fly.toml': '...' } } } },
33
+ // })
34
+
35
+ export const PLUGIN_HOOKS = ['config', 'register', 'routes', 'boot', 'close']
36
+
37
+ export function definePlugin(plugin) {
38
+ return plugin
39
+ }
40
+
41
+ const PLUGIN_FILE = /\.(js|mjs|ts)$/
42
+ const SKIP_FILE = /(\.d\.ts$|\.test\.(js|ts)$|^_|^\.)/
43
+
44
+ async function importSpecifier(baseDir, specifier) {
45
+ if (specifier.startsWith('.') || path.isAbsolute(specifier)) {
46
+ return import(pathToFileURL(path.resolve(baseDir, specifier)).href)
47
+ }
48
+ // A package, resolved from the project (not from @tylix/core).
49
+ const require = createRequire(path.join(baseDir, 'package.json'))
50
+ let resolved
51
+ try {
52
+ resolved = require.resolve(specifier)
53
+ } catch {
54
+ throw new Error(`Plugin "${specifier}" is not installed. Run: npm install ${specifier}`)
55
+ }
56
+ return import(pathToFileURL(resolved).href)
57
+ }
58
+
59
+ // A module's plugin: its default export, or an export named "plugin".
60
+ // A function is a factory and gets the options.
61
+ function fromModule(mod, options, source) {
62
+ const value = mod?.default ?? mod?.plugin
63
+ if (value === undefined) throw new Error(`${source} has no default export (the plugin).`)
64
+ return typeof value === 'function' ? value(options ?? {}) : value
65
+ }
66
+
67
+ function normalize(plugin, source, index) {
68
+ if (!plugin || typeof plugin !== 'object') throw new Error(`Plugin ${source} must be an object, got ${typeof plugin}.`)
69
+ for (const hook of PLUGIN_HOOKS) {
70
+ if (plugin[hook] !== undefined && typeof plugin[hook] !== 'function') throw new Error(`Plugin ${plugin.name ?? source}: ${hook} must be a function.`)
71
+ }
72
+ const name = plugin.name ?? (typeof source === 'string' ? path.basename(source).replace(PLUGIN_FILE, '') : `plugin-${index + 1}`)
73
+ return { ...plugin, name, source }
74
+ }
75
+
76
+ // Resolves config.plugins and app/plugins/* into plugin objects, in that
77
+ // order. Throws with the plugin's name when one can't be loaded.
78
+ export async function loadPlugins(baseDir, config = {}) {
79
+ const loaded = []
80
+ const entries = config.plugins ?? []
81
+ if (!Array.isArray(entries)) throw new Error('tylix.config: plugins must be a list.')
82
+
83
+ for (const [index, entry] of entries.entries()) {
84
+ if (!entry) continue // allows plugins: [isProd && plugin()]
85
+ let plugin
86
+ let source = 'tylix.config'
87
+ if (typeof entry === 'string' || Array.isArray(entry)) {
88
+ const [specifier, options] = Array.isArray(entry) ? entry : [entry]
89
+ source = specifier
90
+ plugin = fromModule(await importSpecifier(baseDir, specifier), options, specifier)
91
+ } else if (typeof entry === 'function') {
92
+ plugin = entry({})
93
+ } else {
94
+ plugin = entry
95
+ }
96
+ loaded.push(normalize(await plugin, source, index))
97
+ }
98
+
99
+ const dir = path.join(baseDir, 'app', 'plugins')
100
+ const files = await fs.readdir(dir).catch(() => [])
101
+ for (const name of files.sort()) {
102
+ if (!PLUGIN_FILE.test(name) || SKIP_FILE.test(name)) continue
103
+ const rel = `app/plugins/${name}`
104
+ const plugin = fromModule(await import(pathToFileURL(path.join(dir, name)).href), {}, rel)
105
+ loaded.push(normalize(await plugin, rel, loaded.length))
106
+ }
107
+
108
+ const seen = new Set()
109
+ for (const plugin of loaded) {
110
+ if (seen.has(plugin.name)) throw new Error(`Two plugins are named "${plugin.name}". Give one a different name.`)
111
+ seen.add(plugin.name)
112
+ }
113
+ return loaded
114
+ }
115
+
116
+ function labelled(plugin, hook, err) {
117
+ err.message = `Plugin "${plugin.name}" ${hook}() failed: ${err.message}`
118
+ return err
119
+ }
120
+
121
+ // Runs plugin hooks in order. One per app.
122
+ export function createPluginHost(plugins = []) {
123
+ return {
124
+ plugins,
125
+
126
+ // Each config() may change the config in place or return keys to
127
+ // merge into it (top level, shallow).
128
+ async applyConfig(config) {
129
+ for (const plugin of plugins) {
130
+ if (!plugin.config) continue
131
+ try {
132
+ const next = await plugin.config(config)
133
+ if (next && typeof next === 'object' && next !== config) Object.assign(config, next)
134
+ } catch (err) {
135
+ throw labelled(plugin, 'config', err)
136
+ }
137
+ }
138
+ return config
139
+ },
140
+
141
+ async run(hook, ...args) {
142
+ for (const plugin of plugins) {
143
+ if (typeof plugin[hook] !== 'function') continue
144
+ try {
145
+ await plugin[hook](...args)
146
+ } catch (err) {
147
+ throw labelled(plugin, hook, err)
148
+ }
149
+ }
150
+ },
151
+
152
+ // Runs a hook with a context made for each plugin.
153
+ async runWith(hook, makeArgs) {
154
+ for (const plugin of plugins) {
155
+ if (typeof plugin[hook] !== 'function') continue
156
+ try {
157
+ await plugin[hook](...makeArgs(plugin))
158
+ } catch (err) {
159
+ throw labelled(plugin, hook, err)
160
+ }
161
+ }
162
+ },
163
+
164
+ // close() hooks run in reverse order and never throw.
165
+ async close() {
166
+ for (const plugin of [...plugins].reverse()) {
167
+ try {
168
+ await plugin.close?.()
169
+ } catch {
170
+ // shutting down: nothing to do about it
171
+ }
172
+ }
173
+ },
174
+
175
+ // Collects a keyed property (commands, logDrivers, deployAdapters)
176
+ // from every plugin. A later plugin can't silently replace an earlier
177
+ // one's key.
178
+ collect(property) {
179
+ const out = new Map()
180
+ for (const plugin of plugins) {
181
+ for (const [key, value] of Object.entries(plugin[property] ?? {})) {
182
+ if (out.has(key)) throw new Error(`Plugins "${out.get(key).plugin}" and "${plugin.name}" both define ${property} "${key}".`)
183
+ out.set(key, { plugin: plugin.name, value })
184
+ }
185
+ }
186
+ return out
187
+ },
188
+
189
+ describe() {
190
+ return plugins.map((plugin) => ({
191
+ name: plugin.name,
192
+ source: plugin.source,
193
+ hooks: PLUGIN_HOOKS.filter((hook) => typeof plugin[hook] === 'function'),
194
+ commands: Object.keys(plugin.commands ?? {}),
195
+ logDrivers: Object.keys(plugin.logDrivers ?? {}),
196
+ deployAdapters: Object.keys(plugin.deployAdapters ?? {}),
197
+ }))
198
+ },
199
+ }
200
+ }
@@ -2,6 +2,6 @@ import { Model } from '@tylix/orm'
2
2
 
3
3
  export class JobRecord extends Model {
4
4
  static table = 'jobs'
5
- static fillable = ['job', 'payload', 'status', 'attempts', 'error']
5
+ static fillable = ['job', 'payload', 'status', 'attempts', 'error', 'available_at']
6
6
  static timestamps = true
7
7
  }
@@ -1,4 +1,50 @@
1
+ export interface DispatchOptions {
2
+ /** Seconds before the job may run. Needs the available_at column (tylix make:queue-retries). */
3
+ delay?: number
4
+ }
1
5
  export declare function dispatch(
2
6
  jobName: string,
3
7
  payload?: Record<string, unknown>,
4
- ): Promise<unknown>
8
+ options?: DispatchOptions,
9
+ ): Promise<unknown>
10
+
11
+ export type Backoff = number | number[] | 'exponential' | ((attempt: number) => number)
12
+ export interface JobContext {
13
+ id: number | string
14
+ /** 1 on the first run. */
15
+ attempt: number
16
+ tries: number
17
+ }
18
+ export interface JobHandler<P = Record<string, unknown>> {
19
+ /** Attempts in total. Default: queue.tries in tylix.config (1). */
20
+ tries?: number
21
+ /** Seconds to wait before each retry. */
22
+ backoff?: Backoff
23
+ /** Cap for exponential backoff, seconds. Default 3600. */
24
+ maxBackoff?: number
25
+ /** Seconds an attempt may take before it counts as failed. 0: no limit. */
26
+ timeout?: number
27
+ handle(payload: P, job: JobContext): unknown | Promise<unknown>
28
+ /** Called once, after the last attempt failed. */
29
+ failed?(payload: P, error: Error, job: JobContext): unknown | Promise<unknown>
30
+ }
31
+ export interface JobOptions {
32
+ tries: number
33
+ backoff: Backoff
34
+ maxBackoff: number
35
+ timeout: number
36
+ }
37
+ export declare class PermanentJobError extends Error {
38
+ retryable: false
39
+ }
40
+ export declare class JobTimeoutError extends Error {}
41
+ export declare const QUEUE_DEFAULTS: JobOptions
42
+ export declare function jobOptions(handler?: Partial<JobHandler>, defaults?: Partial<JobOptions>): JobOptions
43
+ export declare function backoffSeconds(options: JobOptions, attempt: number, random?: () => number): number
44
+ export declare function afterFailure(
45
+ options: JobOptions,
46
+ attempt: number,
47
+ error: unknown,
48
+ now?: number,
49
+ ): { retry: false; attempt: number } | { retry: true; attempt: number; delaySeconds: number; availableAt: Date }
50
+ export declare function runWithTimeout<T>(work: () => Promise<T>, seconds: number): Promise<T>