stonyx 0.2.3-alpha.7 → 0.2.3-alpha.71

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 (69) hide show
  1. package/README.md +30 -7
  2. package/config/{environment.js → environment copy.ts } +16 -12
  3. package/dist/cli/help.d.ts +8 -0
  4. package/dist/cli/help.js +43 -0
  5. package/dist/cli/load-commands.d.ts +10 -0
  6. package/dist/cli/load-commands.js +49 -0
  7. package/dist/cli/new.d.ts +72 -0
  8. package/dist/cli/new.js +422 -0
  9. package/dist/cli/serve.d.ts +6 -0
  10. package/dist/cli/serve.js +49 -0
  11. package/dist/cli/test-setup.d.ts +1 -0
  12. package/dist/cli/test-setup.js +30 -0
  13. package/dist/cli/test.d.ts +4 -0
  14. package/dist/cli/test.js +23 -0
  15. package/dist/cli.d.ts +2 -0
  16. package/dist/cli.js +53 -0
  17. package/dist/exports/config.d.ts +2 -0
  18. package/dist/exports/config.js +2 -0
  19. package/dist/exports/log.d.ts +2 -0
  20. package/{src → dist}/exports/log.js +1 -2
  21. package/dist/exports/test-helpers.d.ts +5 -0
  22. package/dist/exports/test-helpers.js +7 -0
  23. package/dist/lifecycle.d.ts +7 -0
  24. package/dist/lifecycle.js +18 -0
  25. package/dist/main.d.ts +22 -0
  26. package/dist/main.js +102 -0
  27. package/dist/modules.d.ts +5 -0
  28. package/dist/modules.js +186 -0
  29. package/dist/util/duplicate-core.d.ts +186 -0
  30. package/dist/util/duplicate-core.js +377 -0
  31. package/dist/util/import-config.d.ts +52 -0
  32. package/dist/util/import-config.js +256 -0
  33. package/dist/util/resolve-entry-point.d.ts +1 -0
  34. package/dist/util/resolve-entry-point.js +14 -0
  35. package/dist/util/resolve-module-name.d.ts +14 -0
  36. package/dist/util/resolve-module-name.js +33 -0
  37. package/package.json +41 -12
  38. package/scripts/postinstall.js +24 -2
  39. package/.claude/index.md +0 -96
  40. package/.github/workflows/ci.yml +0 -16
  41. package/.github/workflows/publish.yml +0 -51
  42. package/docs/api.md +0 -89
  43. package/docs/cli.md +0 -78
  44. package/docs/configuration.md +0 -72
  45. package/docs/conventions/discord-conventions.md +0 -62
  46. package/docs/conventions/framework-modules.md +0 -127
  47. package/docs/conventions/index.md +0 -24
  48. package/docs/conventions/orm-conventions.md +0 -190
  49. package/docs/conventions/project-structure.md +0 -105
  50. package/docs/conventions/rest-conventions.md +0 -96
  51. package/docs/conventions/testing-conventions.md +0 -56
  52. package/docs/developing-modules.md +0 -108
  53. package/docs/index.md +0 -15
  54. package/docs/lifecycle.md +0 -47
  55. package/docs/logging.md +0 -52
  56. package/docs/modules.md +0 -78
  57. package/docs/testing.md +0 -64
  58. package/src/cli/help.js +0 -48
  59. package/src/cli/load-commands.js +0 -56
  60. package/src/cli/new.js +0 -237
  61. package/src/cli/serve.js +0 -38
  62. package/src/cli/test-setup.js +0 -8
  63. package/src/cli/test.js +0 -27
  64. package/src/cli.js +0 -63
  65. package/src/exports/config.js +0 -3
  66. package/src/exports/test-helpers.js +0 -8
  67. package/src/lifecycle.js +0 -17
  68. package/src/main.js +0 -101
  69. package/src/modules.js +0 -112
