@c9up/ream 0.2.7 → 0.2.9

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.
Files changed (84) hide show
  1. package/dist/HttpKernel.d.ts.map +1 -1
  2. package/dist/HttpKernel.js +10 -0
  3. package/dist/HttpKernel.js.map +1 -1
  4. package/dist/Ignitor.d.ts.map +1 -1
  5. package/dist/Ignitor.js +51 -3
  6. package/dist/Ignitor.js.map +1 -1
  7. package/dist/commands/Migrate.d.ts +9 -0
  8. package/dist/commands/Migrate.d.ts.map +1 -0
  9. package/dist/commands/Migrate.js +16 -0
  10. package/dist/commands/Migrate.js.map +1 -0
  11. package/dist/commands/MigrateBase.d.ts +27 -0
  12. package/dist/commands/MigrateBase.d.ts.map +1 -0
  13. package/dist/commands/MigrateBase.js +77 -0
  14. package/dist/commands/MigrateBase.js.map +1 -0
  15. package/dist/commands/MigrateRollback.d.ts +9 -0
  16. package/dist/commands/MigrateRollback.d.ts.map +1 -0
  17. package/dist/commands/MigrateRollback.js +16 -0
  18. package/dist/commands/MigrateRollback.js.map +1 -0
  19. package/dist/commands/MigrateStatus.d.ts +9 -0
  20. package/dist/commands/MigrateStatus.d.ts.map +1 -0
  21. package/dist/commands/MigrateStatus.js +19 -0
  22. package/dist/commands/MigrateStatus.js.map +1 -0
  23. package/dist/commands/ScheduleList.d.ts +18 -0
  24. package/dist/commands/ScheduleList.d.ts.map +1 -0
  25. package/dist/commands/ScheduleList.js +55 -0
  26. package/dist/commands/ScheduleList.js.map +1 -0
  27. package/dist/commands/ScheduleRun.d.ts +19 -0
  28. package/dist/commands/ScheduleRun.d.ts.map +1 -0
  29. package/dist/commands/ScheduleRun.js +61 -0
  30. package/dist/commands/ScheduleRun.js.map +1 -0
  31. package/dist/commands/index.d.ts +15 -0
  32. package/dist/commands/index.d.ts.map +1 -0
  33. package/dist/commands/index.js +63 -0
  34. package/dist/commands/index.js.map +1 -0
  35. package/dist/commands/scheduler_resolver.d.ts +12 -0
  36. package/dist/commands/scheduler_resolver.d.ts.map +1 -0
  37. package/dist/commands/scheduler_resolver.js +19 -0
  38. package/dist/commands/scheduler_resolver.js.map +1 -0
  39. package/dist/debug.d.ts +22 -0
  40. package/dist/debug.d.ts.map +1 -0
  41. package/dist/debug.js +23 -0
  42. package/dist/debug.js.map +1 -0
  43. package/dist/dumper/Dumper.d.ts +80 -0
  44. package/dist/dumper/Dumper.d.ts.map +1 -0
  45. package/dist/dumper/Dumper.js +129 -0
  46. package/dist/dumper/Dumper.js.map +1 -0
  47. package/dist/index.d.ts +1 -1
  48. package/dist/index.js +1 -1
  49. package/dist/middleware/Pipeline.d.ts.map +1 -1
  50. package/dist/middleware/Pipeline.js +7 -0
  51. package/dist/middleware/Pipeline.js.map +1 -1
  52. package/dist/repl/Repl.d.ts +88 -0
  53. package/dist/repl/Repl.d.ts.map +1 -0
  54. package/dist/repl/Repl.js +123 -0
  55. package/dist/repl/Repl.js.map +1 -0
  56. package/dist/services/dumper.d.ts +25 -0
  57. package/dist/services/dumper.d.ts.map +1 -0
  58. package/dist/services/dumper.js +27 -0
  59. package/dist/services/dumper.js.map +1 -0
  60. package/dist/services/repl.d.ts +19 -0
  61. package/dist/services/repl.d.ts.map +1 -0
  62. package/dist/services/repl.js +19 -0
  63. package/dist/services/repl.js.map +1 -0
  64. package/events.win32-x64-msvc.node +0 -0
  65. package/index.win32-x64-msvc.node +0 -0
  66. package/package.json +21 -1
  67. package/scheduler.win32-x64-msvc.node +0 -0
  68. package/src/HttpKernel.ts +27 -0
  69. package/src/Ignitor.ts +51 -3
  70. package/src/commands/Migrate.ts +18 -0
  71. package/src/commands/MigrateBase.ts +81 -0
  72. package/src/commands/MigrateRollback.ts +18 -0
  73. package/src/commands/MigrateStatus.ts +22 -0
  74. package/src/commands/ScheduleList.ts +66 -0
  75. package/src/commands/ScheduleRun.ts +65 -0
  76. package/src/commands/index.ts +73 -0
  77. package/src/commands/scheduler_resolver.ts +23 -0
  78. package/src/debug.ts +25 -0
  79. package/src/dumper/Dumper.ts +164 -0
  80. package/src/index.ts +1 -1
  81. package/src/middleware/Pipeline.ts +7 -0
  82. package/src/repl/Repl.ts +162 -0
  83. package/src/services/dumper.ts +30 -0
  84. package/src/services/repl.ts +21 -0
