Skip to content

Commit

Permalink
feat(core): support service without context
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Feb 8, 2024
1 parent f58cb36 commit e0d96b4
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 38 deletions.
23 changes: 14 additions & 9 deletions packages/cordis/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import * as core from '@cordisjs/core'
import * as logger from '@cordisjs/logger'
import { TimerService } from '@cordisjs/timer'
import Schema from 'schemastery'

export * from '@cordisjs/core'

export { Schema }

export { Logger } from '@cordisjs/logger'

export type EffectScope<C extends Context = Context> = core.EffectScope<C>
Expand All @@ -12,15 +15,6 @@ export type MainScope<C extends Context = Context> = core.MainScope<C>

export interface Events<C extends Context = Context> extends core.Events<C> {}

export class Service<C extends Context = Context> extends core.Service<C> {
public logger: logger.Logger

constructor(ctx: C, name: string, immediate?: boolean) {
super(ctx, name, immediate)
this.logger = ctx.logger(name)
}
}

export namespace Context {
export type Associate<P extends string, C extends Context = Context> = core.Context.Associate<P, C>
}
Expand All @@ -44,4 +38,15 @@ export class Context extends core.Context {
}
}

export class Service<C extends Context = Context> extends core.Service<C> {
static Context = Context

public logger: logger.Logger

constructor(ctx: C | undefined, name: string, immediate?: boolean) {
super(ctx, name, immediate)
this.logger = this.ctx.logger(name)
}
}

export default function () {}
2 changes: 0 additions & 2 deletions packages/core/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ export class Context {
static readonly filter = Symbol.for('cordis.filter')
static readonly expose = Symbol.for('cordis.expose')
static readonly shadow = Symbol.for('cordis.shadow')
/** @deprecated use `Context.current` instead */
static readonly source = Symbol.for('cordis.current')
static readonly current = Symbol.for('cordis.current')
static readonly internal = Symbol.for('cordis.internal')

Expand Down
16 changes: 8 additions & 8 deletions packages/core/src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export class Lifecycle {

constructor(private root: Context) {
defineProperty(this, Context.current, root)

defineProperty(this.on('internal/listener', function (this: Context, name, listener, prepend) {
const method = prepend ? 'unshift' : 'push'
if (name === 'ready') {
Expand All @@ -54,14 +55,13 @@ export class Lifecycle {
return this.scope.collect('event <fork>', () => remove(this.scope.runtime.forkables, listener))
}
}), Context.static, root.scope)
defineProperty(this.on('internal/error', (error) => {
if (this._hooks['internal/error'].length > 1) return
console.error(error)
}), Context.static, root.scope)
defineProperty(this.on('internal/warning', (error) => {
if (this._hooks['internal/warning'].length > 1) return
console.warn(error)
}), Context.static, root.scope)

for (const level of ['info', 'error', 'warning']) {
defineProperty(this.on(`internal/${level}`, (format, ...param) => {
if (this._hooks['internal/info'].length > 1) return
console.info(format, ...param)
}), Context.static, root.scope)
}
}

async flush() {
Expand Down
17 changes: 11 additions & 6 deletions packages/core/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,33 @@ import { Awaitable, defineProperty } from 'cosmokit'
import { Context } from './context.ts'

export class Service<C extends Context = Context> {
static Context = Context

protected start(): Awaitable<void> {}
protected stop(): Awaitable<void> {}
protected fork?(ctx: C, config: any): void

protected ctx!: C
protected [Context.current]!: C

constructor(protected ctx: C, public name: string, immediate?: boolean) {
ctx.provide(name)
constructor(ctx: C | undefined, public name: string, immediate?: boolean) {
this.ctx = ctx ?? new (this.constructor as any).Context()
this.ctx.provide(name)
defineProperty(this, Context.current, ctx)

if (immediate) {
this[Context.expose] = name
if (ctx) this[Context.expose] = name
else this.ctx[name] = this
}

ctx.on('ready', async () => {
this.ctx.on('ready', async () => {
// await until next tick because derived class has not been initialized yet
await Promise.resolve()
await this.start()
if (!immediate) ctx[name] = this
if (!immediate) this.ctx[name] = this
})

ctx.on('dispose', () => this.stop())
this.ctx.on('dispose', () => this.stop())
return Context.associate(this, name)
}

Expand Down
3 changes: 1 addition & 2 deletions packages/hmr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
},
"dependencies": {
"@babel/code-frame": "^7.23.5",
"chokidar": "^3.5.3",
"schemastery": "^3.14.3"
"chokidar": "^3.5.3"
}
}
17 changes: 6 additions & 11 deletions packages/hmr/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Context, ForkScope, Logger, MainScope, Plugin } from 'cordis'
import { Context, ForkScope, MainScope, Plugin, Schema, Service } from 'cordis'
import { Dict, makeArray } from 'cosmokit'
import { ModuleJob } from 'cordis/worker'
import Schema from 'schemastery'
import { FSWatcher, watch, WatchOptions } from 'chokidar'
import { relative, resolve } from 'path'
import { handleError } from './error.js'
Expand All @@ -10,7 +9,7 @@ import { fileURLToPath, pathToFileURL } from 'url'

declare module 'cordis' {
interface Context {
watcher: Watcher
hmr: Watcher
}

interface Events {
Expand All @@ -35,8 +34,8 @@ interface Reload {
children: ForkScope[]
}

class Watcher {
static inject = ['loader', 'timer']
class Watcher extends Service {
static inject = ['loader']

private base: string
private watcher!: FSWatcher
Expand Down Expand Up @@ -67,17 +66,13 @@ class Watcher {
/** stashed changes */
private stashed = new Set<string>()

private logger: Logger

private initialURL!: string

constructor(private ctx: Context, private config: Watcher.Config) {
constructor(ctx: Context, private config: Watcher.Config) {
super(ctx, 'hmr')
this.base = resolve(ctx.baseDir, config.base || '')
this.logger = ctx.logger('hmr')
this.initialURL = pathToFileURL(ctx.loader.filename).href
ctx.provide('watcher', this)
ctx.on('ready', () => this.start())
ctx.on('dispose', () => this.stop())
}

relative(filename: string) {
Expand Down

0 comments on commit e0d96b4

Please sign in to comment.