@@ -0,0 +1,422 @@
1
+ import { confirm, prompt } from '@stonyx/utils/prompt';
2
+ import { createFile, createDirectory, copyFile, fileExists } from '@stonyx/utils/file';
3
+ import { spawn } from 'child_process';
4
+ import { readFileSync } from 'fs';
5
+ import path from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ export const MODULE_OPTIONS = [
8
+ {
9
+ question: 'Will this project need a REST server?',
10
+ package: '@stonyx/rest-server',
11
+ dirs: ['requests']
12
+ },
13
+ {
14
+ question: 'Will this project need WebSockets?',
15
+ package: '@stonyx/sockets',
16
+ dirs: ['socket-handlers']
17
+ },
18
+ {
19
+ question: 'Will this project need data management?',
20
+ package: '@stonyx/orm',
21
+ dirs: ['models', 'serializers', 'access', 'transforms', 'hooks'],
22
+ files: { 'config/db-schema.ts': generateDbSchema }
23
+ },
24
+ {
25
+ question: 'Will this project need scheduled tasks (cron)?',
26
+ package: '@stonyx/cron',
27
+ dirs: ['crons']
28
+ },
29
+ {
30
+ question: 'Will this project need OAuth?',
31
+ package: '@stonyx/oauth'
32
+ },
33
+ {
34
+ question: 'Will this project need pub/sub events?',
35
+ package: '@stonyx/events'
36
+ },
37
+ {
38
+ question: 'Will this project need a Discord bot?',
39
+ package: '@stonyx/discord',
40
+ dirs: ['discord-commands', 'discord-events']
41
+ }
42
+ ];
43
+ export function generateDbSchema() {
44
+ return `import { Model, hasMany, type HasMany } from '@stonyx/orm';
45
+
46
+ export default class DBModel extends Model {
47
+ // Define your collections here
48
+ // examples: HasMany = hasMany('example');
49
+ }
50
+ `;
51
+ }
52
+ /**
53
+ * The npm dist-tag that points at a package's stable release line. Only ever
54
+ * used as a *release line* selector for `@stonyx/*` modules (see
55
+ * `releaseTagFor`) -- never as the specifier for the core, which is always
56
+ * pinned exactly.
57
+ */
58
+ const STABLE_DIST_TAG = 'latest';
59
+ /** Absolute path to this package's own root, from both `src/` and `dist/`. */
60
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
61
+ /** A full semver version: `major.minor.patch`, optional prerelease, optional build. */
62
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
63
+ /**
64
+ * A string npm accepts as a *dist-tag* and never reinterprets as a version range.
65
+ * npm requires a tag to be non-numeric, and `x`/`X` are semver wildcards rather
66
+ * than tag names, so both are rejected in `releaseTagFor`.
67
+ */
68
+ const DIST_TAG = /^[A-Za-z][0-9A-Za-z-]*$/;
69
+ /**
70
+ * Rejects any version this generator must not emit.
71
+ *
72
+ * `readCoreVersion` used to check only that the field was a non-empty string, so
73
+ * `"garbage"`, `"0.2"` and `"latest"` all flowed through to the manifest verbatim
74
+ * and made `releaseTagFor` fall through to `latest` -- the one specifier
75
+ * abofs/stonyx#113 exists to stop emitting.
76
+ */
77
+ function assertVersionShape(version, source) {
78
+ if (typeof version !== 'string' || !version) {
79
+ throw new Error(`Could not read the stonyx version from ${source}`);
80
+ }
81
+ if (!SEMVER.test(version)) {
82
+ throw new Error(`The stonyx version from ${source} is not a semver version: "${version}"`);
83
+ }
84
+ }
85
+ /**
86
+ * The version of the `stonyx` package running this generator, read from its own
87
+ * `package.json` at call time.
88
+ *
89
+ * Read rather than hardcoded on purpose: a literal would be correct on the day
90
+ * it was written and silently stale on every day after (abofs/stonyx#113).
91
+ */
92
+ export function readCoreVersion() {
93
+ const manifest = path.join(packageRoot, 'package.json');
94
+ const raw = readFileSync(manifest, 'utf8');
95
+ const version = JSON.parse(raw).version;
96
+ assertVersionShape(version, manifest);
97
+ return version;
98
+ }
99
+ /**
100
+ * The npm dist-tag naming the release line a version belongs to:
101
+ * `0.2.3-beta.96` -> `beta`, `0.2.3-alpha.4` -> `alpha`, `0.2.2` -> `latest`.
102
+ *
103
+ * Every scaffolded `@stonyx/*` module is requested on the same line as the core
104
+ * that scaffolded it, so the generated project cannot mix a prerelease core with
105
+ * modules from the stable line (or the reverse).
106
+ *
107
+ * Throws, rather than guessing, when the prerelease identifier is not usable as a
108
+ * dist-tag. Returning it verbatim was only safe for *alphabetic* identifiers: npm
109
+ * parses a numeric or wildcard identifier as a version **range**, so `0.2.3-0`
110
+ * emitted `"0"` and `0.2.3-x` emitted `"x"`, both of which install with rc=0 and
111
+ * silently resolve the module's `latest` release -- for `@stonyx/orm` that is
112
+ * `0.3.1`, which pins `stonyx@0.2.3-beta.11` and so reproduces abofs/stonyx#113
113
+ * through a different door, with no error. `0.2.3-0` is reachable from this
114
+ * repo's own `publish.yml` `custom-version` dispatch input, which accepts any
115
+ * semver string and also expands the keyword `prerelease` to `x.y.z-0`.
116
+ *
117
+ * Two bounds remain, both loud rather than silent:
118
+ *
119
+ * - An alphabetic identifier is assumed to also be a published dist-tag name.
120
+ * True for `beta` and `alpha`, the only two lines the fleet publishes; a core
121
+ * released as e.g. `0.2.3-rc.1` with no `rc` dist-tag scaffolds an unresolvable
122
+ * module specifier, which fails `pnpm install` with
123
+ * `ERR_PNPM_NO_MATCHING_VERSION`. The tag has to exist on every package in
124
+ * `MODULE_OPTIONS`, not only on the core.
125
+ * - On the stable line this returns `latest`, the correct tag for that line -- but
126
+ * only useful once the *modules* have advanced their own `latest` tags. Today
127
+ * `@stonyx/orm@latest` is `0.3.1` and pins `stonyx@0.2.3-beta.11`, so the module
128
+ * `latest` tags must advance before the core's does (abofs/stonyx#115).
129
+ */
130
+ export function releaseTagFor(version) {
131
+ // Fail closed, not open. Without this the exported function still answered
132
+ // `latest` for `"garbage"`, `"0.2"`, `""` and `"latest"` itself -- the same
133
+ // fall-through-to-`latest` shape this change exists to remove, one level down
134
+ // from the emission path that `generatePackageJson` already guards.
135
+ assertVersionShape(version, 'the supplied version');
136
+ const prerelease = /^\d+\.\d+\.\d+-(.*)$/.exec(version);
137
+ if (!prerelease)
138
+ return STABLE_DIST_TAG;
139
+ const identifier = prerelease[1].split('.')[0];
140
+ if (!DIST_TAG.test(identifier) || /^[xX]$/.test(identifier)) {
141
+ throw new Error(`Cannot derive a dist-tag from the prerelease identifier "${identifier}" in version "${version}": ` +
142
+ 'npm reads it as a version range, not a tag.');
143
+ }
144
+ if (identifier === STABLE_DIST_TAG) {
145
+ throw new Error(`A prerelease core must not request modules at "${STABLE_DIST_TAG}" (version "${version}").`);
146
+ }
147
+ return identifier;
148
+ }
149
+ export function generatePackageJson(name, selectedModules, coreVersion = readCoreVersion()) {
150
+ // Resolved first, before anything is emitted, and unconditionally -- deliberately
151
+ // not inside the module loop below. `releaseTagFor` asserts the version's shape as
152
+ // its first act, so this one call is also what stops an injected non-semver
153
+ // `coreVersion` from reaching the manifest verbatim.
154
+ //
155
+ // A second `assertVersionShape(coreVersion, ...)` stood at the top of this function
156
+ // until abofs/stonyx#118's review: deleting it left the suite green, because this
157
+ // call already rejects the same value on every path. It was removed rather than
158
+ // left as decoration. The invariant that replaces it is positional -- keep this
159
+ // call above the emission and the guard stays load-bearing; push it under an
160
+ // `if (selectedModules.length)` and the core becomes unvalidated again.
161
+ const moduleTag = releaseTagFor(coreVersion);
162
+ // The framework is a runtime dependency of the application, pinned exactly to
163
+ // the core that generated the project.
164
+ const dependencies = { stonyx: coreVersion };
165
+ const devDependencies = {
166
+ qunit: '^2.24.1',
167
+ tsx: '^4.21.0',
168
+ typescript: '^5.8.3'
169
+ };
170
+ // Modules are discovered from devDependencies (see docs/modules.md), and are
171
+ // requested on the core's own release line rather than at `latest`.
172
+ for (const mod of selectedModules) {
173
+ devDependencies[mod.package] = moduleTag;
174
+ }
175
+ // Sort dependencies alphabetically
176
+ const sorted = Object.fromEntries(Object.entries(devDependencies).sort(([a], [b]) => a.localeCompare(b)));
177
+ return JSON.stringify({
178
+ name,
179
+ version: '0.1.0',
180
+ type: 'module',
181
+ private: true,
182
+ scripts: {
183
+ build: 'tsc',
184
+ serve: 'stonyx serve',
185
+ start: 'stonyx serve',
186
+ test: "NODE_ENV=test node --import tsx/esm --import ./test/setup.ts node_modules/qunit/bin/qunit.js 'test/**/*-test.ts'"
187
+ },
188
+ dependencies,
189
+ devDependencies: sorted
190
+ }, null, 2) + '\n';
191
+ }
192
+ export function generateAppTs() {
193
+ return `import log from 'stonyx/log';
194
+
195
+ export default class App {
196
+ static instance: App;
197
+ ready: Promise<void>;
198
+
199
+ constructor() {
200
+ if (App.instance) return App.instance;
201
+ App.instance = this;
202
+
203
+ this.ready = this.init();
204
+ }
205
+
206
+ async init(): Promise<void> {
207
+ log.info('Initializing Application');
208
+
209
+ // Application setup here
210
+
211
+ log.info('Application has been initialized');
212
+ }
213
+ }
214
+ `;
215
+ }
216
+ export function generateEnvironmentTs() {
217
+ return `import type { StoynxConfig } from 'stonyx';
218
+
219
+ const config: StoynxConfig = {
220
+ };
221
+
222
+ export default config;
223
+ `;
224
+ }
225
+ export function generateTestEnvironmentTs() {
226
+ return `import type { StoynxConfig } from 'stonyx';
227
+
228
+ // Test-specific config overrides
229
+ const config: Partial<StoynxConfig> = {
230
+ };
231
+
232
+ export default config;
233
+ `;
234
+ }
235
+ export function generateSetupTs() {
236
+ return `// Test setup: bootstrap Stonyx with the consumer config before qunit runs.
237
+ // Loaded via \`node --import ./test/setup.ts\`.
238
+ import { pathToFileURL } from 'url';
239
+
240
+ const cwd = process.cwd();
241
+
242
+ const { default: Stonyx } = await import('stonyx');
243
+ const { default: config } = await import(pathToFileURL(\`\${cwd}/config/environment.ts\`).href);
244
+
245
+ new Stonyx(config, cwd);
246
+
247
+ await Stonyx.ready;
248
+ `;
249
+ }
250
+ export function generateZzExitTestTs() {
251
+ return `// Force-exit hook for qunit runs.
252
+ //
253
+ // Stonyx modules may keep listeners/servers open that would otherwise
254
+ // block the process from exiting after tests complete, causing CI to
255
+ // hit timeouts even though all tests passed.
256
+ //
257
+ // Named \`zz-\` so alphabetical test-file order places it last, after
258
+ // all real test files have registered with QUnit.
259
+ import QUnit from 'qunit';
260
+
261
+ QUnit.on('runEnd', () => {
262
+ setImmediate(() => process.exit(process.exitCode ?? 0));
263
+ });
264
+ `;
265
+ }
266
+ export function generateEnvironmentExampleTs() {
267
+ return `// Copy this file to environment.ts and fill in your values
268
+ // All values should use environment variables with ?? fallback defaults
269
+
270
+ const {
271
+ NODE_ENV,
272
+ } = process.env;
273
+
274
+ const environment: string = NODE_ENV ?? 'development';
275
+
276
+ export default {
277
+ }
278
+ `;
279
+ }
280
+ export function generateGitignore() {
281
+ return `node_modules/
282
+ .env
283
+ db.json
284
+ *.log
285
+
286
+ # Compiled TypeScript output (tsc compiles .ts to .js in-place)
287
+ *.js
288
+ *.d.ts
289
+ *.js.map
290
+ `;
291
+ }
292
+ export function generateTsConfig() {
293
+ return JSON.stringify({
294
+ compilerOptions: {
295
+ strict: true,
296
+ target: 'ES2022',
297
+ module: 'NodeNext',
298
+ moduleResolution: 'NodeNext',
299
+ outDir: '.',
300
+ rootDir: '.',
301
+ esModuleInterop: true,
302
+ skipLibCheck: true,
303
+ forceConsistentCasingInFileNames: true
304
+ },
305
+ include: ['**/*.ts'],
306
+ exclude: ['node_modules', 'test']
307
+ }, null, 2) + '\n';
308
+ }
309
+ /**
310
+ * Rejects when `pnpm install` fails, either by exiting non-zero or by failing to
311
+ * spawn. Exported so the rejection path is testable without a network round-trip.
312
+ */
313
+ export function runPnpmInstall(projectDir) {
314
+ return new Promise((resolve, reject) => {
315
+ const child = spawn('pnpm', ['install'], {
316
+ cwd: projectDir,
317
+ stdio: 'inherit'
318
+ });
319
+ child.on('close', code => {
320
+ if (code === 0)
321
+ resolve();
322
+ else
323
+ reject(new Error(`pnpm install exited with code ${code}`));
324
+ });
325
+ child.on('error', reject);
326
+ });
327
+ }
328
+ /**
329
+ * Write every scaffolded file to disk given a resolved project directory,
330
+ * app name, and pre-selected module options. Factored out of `newCommand`
331
+ * so tests can exercise the file-writing path without interactive prompts.
332
+ */
333
+ export async function scaffoldProject(projectDir, appName, selectedModules) {
334
+ // Create project directory
335
+ await createDirectory(projectDir);
336
+ // Copy .nvmrc from monorepo root
337
+ const monorepoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
338
+ const nvmrcSource = path.join(monorepoRoot, '.nvmrc');
339
+ if (await fileExists(nvmrcSource)) {
340
+ await copyFile(nvmrcSource, path.join(projectDir, '.nvmrc'));
341
+ }
342
+ // Generate core files
343
+ await createFile(path.join(projectDir, 'package.json'), generatePackageJson(appName, selectedModules));
344
+ await createFile(path.join(projectDir, 'app.ts'), generateAppTs());
345
+ await createFile(path.join(projectDir, 'tsconfig.json'), generateTsConfig());
346
+ await createFile(path.join(projectDir, '.gitignore'), generateGitignore());
347
+ // Create config directory and files
348
+ await createFile(path.join(projectDir, 'config', 'environment.ts'), generateEnvironmentTs());
349
+ await createFile(path.join(projectDir, 'config', 'environment.example.ts'), generateEnvironmentExampleTs());
350
+ // Create module-specific directories and files
351
+ for (const mod of selectedModules) {
352
+ if (mod.dirs) {
353
+ for (const dir of mod.dirs) {
354
+ await createDirectory(path.join(projectDir, dir));
355
+ // Create .gitkeep so empty dirs are tracked
356
+ await createFile(path.join(projectDir, dir, '.gitkeep'), '');
357
+ }
358
+ }
359
+ if (mod.files) {
360
+ for (const [filePath, generator] of Object.entries(mod.files)) {
361
+ await createFile(path.join(projectDir, filePath), generator());
362
+ }
363
+ }
364
+ }
365
+ // Create test structure
366
+ await createDirectory(path.join(projectDir, 'test', 'unit'));
367
+ await createFile(path.join(projectDir, 'test', 'unit', '.gitkeep'), '');
368
+ await createDirectory(path.join(projectDir, 'test', 'integration'));
369
+ await createFile(path.join(projectDir, 'test', 'integration', '.gitkeep'), '');
370
+ await createDirectory(path.join(projectDir, 'test', 'acceptance'));
371
+ await createFile(path.join(projectDir, 'test', 'acceptance', '.gitkeep'), '');
372
+ // Create test config (TS)
373
+ await createFile(path.join(projectDir, 'test', 'config', 'environment.ts'), generateTestEnvironmentTs());
374
+ // Create test harness files (setup bootstraps Stonyx, zz-exit-test drains event loop)
375
+ await createFile(path.join(projectDir, 'test', 'setup.ts'), generateSetupTs());
376
+ await createFile(path.join(projectDir, 'test', 'zz-exit-test.ts'), generateZzExitTestTs());
377
+ }
378
+ export default async function newCommand({ args }) {
379
+ let appName = args[0];
380
+ if (!appName) {
381
+ appName = await prompt('Project name:');
382
+ }
383
+ if (!appName) {
384
+ console.error('Project name is required.');
385
+ process.exit(1);
386
+ }
387
+ const projectDir = path.resolve(process.cwd(), appName);
388
+ if (await fileExists(projectDir)) {
389
+ console.error(`Directory "${appName}" already exists.`);
390
+ process.exit(1);
391
+ }
392
+ console.log(`\nScaffolding new Stonyx project: ${appName}\n`);
393
+ // Prompt for module selection
394
+ const selectedModules = [];
395
+ for (const mod of MODULE_OPTIONS) {
396
+ if (await confirm(mod.question)) {
397
+ selectedModules.push(mod);
398
+ }
399
+ }
400
+ console.log('\nCreating project structure...\n');
401
+ await scaffoldProject(projectDir, appName, selectedModules);
402
+ console.log('Installing dependencies...\n');
403
+ try {
404
+ await runPnpmInstall(projectDir);
405
+ }
406
+ catch (error) {
407
+ // `pnpm`'s own diagnostic already reached the terminal via stdio: 'inherit'.
408
+ // What used to be missing is the exit code: this catch discarded `error` and
409
+ // fell through to the success banner, so `stonyx new` announced success and
410
+ // exited 0 on a project with no node_modules -- loud to a human, silent to any
411
+ // supervisor, CI job or wrapper reading the status.
412
+ console.error(error instanceof Error ? error.message : String(error));
413
+ console.error(`\n✗ Project "${appName}" was created, but its dependencies are NOT installed.`);
414
+ console.error(`\n cd ${appName}`);
415
+ console.error(' pnpm install\n');
416
+ process.exitCode = 1;
417
+ return;
418
+ }
419
+ console.log(`\n✓ Project "${appName}" created successfully!`);
420
+ console.log(`\n cd ${appName}`);
421
+ console.log(` stonyx serve\n`);
422
+ }
@@ -0,0 +1,6 @@
1
+ import { type StoynxModule } from '../lifecycle.js';
2
+ export declare function createShutdownHandler(modules: StoynxModule[]): () => Promise<void>;
3
+ export declare function maybeRegisterAppShutdown(modules: StoynxModule[], appInstance: unknown, originalShutdown: () => Promise<void>): void;
4
+ export default function serve({ args }: {
5
+ args: string[];
6
+ }): Promise<void>;
@@ -0,0 +1,49 @@
1
+ import { resolve } from 'path';
2
+ import { pathToFileURL } from 'url';
3
+ import { runStartupHooks, runShutdownHooks } from '../lifecycle.js';
4
+ import { importConfig } from '../util/import-config.js';
5
+ import { resolveEntryPoint } from '../util/resolve-entry-point.js';
6
+ export function createShutdownHandler(modules) {
7
+ let shuttingDown = false;
8
+ return async () => {
9
+ if (shuttingDown)
10
+ return;
11
+ shuttingDown = true;
12
+ await runShutdownHooks(modules);
13
+ process.exit(0);
14
+ };
15
+ }
16
+ export function maybeRegisterAppShutdown(modules, appInstance, originalShutdown) {
17
+ if (appInstance &&
18
+ typeof appInstance.shutdown === 'function') {
19
+ const appShutdown = createShutdownHandler([
20
+ ...modules,
21
+ appInstance
22
+ ]);
23
+ process.removeListener('SIGTERM', originalShutdown);
24
+ process.removeListener('SIGINT', originalShutdown);
25
+ process.on('SIGTERM', appShutdown);
26
+ process.on('SIGINT', appShutdown);
27
+ }
28
+ }
29
+ export default async function serve({ args }) {
30
+ const cwd = process.cwd();
31
+ const entryFlag = args.indexOf('--entry');
32
+ const entryArg = (entryFlag !== -1 && entryFlag + 1 < args.length) ? args[entryFlag + 1] : null;
33
+ const entryPoint = entryArg !== null ? resolve(cwd, entryArg) : resolveEntryPoint(`${cwd}/app`);
34
+ const config = await importConfig(`${cwd}/config/environment`);
35
+ const { default: Stonyx } = await import('../main.js');
36
+ new Stonyx(config, cwd);
37
+ await Stonyx.ready;
38
+ const { modules } = Stonyx.instance;
39
+ await runStartupHooks(modules);
40
+ const shutdown = createShutdownHandler(modules);
41
+ process.on('SIGTERM', shutdown);
42
+ process.on('SIGINT', shutdown);
43
+ const entryModule = await import(pathToFileURL(entryPoint).href);
44
+ let appInstance;
45
+ if (entryModule.default) {
46
+ appInstance = new entryModule.default();
47
+ }
48
+ maybeRegisterAppShutdown(modules, appInstance, shutdown);
49
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ import { createRequire } from 'module';
2
+ import { importConfig } from '../util/import-config.js';
3
+ const cwd = process.cwd();
4
+ const { default: Stonyx } = await import('stonyx');
5
+ const config = await importConfig(`${cwd}/config/environment`);
6
+ new Stonyx(config, cwd);
7
+ // Drain the event loop once qunit finishes. Modules loaded by Stonyx
8
+ // (e.g. @stonyx/rest-server) may keep listeners/servers open that would
9
+ // otherwise block the process from exiting, causing CI to hit timeouts
10
+ // even though all tests passed.
11
+ //
12
+ // qunit's CLI bin does `delete require.cache[qunitPath]` and re-requires
13
+ // qunit before running, so any qunit instance we grab synchronously from
14
+ // this --import setup is a DIFFERENT object than the one qunit's CLI
15
+ // actually uses. We defer the hook registration with setImmediate so it
16
+ // runs AFTER the qunit bin has populated require.cache with its own
17
+ // instance; grabbing qunit via CJS require at that point returns the
18
+ // instance the tests are running on.
19
+ //
20
+ // See: https://github.com/abofs/stonyx/issues/55
21
+ const require = createRequire(import.meta.url);
22
+ setImmediate(() => {
23
+ const qunitPath = require.resolve('qunit', {
24
+ paths: [`${cwd}/node_modules`, cwd]
25
+ });
26
+ const QUnit = require(qunitPath);
27
+ QUnit.on('runEnd', () => {
28
+ setImmediate(() => process.exit(process.exitCode ?? 0));
29
+ });
30
+ });
@@ -0,0 +1,4 @@
1
+ export declare const DEFAULT_TEST_GLOB = "test/**/*-test.{js,ts}";
2
+ export default function test({ args }: {
3
+ args: string[];
4
+ }): Promise<void>;
@@ -0,0 +1,23 @@
1
+ import { spawn } from 'child_process';
2
+ import { fileURLToPath, pathToFileURL } from 'url';
3
+ import path from 'path';
4
+ export const DEFAULT_TEST_GLOB = 'test/**/*-test.{js,ts}';
5
+ export default async function test({ args }) {
6
+ const cwd = process.cwd();
7
+ const setupFile = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'test-setup.js');
8
+ const setupFileUrl = pathToFileURL(setupFile).href;
9
+ const qunitBin = path.resolve(cwd, 'node_modules/qunit/bin/qunit.js');
10
+ const testArgs = args.length > 0 ? args : [DEFAULT_TEST_GLOB];
11
+ const child = spawn(process.execPath, [
12
+ '--import', setupFileUrl,
13
+ qunitBin,
14
+ ...testArgs
15
+ ], {
16
+ cwd,
17
+ stdio: 'inherit',
18
+ env: { ...process.env, NODE_ENV: 'test' }
19
+ });
20
+ child.on('close', (code) => {
21
+ process.exit(code ?? 1);
22
+ });
23
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ import serve from './cli/serve.js';
3
+ import test from './cli/test.js';
4
+ import help from './cli/help.js';
5
+ import newCommand from './cli/new.js';
6
+ import loadModuleCommands from './cli/load-commands.js';
7
+ import { importConfig } from './util/import-config.js';
8
+ try {
9
+ process.loadEnvFile();
10
+ }
11
+ catch { /* no .env file */ }
12
+ const aliases = { s: 'serve', t: 'test', h: 'help', n: 'new' };
13
+ const builtInCommands = {
14
+ serve: { description: 'Bootstrap Stonyx and run the app', run: serve },
15
+ test: { description: 'Bootstrap Stonyx in test mode and run tests', run: test },
16
+ new: { description: 'Scaffold a new Stonyx project', run: newCommand },
17
+ help: { description: 'Show available commands', run: help }
18
+ };
19
+ const args = process.argv.slice(2);
20
+ const commandName = aliases[args[0]] || args[0];
21
+ const commandArgs = args.slice(1);
22
+ async function main() {
23
+ if (!commandName || commandName === 'help') {
24
+ await help({ args: commandArgs, builtInCommands, loadModuleCommands });
25
+ return;
26
+ }
27
+ const builtIn = builtInCommands[commandName];
28
+ if (builtIn) {
29
+ await builtIn.run({ args: commandArgs });
30
+ return;
31
+ }
32
+ // Search module commands
33
+ const moduleCommands = await loadModuleCommands();
34
+ const moduleCommand = moduleCommands[commandName];
35
+ if (moduleCommand) {
36
+ const cwd = process.cwd();
37
+ if (moduleCommand.bootstrap) {
38
+ const config = await importConfig(`${cwd}/config/environment`);
39
+ const { default: Stonyx } = await import('./main.js');
40
+ new Stonyx(config, cwd);
41
+ await Stonyx.ready;
42
+ }
43
+ await moduleCommand.run({ args: commandArgs, cwd });
44
+ return;
45
+ }
46
+ console.error(`Unknown command: ${args[0]}\n`);
47
+ await help({ args: [], builtInCommands, loadModuleCommands });
48
+ process.exit(1);
49
+ }
50
+ main().catch(error => {
51
+ console.error(error);
52
+ process.exit(1);
53
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("stonyx").StoynxConfig;
2
+ export default _default;
@@ -0,0 +1,2 @@
1
+ import Stonyx from 'stonyx';
2
+ export default Stonyx.config;
@@ -0,0 +1,2 @@
1
+ declare const _default: import("@stonyx/logs").default;
2
+ export default _default;
@@ -1,3 +1,2 @@
1
1
  import Stonyx from 'stonyx';
2
-
3
- export default Stonyx.log;
2
+ export default Stonyx.log;
@@ -0,0 +1,5 @@
1
+ interface TestHooks {
2
+ before(fn: () => Promise<void>): void;
3
+ }
4
+ export declare function setupIntegrationTests(hooks: TestHooks): void;
5
+ export {};
@@ -0,0 +1,7 @@
1
+ import Stonyx from 'stonyx';
2
+ export function setupIntegrationTests(hooks) {
3
+ hooks.before(async function () {
4
+ await Stonyx.ready;
5
+ console.log('Stonyx ready');
6
+ });
7
+ }
@@ -0,0 +1,7 @@
1
+ export interface StoynxModule {
2
+ init?(): Promise<void>;
3
+ startup?(): Promise<void>;
4
+ shutdown?(): Promise<void>;
5
+ }
6
+ export declare function runStartupHooks(modules: StoynxModule[]): Promise<void>;
7
+ export declare function runShutdownHooks(modules: StoynxModule[]): Promise<void>;
@@ -0,0 +1,18 @@
1
+ export async function runStartupHooks(modules) {
2
+ for (const module of modules) {
3
+ if (typeof module.startup === 'function')
4
+ await module.startup();
5
+ }
6
+ }
7
+ export async function runShutdownHooks(modules) {
8
+ for (const module of [...modules].reverse()) {
9
+ if (typeof module.shutdown === 'function') {
10
+ try {
11
+ await module.shutdown();
12
+ }
13
+ catch (error) {
14
+ console.error('Error during module shutdown:', error);
15
+ }
16
+ }
17
+ }
18
+ }