@@ -0,0 +1,18 @@
1
+ /** `migrate:rollback` — undo the last batch, in every registered store. */
2
+
3
+ import type { RegisteredMigrationSource } from '../migrations/types.js'
4
+ import { MigrateBase } from './MigrateBase.js'
5
+
6
+ export default class MigrateRollback extends MigrateBase {
7
+ static override commandName = 'migrate:rollback'
8
+ static override description = 'Roll back the last batch for every registered migration source'
9
+
10
+ protected async migrateSource(source: RegisteredMigrationSource): Promise<void> {
11
+ const rolled = await source.runner.rollback()
12
+ if (rolled.length === 0) {
13
+ this.report(source, 'nothing to rollback.')
14
+ return
15
+ }
16
+ for (const name of rolled) this.report(source, `rolled back: ${name}`)
17
+ }
18
+ }
@@ -0,0 +1,22 @@
1
+ /** `migrate:status` — what has run and what has not, in every registered store. */
2
+
3
+ import type { RegisteredMigrationSource } from '../migrations/types.js'
4
+ import { MigrateBase } from './MigrateBase.js'
5
+
6
+ export default class MigrateStatus extends MigrateBase {
7
+ static override commandName = 'migrate:status'
8
+ static override description = 'Show applied and pending migrations for every source'
9
+
10
+ protected async migrateSource(source: RegisteredMigrationSource): Promise<void> {
11
+ const statuses = await source.runner.status()
12
+ if (statuses.length === 0) {
13
+ this.report(source, 'no migrations found.')
14
+ return
15
+ }
16
+ for (const node of statuses) {
17
+ const mark = node.status === 'applied' ? '✓' : '○'
18
+ const batch = node.batch === undefined ? '' : ` (batch ${node.batch})`
19
+ this.report(source, `${mark} ${node.name}${batch}`)
20
+ }
21
+ }
22
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * `schedule:list` — every registered task, when it next fires, and how its past
3
+ * runs went.
4
+ *
5
+ * The columns are the operator's questions in order: is my task registered at
6
+ * all, on what schedule, when does it fire next, when did it last fire, and is
7
+ * it failing. Stats come from the scheduler's own tracker, so a task that has
8
+ * never run reads as `—` rather than a zero that looks like a result.
9
+ */
10
+
11
+ import { BaseCommand } from '../console/BaseCommand.js'
12
+ import type { CommandOptions } from '../console/types.js'
13
+ import { resolveScheduler } from './scheduler_resolver.js'
14
+
15
+ /** Over-long names and cron expressions are truncated so the table stays a table. */
16
+ function truncate(value: string, width: number): string {
17
+ return value.length > width ? `${value.slice(0, width - 1)}…` : value
18
+ }
19
+
20
+ function asDate(ms: number | null): string {
21
+ return ms === null ? '—' : new Date(ms).toISOString()
22
+ }
23
+
24
+ export default class ScheduleList extends BaseCommand {
25
+ static override commandName = 'schedule:list'
26
+ static override description = 'List every registered scheduled task, its next run and its stats'
27
+ static override options: CommandOptions = { startApp: true }
28
+
29
+ async run(): Promise<void> {
30
+ const scheduler = await resolveScheduler(this)
31
+ if (!scheduler) return
32
+
33
+ const tasks = scheduler.listTasks()
34
+ if (tasks.length === 0) {
35
+ this.logger.info('No scheduled tasks registered.')
36
+ return
37
+ }
38
+
39
+ this.logger.log(
40
+ [
41
+ 'NAME'.padEnd(32),
42
+ 'CRON'.padEnd(18),
43
+ 'NEXT RUN'.padEnd(22),
44
+ 'LAST RUN'.padEnd(22),
45
+ 'RUNS'.padStart(6),
46
+ 'ERR'.padStart(5),
47
+ 'AVG(ms)'.padStart(9),
48
+ ].join(' '),
49
+ )
50
+
51
+ for (const task of tasks) {
52
+ const stats = scheduler.getStats(task.name)
53
+ this.logger.log(
54
+ [
55
+ truncate(task.name, 32).padEnd(32),
56
+ truncate(task.cronExpr, 18).padEnd(18),
57
+ asDate(task.nextRun).padEnd(22),
58
+ asDate(stats.lastRunMs).padEnd(22),
59
+ String(stats.runCount).padStart(6),
60
+ String(stats.errorCount).padStart(5),
61
+ String(Math.round(stats.avgDurationMs)).padStart(9),
62
+ ].join(' '),
63
+ )
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * `schedule:run <name>` — run one registered task immediately.
3
+ *
4
+ * An admin override: it calls the task body directly, so it bypasses both the
5
+ * cron schedule and the distributed lock. That is the point — you reach for it
6
+ * when a task must run now, or to see it fail with your own eyes — and it is
7
+ * also why the exit codes are distinct: `1` the task failed, `2` no such task,
8
+ * `3` an invocation of it is already in flight.
9
+ */
10
+
11
+ import { BaseCommand } from '../console/BaseCommand.js'
12
+ import { args } from '../console/decorators.js'
13
+ import type { CommandOptions } from '../console/types.js'
14
+ import { resolveScheduler } from './scheduler_resolver.js'
15
+
16
+ export default class ScheduleRun extends BaseCommand {
17
+ static override commandName = 'schedule:run'
18
+ static override description = 'Run a registered scheduled task once, now (bypasses the lock)'
19
+ static override options: CommandOptions = { startApp: true }
20
+
21
+ @args.string({ description: 'Task name, as `schedule:list` prints it' })
22
+ declare name: string
23
+
24
+ async run(): Promise<void> {
25
+ // Rejected here rather than in the scheduler so the message arrives without
26
+ // the operator first paying for a boot.
27
+ if (this.name.trim() === '') {
28
+ this.logger.error('Task name cannot be empty. Usage: schedule:run <name>')
29
+ this.exitCode = 1
30
+ return
31
+ }
32
+
33
+ const scheduler = await resolveScheduler(this)
34
+ if (!scheduler) return
35
+
36
+ const result = await scheduler.runTaskNow(this.name)
37
+ const duration = Math.round(result.durationMs)
38
+
39
+ if (result.outcome === 'unknown') {
40
+ this.logger.error(
41
+ `Unknown task: ${this.name}. Run "schedule:list" to see the registered tasks.`,
42
+ )
43
+ this.exitCode = 2
44
+ return
45
+ }
46
+
47
+ if (result.outcome === 'already-running') {
48
+ this.logger.error(
49
+ `Task ${this.name} is already running in this process — skipped. Try again once it completes.`,
50
+ )
51
+ this.exitCode = 3
52
+ return
53
+ }
54
+
55
+ if (result.outcome === 'completed') {
56
+ this.logger.success(`${this.name} completed in ${duration} ms`)
57
+ return
58
+ }
59
+
60
+ this.logger.error(
61
+ `${this.name} failed after ${duration} ms: ${result.error?.message || 'unknown error'}`,
62
+ )
63
+ this.exitCode = 1
64
+ }
65
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * `@c9up/ream/commands` — the commands the framework itself ships.
3
+ *
4
+ * The shape AdonisJS uses for `@adonisjs/core/commands`: a module answering
5
+ * `getMetaData()` then `getCommand()`, so listing a command does not import it.
6
+ *
7
+ * The kernel registers this loader on its own rather than waiting for an entry
8
+ * in `reamrc.commands` — the deviation from AdonisJS, where the starter kit
9
+ * lists it. These commands were part of the `ream` binary before they were
10
+ * classes, and an application that upgrades must not silently lose them.
11
+ */
12
+
13
+ import type { CommandClass, SerializedCommand } from '../console/types.js'
14
+
15
+ interface Entry {
16
+ commandName: string
17
+ description: string
18
+ load: () => Promise<{ default: CommandClass }>
19
+ }
20
+
21
+ const COMMANDS: readonly Entry[] = [
22
+ // The registry commands first: a data package registers its runner, and
23
+ // these drive whatever registered — they name no store.
24
+ {
25
+ commandName: 'migrate',
26
+ description: 'Run pending migrations for every registered migration source',
27
+ load: () => import('./Migrate.js'),
28
+ },
29
+ {
30
+ commandName: 'migrate:rollback',
31
+ description: 'Roll back the last batch for every registered migration source',
32
+ load: () => import('./MigrateRollback.js'),
33
+ },
34
+ {
35
+ commandName: 'migrate:status',
36
+ description: 'Show applied and pending migrations for every source',
37
+ load: () => import('./MigrateStatus.js'),
38
+ },
39
+ {
40
+ commandName: 'schedule:list',
41
+ description: 'List every registered scheduled task, its next run and its stats',
42
+ load: () => import('./ScheduleList.js'),
43
+ },
44
+ {
45
+ commandName: 'schedule:run',
46
+ description: 'Run a registered scheduled task once, now (bypasses the lock)',
47
+ load: () => import('./ScheduleRun.js'),
48
+ },
49
+ ]
50
+
51
+ /** `migrate:status` → `migrate`; a name without a colon has no namespace. */
52
+ function namespaceOf(commandName: string): string | null {
53
+ const colon = commandName.indexOf(':')
54
+ return colon === -1 ? null : commandName.slice(0, colon)
55
+ }
56
+
57
+ export async function getMetaData(): Promise<SerializedCommand[]> {
58
+ return COMMANDS.map((entry) => ({
59
+ commandName: entry.commandName,
60
+ namespace: namespaceOf(entry.commandName),
61
+ description: entry.description,
62
+ aliases: [],
63
+ options: { startApp: true },
64
+ args: [],
65
+ flags: [],
66
+ }))
67
+ }
68
+
69
+ export async function getCommand(metadata: SerializedCommand): Promise<CommandClass | null> {
70
+ const entry = COMMANDS.find((command) => command.commandName === metadata.commandName)
71
+ if (!entry) return null
72
+ return (await entry.load()).default
73
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Resolve the scheduler for the `schedule:*` commands.
3
+ *
4
+ * Shared because the failure is the same one on both, and it is a
5
+ * configuration mistake rather than a crash: the provider is simply not in the
6
+ * list, and the message has to say so — a container error mentioning an
7
+ * unbound `scheduler` binding tells an operator nothing.
8
+ */
9
+
10
+ import type { BaseCommand } from '../console/BaseCommand.js'
11
+ import type { Scheduler } from '../scheduler/Scheduler.js'
12
+
13
+ export async function resolveScheduler(command: BaseCommand): Promise<Scheduler | undefined> {
14
+ try {
15
+ return await command.app.container.resolve<Scheduler>('scheduler')
16
+ } catch {
17
+ command.logger.error(
18
+ 'No ScheduleProvider is registered. Add ScheduleProvider to the providers list in reamrc.ts.',
19
+ )
20
+ command.exitCode = 2
21
+ return undefined
22
+ }
23
+ }
package/src/debug.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Debug channels, off unless `NODE_DEBUG` names them — the shape AdonisJS
3
+ * uses (`NODE_DEBUG=adonisjs:http`).
4
+ *
5
+ * NODE_DEBUG=ream:http ream serve
6
+ * NODE_DEBUG=ream:* ream serve
7
+ *
8
+ * These are for the framework's own tracing: which route a request matched,
9
+ * which middleware ran, what status came back. They are NOT request logging —
10
+ * a production request log belongs to the app's logger (`ctx.logger`), which
11
+ * is correlation-scoped and structured. Neither framework prints one by
12
+ * default, and this is the switch for when you need to see the plumbing.
13
+ *
14
+ * `debuglog` returns a no-op when the channel is off, so an inactive probe
15
+ * costs a call. Guard with `.enabled` anywhere the ARGUMENTS would cost
16
+ * something to build — the per-request probes below all do.
17
+ */
18
+
19
+ import { debuglog } from 'node:util'
20
+
21
+ /** Routing, middleware and response tracing. AdonisJS `adonisjs:http`. */
22
+ export const debugHttp = debuglog('ream:http')
23
+
24
+ /** Boot: providers, preloads, container bindings. AdonisJS `adonisjs:core`. */
25
+ export const debugCore = debuglog('ream:core')
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Value dumping — AdonisJS's `Dumper`, in shape and in method names.
3
+ *
4
+ * import { dd } from '@c9up/ream/services/dumper'
5
+ * dd(user) // prints and stops the process
6
+ *
7
+ * import dumper from '@c9up/ream/services/dumper'
8
+ * response.send(dumper.dumpToHtml(user, { cspNonce: response.nonce }))
9
+ *
10
+ * The rendering is `node:util`'s `inspect`, not a dependency. It already knows
11
+ * about depth limits, circular references, getters, Maps, Sets and typed
12
+ * arrays, and it colours for a terminal — which is the whole of the ANSI side.
13
+ * The HTML side escapes that same output rather than building a second
14
+ * formatter, so the two can never describe a value differently.
15
+ */
16
+
17
+ import { inspect } from 'node:util'
18
+ import { escapeHTML } from '../helpers/string.js'
19
+
20
+ /** Where a dump was written, so the output can say so. */
21
+ export interface DumpSource {
22
+ location: string
23
+ line: number
24
+ }
25
+
26
+ /** Knobs for the terminal rendering — AdonisJS `ConsoleDumpConfig`. */
27
+ export interface ConsoleDumpConfig {
28
+ /** How deep to walk before printing `[Object]`. Default 4. */
29
+ depth?: number
30
+ /** Colour the output. Default: whether stdout is a TTY. */
31
+ colors?: boolean
32
+ /** Show non-enumerable properties. Default false. */
33
+ showHidden?: boolean
34
+ }
35
+
36
+ /** Knobs for the HTML rendering — AdonisJS `HTMLDumpConfig`. */
37
+ export interface HTMLDumpConfig {
38
+ /** How deep to walk. Default 4. */
39
+ depth?: number
40
+ /** Show non-enumerable properties. Default false. */
41
+ showHidden?: boolean
42
+ /** Style overrides for the emitted `<pre>`, as CSS declarations. */
43
+ styles?: Record<string, string>
44
+ }
45
+
46
+ const DEFAULT_STYLES: Record<string, string> = {
47
+ 'background-color': '#0b0b0d',
48
+ color: '#e6e6e6',
49
+ padding: '1rem',
50
+ 'border-radius': '6px',
51
+ 'font-family': 'ui-monospace, SFMono-Regular, Menlo, monospace',
52
+ 'font-size': '13px',
53
+ 'line-height': '1.5',
54
+ 'overflow-x': 'auto',
55
+ }
56
+
57
+ export class Dumper {
58
+ #html: HTMLDumpConfig = {}
59
+ #ansi: ConsoleDumpConfig = {}
60
+
61
+ /** Configure the HTML rendering. Chainable, as in AdonisJS. */
62
+ configureHtmlOutput(config: HTMLDumpConfig): this {
63
+ this.#html = { ...this.#html, ...config }
64
+ return this
65
+ }
66
+
67
+ /** Configure the terminal rendering. Chainable, as in AdonisJS. */
68
+ configureAnsiOutput(config: ConsoleDumpConfig): this {
69
+ this.#ansi = { ...this.#ansi, ...config }
70
+ return this
71
+ }
72
+
73
+ /**
74
+ * The `<style>` a page needs before its first HTML dump.
75
+ *
76
+ * Takes a CSP nonce because a page that sets a nonce-based policy rejects an
77
+ * unattributed inline `<style>` — and a dump landing in a page that silently
78
+ * drops its styling is worse than no dump. `response.nonce` is what to pass.
79
+ */
80
+ getHeadElements(cspNonce?: string): string {
81
+ const nonce = cspNonce ? ` nonce="${escapeHTML(cspNonce)}"` : ''
82
+ const styles = { ...DEFAULT_STYLES, ...this.#html.styles }
83
+ const declarations = Object.entries(styles)
84
+ .map(([property, value]) => ` ${property}: ${value};`)
85
+ .join('\n')
86
+ return `<style${nonce}>\n.ream-dump {\n${declarations}\n}\n</style>`
87
+ }
88
+
89
+ /** Render `value` for a terminal. */
90
+ dumpToAnsi(value: unknown, options?: { title?: string; source?: DumpSource }): string {
91
+ const body = inspect(value, {
92
+ depth: this.#ansi.depth ?? 4,
93
+ colors: this.#ansi.colors ?? process.stdout.isTTY === true,
94
+ showHidden: this.#ansi.showHidden ?? false,
95
+ // Long strings and arrays are the reason someone is dumping; truncating
96
+ // them defeats the call.
97
+ maxStringLength: null,
98
+ maxArrayLength: null,
99
+ })
100
+ return [header(options), body].filter(Boolean).join('\n')
101
+ }
102
+
103
+ /**
104
+ * Render `value` as HTML.
105
+ *
106
+ * The inspected output is escaped before it reaches the page: a dumped value
107
+ * is by definition data someone else may control, and a dump is something
108
+ * you reach for while debugging — exactly when a script tag in a field name
109
+ * would be least expected.
110
+ */
111
+ dumpToHtml(
112
+ value: unknown,
113
+ options?: { cspNonce?: string; title?: string; source?: DumpSource },
114
+ ): string {
115
+ const body = inspect(value, {
116
+ depth: this.#html.depth ?? 4,
117
+ colors: false,
118
+ showHidden: this.#html.showHidden ?? false,
119
+ maxStringLength: null,
120
+ maxArrayLength: null,
121
+ })
122
+ const heading = header(options)
123
+ const label = heading ? `<div class="ream-dump-header">${escapeHTML(heading)}</div>` : ''
124
+ return `${this.getHeadElements(options?.cspNonce)}\n${label}<pre class="ream-dump">${escapeHTML(body)}</pre>`
125
+ }
126
+
127
+ /**
128
+ * Dump and die — print to stderr and stop the process.
129
+ *
130
+ * `traceSourceIndex` selects which stack frame to report as the dump site:
131
+ * 1 is the caller of `dd`, which is right when `dd` is called directly, and
132
+ * a wrapper passes 2.
133
+ */
134
+ dd(value: unknown, traceSourceIndex = 1): void {
135
+ process.stderr.write(`${this.dumpToAnsi(value, { source: callSite(traceSourceIndex) })}\n`)
136
+ process.exit(1)
137
+ }
138
+ }
139
+
140
+ /** `title` and `source` as one line, or nothing when neither is given. */
141
+ function header(options?: { title?: string; source?: DumpSource }): string {
142
+ const parts: string[] = []
143
+ if (options?.title) parts.push(options.title)
144
+ if (options?.source) parts.push(`${options.source.location}:${options.source.line}`)
145
+ return parts.join(' — ')
146
+ }
147
+
148
+ /**
149
+ * Where `dd` was called, read from a thrown stack.
150
+ *
151
+ * Best-effort: a bundled or minified frame may not parse, and a dump that
152
+ * cannot name its own line is still a useful dump — so a miss returns nothing
153
+ * rather than throwing on the debugging path.
154
+ */
155
+ function callSite(index: number): DumpSource | undefined {
156
+ const frames = new Error().stack?.split('\n').slice(1)
157
+ const frame = frames?.[index]
158
+ if (!frame) return undefined
159
+ const match = /\(?(.+):(\d+):\d+\)?$/.exec(frame.trim())
160
+ const location = match?.[1]
161
+ const line = match?.[2]
162
+ if (!location || !line) return undefined
163
+ return { location, line: Number(line) }
164
+ }
package/src/index.ts CHANGED
@@ -371,4 +371,4 @@ export {
371
371
  StatsTracker,
372
372
  } from './scheduler/index.js'
373
373
 
374
- export const VERSION = '0.2.7'
374
+ export const VERSION = '0.2.9'
@@ -11,6 +11,7 @@
11
11
  * 5. Handler
12
12
  */
13
13
 
14
+ import { debugHttp } from '../debug.js'
14
15
  import { ReamError } from '../errors/ReamError.js'
15
16
  import { E_FORBIDDEN, E_UNAUTHORIZED, E_VALIDATION_ERROR } from '../http/Exception.js'
16
17
  import type { HttpContext } from '../http/HttpContext.js'
@@ -196,6 +197,12 @@ function composeMiddleware(middleware: MiddlewareFunction[]): MiddlewareFunction
196
197
  const fn = i < middleware.length ? middleware[i] : finalNext
197
198
  if (!fn) return
198
199
 
200
+ if (debugHttp.enabled && i < middleware.length) {
201
+ // `fn.name` is what a named middleware function or a bound class
202
+ // method carries; an inline arrow has none, and its position is the
203
+ // only thing that identifies it.
204
+ debugHttp('middleware %d/%d %s', i + 1, middleware.length, fn.name || '(anonymous)')
205
+ }
199
206
  await fn(ctx, () => dispatch(i + 1))
200
207
  }
201
208
 
@@ -0,0 +1,162 @@
1
+ /**
2
+ * The application REPL — AdonisJS's `Repl`, in shape and in method names.
3
+ *
4
+ * import repl from '@c9up/ream/services/repl'
5
+ * repl.addMethod('loadModels', async () => { … }, {
6
+ * description: 'Load every entity onto the prompt',
7
+ * })
8
+ * repl.start({ app, router })
9
+ *
10
+ * Built on `node:repl`, which is the REPL — this adds what makes it an
11
+ * APPLICATION repl: a context seeded with the booted services, helpers a
12
+ * project registers itself, and `.ls` to list them, because a prompt full of
13
+ * undiscoverable helpers is a prompt nobody uses.
14
+ */
15
+
16
+ import type { REPLServer } from 'node:repl'
17
+ import { start as startNodeRepl } from 'node:repl'
18
+
19
+ /** What a registered helper receives — the repl itself, then its arguments. */
20
+ export type MethodCallback = (repl: Repl, ...args: unknown[]) => unknown
21
+
22
+ /** How a helper describes itself in `.ls`. */
23
+ export interface MethodOptions {
24
+ description?: string
25
+ usage?: string
26
+ }
27
+
28
+ /**
29
+ * A TypeScript compiler for the prompt, when the host has one.
30
+ *
31
+ * `node:repl` evaluates JavaScript. A project whose code is TypeScript wants
32
+ * to paste TypeScript, so the host supplies the compiler it already runs
33
+ * rather than ream carrying one.
34
+ */
35
+ export interface Compiler {
36
+ compile(code: string, fileName: string): string
37
+ supportsTypescript: boolean
38
+ }
39
+
40
+ interface RegisteredMethod {
41
+ handler: MethodCallback
42
+ options: MethodOptions & { width: number }
43
+ }
44
+
45
+ export class Repl {
46
+ readonly #methods = new Map<string, RegisteredMethod>()
47
+ readonly #readyCallbacks: Array<(repl: Repl) => void> = []
48
+ #compiler: Compiler | undefined
49
+ #server: REPLServer | undefined
50
+ readonly #prompt: string
51
+ readonly #write: (message: string) => void
52
+
53
+ constructor(options: { prompt?: string; write?: (message: string) => void } = {}) {
54
+ this.#prompt = options.prompt ?? '> '
55
+ this.#write =
56
+ options.write ??
57
+ ((message) => {
58
+ process.stdout.write(message)
59
+ })
60
+ }
61
+
62
+ /**
63
+ * Print a message around the prompt.
64
+ *
65
+ * Newline-wrapped: written mid-session the text would otherwise land on the
66
+ * line the user is typing.
67
+ */
68
+ notify(message: string): void {
69
+ this.#write(`\n${message}\n`)
70
+ }
71
+
72
+ /** Run `callback` once the prompt is up. Chainable. */
73
+ ready(callback: (repl: Repl) => void): this {
74
+ this.#readyCallbacks.push(callback)
75
+ return this
76
+ }
77
+
78
+ /**
79
+ * Register a helper, available at the prompt by name. Chainable.
80
+ *
81
+ * `width` is the name's display width, recorded here so `.ls` can align a
82
+ * column without measuring the set twice.
83
+ */
84
+ addMethod(name: string, handler: MethodCallback, options: MethodOptions = {}): this {
85
+ this.#methods.set(name, { handler, options: { ...options, width: name.length } })
86
+ return this
87
+ }
88
+
89
+ /** Every registered helper, keyed by name — AdonisJS `getMethods`. */
90
+ getMethods(): Record<string, RegisteredMethod> {
91
+ return Object.fromEntries(this.#methods)
92
+ }
93
+
94
+ /** Use `compiler` for the code typed at the prompt. Chainable. */
95
+ useCompiler(compiler: Compiler): this {
96
+ this.#compiler = compiler
97
+ return this
98
+ }
99
+
100
+ /** The compiler in use, if any. */
101
+ get compiler(): Compiler | undefined {
102
+ return this.#compiler
103
+ }
104
+
105
+ /** The underlying `node:repl` server, once started. */
106
+ get server(): REPLServer | undefined {
107
+ return this.#server
108
+ }
109
+
110
+ /**
111
+ * List the registered helpers, one per line, names aligned.
112
+ *
113
+ * Exposed rather than private because it IS the `.ls` command, and a caller
114
+ * driving the repl programmatically (a test, a custom command) needs the
115
+ * same listing without a live prompt.
116
+ */
117
+ describeMethods(): string {
118
+ if (this.#methods.size === 0) return 'No methods registered'
119
+ const widest = Math.max(...[...this.#methods.values()].map((m) => m.options.width))
120
+ return [...this.#methods]
121
+ .map(([name, method]) => {
122
+ const description = method.options.description ?? ''
123
+ const usage = method.options.usage ? ` (${method.options.usage})` : ''
124
+ return `${name.padEnd(widest)} ${description}${usage}`.trimEnd()
125
+ })
126
+ .join('\n')
127
+ }
128
+
129
+ /**
130
+ * Start the prompt, seeding it with `context`.
131
+ *
132
+ * Registered helpers are bound to this repl before the prompt appears — a
133
+ * helper that only exists after the first keystroke is a helper the user
134
+ * finds missing.
135
+ */
136
+ start(context: Record<string, unknown> = {}): this {
137
+ const server = startNodeRepl({ prompt: this.#prompt, useGlobal: false })
138
+ this.#server = server
139
+
140
+ for (const [key, value] of Object.entries(context)) {
141
+ Object.defineProperty(server.context, key, { value, configurable: true, enumerable: true })
142
+ }
143
+ for (const [name, method] of this.#methods) {
144
+ Object.defineProperty(server.context, name, {
145
+ value: (...args: unknown[]) => method.handler(this, ...args),
146
+ configurable: true,
147
+ enumerable: true,
148
+ })
149
+ }
150
+
151
+ server.defineCommand('ls', {
152
+ help: 'List the helpers available at this prompt',
153
+ action: () => {
154
+ this.notify(this.describeMethods())
155
+ server.displayPrompt()
156
+ },
157
+ })
158
+
159
+ for (const callback of this.#readyCallbacks) callback(this)
160
+ return this
161
+ }
162
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Dumper singleton service.
3
+ *
4
+ * import { dd } from '@c9up/ream/services/dumper'
5
+ * dd(user)
6
+ *
7
+ * import dumper from '@c9up/ream/services/dumper'
8
+ * dumper.configureAnsiOutput({ depth: 8 })
9
+ *
10
+ * Unlike the other accessors this one holds a real instance rather than a
11
+ * proxy: the dumper depends on nothing the boot phase builds, and something
12
+ * you reach for mid-debug should not require a booted application.
13
+ */
14
+
15
+ import { Dumper } from '../dumper/Dumper.js'
16
+
17
+ const dumper = new Dumper()
18
+
19
+ /**
20
+ * Dump and die — AdonisJS's `dd`.
21
+ *
22
+ * The trace index is 2, not the default 1: the frame above is this function,
23
+ * so the caller of `dd` is one further out. Without it, every dump would
24
+ * report this file as its source.
25
+ */
26
+ export const dd = (value: unknown): void => {
27
+ dumper.dd(value, 2)
28
+ }
29
+
30
+ export default dumper