@niyamulahsan/create-deskapp 1.2.4 → 1.2.6

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 (104) hide show
  1. package/package.json +16 -16
  2. package/template/.env.example +20 -13
  3. package/template/AGENTS.md +699 -0
  4. package/template/package.json +3 -0
  5. package/template/src/config/app.ts +26 -24
  6. package/template/src/config/winsetup.ts +93 -91
  7. package/template/src/core/api/binding-error.ts +57 -0
  8. package/template/src/core/api/bindings.generated.ts +2 -0
  9. package/template/src/core/api/generate.manifest.ts +84 -80
  10. package/template/src/core/api/registry.ts +58 -48
  11. package/template/src/core/config.ts +101 -99
  12. package/template/src/core/database/aggregate.ts +89 -85
  13. package/template/src/core/database/config.ts +50 -48
  14. package/template/src/core/database/connection.ts +116 -114
  15. package/template/src/core/database/migrate-hooks.ts +86 -84
  16. package/template/src/core/database/paginate.ts +226 -224
  17. package/template/src/core/database/reset.ts +21 -19
  18. package/template/src/core/database/seed.ts +169 -167
  19. package/template/src/core/database/status.ts +37 -35
  20. package/template/src/core/env.ts +108 -106
  21. package/template/src/core/facade.ts +63 -61
  22. package/template/src/core/maker/db/fresh.ts +10 -8
  23. package/template/src/core/maker/db/generate.ts +13 -11
  24. package/template/src/core/maker/db/helpers.ts +92 -96
  25. package/template/src/core/maker/db/migrate.ts +37 -35
  26. package/template/src/core/maker/db/mod.ts +93 -91
  27. package/template/src/core/maker/db/module-migrate.ts +56 -54
  28. package/template/src/core/maker/db/push.ts +23 -21
  29. package/template/src/core/maker/db/reset.ts +8 -6
  30. package/template/src/core/maker/db/seed.ts +9 -7
  31. package/template/src/core/maker/db/status.ts +8 -6
  32. package/template/src/core/maker/help.ts +59 -57
  33. package/template/src/core/maker/make/controller.ts +25 -22
  34. package/template/src/core/maker/make/helpers.ts +97 -91
  35. package/template/src/core/maker/make/mod.ts +69 -67
  36. package/template/src/core/maker/make/model.ts +16 -14
  37. package/template/src/core/maker/make/module.ts +53 -39
  38. package/template/src/core/maker/make/seeder.ts +23 -21
  39. package/template/src/core/maker/make/test.ts +33 -30
  40. package/template/src/core/maker/mod.ts +85 -83
  41. package/template/src/core/maker/run/mod.ts +134 -132
  42. package/template/src/core/maker/stub.ts +26 -24
  43. package/template/src/core/maker/stubs/controller/controller.controller.stub +57 -55
  44. package/template/src/core/maker/stubs/controller/controller.schema.stub +18 -13
  45. package/template/src/core/maker/stubs/facade/facade.stub +21 -0
  46. package/template/src/core/maker/stubs/model/model.stub +10 -8
  47. package/template/src/core/maker/stubs/seeder/seeder.stub +18 -16
  48. package/template/src/core/maker/stubs/test/test.stub +9 -7
  49. package/template/src/core/maker/sync-config.ts +93 -94
  50. package/template/src/core/utils/password.ts +29 -27
  51. package/template/src/core/utils/playwright.ts +123 -121
  52. package/template/src/core/utils/queue.ts +68 -66
  53. package/template/src/core/utils/scheduler.ts +62 -60
  54. package/template/src/core/utils/storage.ts +3 -1
  55. package/template/src/core/utils/validation.ts +37 -35
  56. package/template/src/database/schema.ts +2 -0
  57. package/template/src/main.ts +120 -118
  58. package/template/src/modules/app/__tests__/demo.controller.test.ts +75 -0
  59. package/template/src/modules/app/__tests__/net.controller.test.ts +65 -0
  60. package/template/src/modules/app/__tests__/playwright.controller.test.ts +50 -0
  61. package/template/src/modules/app/__tests__/storage.controller.test.ts +114 -0
  62. package/template/src/modules/app/__tests__/window.controller.test.ts +98 -0
  63. package/template/src/modules/app/controllers/demo.controller.ts +120 -118
  64. package/template/src/modules/app/controllers/net.controller.ts +50 -48
  65. package/template/src/modules/app/controllers/playwright.controller.ts +142 -140
  66. package/template/src/modules/app/controllers/storage.controller.ts +231 -229
  67. package/template/src/modules/app/controllers/window.controller.ts +2 -0
  68. package/template/src/modules/app/facade.ts +21 -0
  69. package/template/src/preload.ts +25 -2
  70. package/template/src/ui/src/App.vue +4 -2
  71. package/template/src/ui/src/app.ts +38 -23
  72. package/template/src/ui/src/bindings.d.ts +18 -16
  73. package/template/src/ui/src/components/Button.vue +34 -32
  74. package/template/src/ui/src/components/Checkbox.vue +26 -29
  75. package/template/src/ui/src/components/Input.vue +221 -227
  76. package/template/src/ui/src/components/InputGroup.vue +141 -0
  77. package/template/src/ui/src/components/InputPasswordToggle.vue +204 -0
  78. package/template/src/ui/src/components/Modal.vue +65 -55
  79. package/template/src/ui/src/components/Spinner.vue +44 -42
  80. package/template/src/ui/src/components/Switch.vue +62 -65
  81. package/template/src/ui/src/components/TextArea.vue +108 -121
  82. package/template/src/ui/src/components/Toast.vue +55 -56
  83. package/template/src/ui/src/components/datatable/DataTableSkeleton.vue +100 -98
  84. package/template/src/ui/src/components/datatable/Pagination.vue +153 -125
  85. package/template/src/ui/src/components/datatable/SelectOpption.vue +36 -35
  86. package/template/src/ui/src/components/datatable/index.vue +336 -258
  87. package/template/src/ui/src/env.d.ts +16 -13
  88. package/template/src/ui/src/global.d.ts +21 -2
  89. package/template/src/ui/src/helpers/nformatter.ts +12 -10
  90. package/template/src/ui/src/pages/dashboard/index.vue +690 -687
  91. package/template/src/ui/src/plugins/browserDetect.ts +57 -0
  92. package/template/src/ui/src/plugins/gum.ts +576 -549
  93. package/template/src/ui/src/plugins/pulse.ts +181 -147
  94. package/template/src/ui/src/plugins/routeProgress.ts +89 -0
  95. package/template/src/ui/src/router/index.ts +44 -25
  96. package/template/src/ui/src/stores/example.ts +2 -0
  97. package/template/src/ui/vite.config.ts +40 -38
  98. package/template/src/window/app-menu.ts +89 -87
  99. package/template/src/window/config.ts +14 -12
  100. package/template/src/window/context-menu.ts +23 -21
  101. package/template/src/window/dialogs.ts +92 -90
  102. package/template/src/window/manager.ts +2 -0
  103. package/template/src/window/native.ts +47 -45
  104. package/template/src/window/tray.ts +132 -130
@@ -1,60 +1,62 @@
1
- import { Cron } from "croner";
2
-
3
- /**
4
- * scheduler.ts - reusable cron scheduling backed by `croner`.
5
- *
6
- * Named schedules are unique (same name replaces the old job). Call
7
- * `cron.stop()` on shutdown for all jobs. Import via the facade:
8
- * `import { cron } from "@/core/facade.ts"`.
9
- */
10
-
11
- const jobs = new Map<string, Cron>();
12
-
13
- export interface CronHandle {
14
- stop(): void;
15
- }
16
-
17
- /**
18
- * Cron namespace - schedule/replace unique named jobs and stop them all at
19
- * shutdown. Access through the facade: `cron.schedule(...)`, `cron.stop()`.
20
- */
21
- export const cron = {
22
- /**
23
- * Schedule a named cron job. Re-scheduling the same name replaces the old
24
- * job (and stops it). Returns a handle with `stop()`.
25
- */
26
- schedule(name: string, expression: string, task: () => void | Promise<void>, options?: { timezone?: string }): CronHandle {
27
- return scheduleCron(name, expression, task, options);
28
- },
29
-
30
- /** Stop every scheduled job (call on app shutdown). */
31
- stop(): void {
32
- stopSchedules();
33
- }
34
- };
35
-
36
- function scheduleCron(name: string, expression: string, task: () => void | Promise<void>, options?: { timezone?: string }): CronHandle {
37
- jobs.get(name)?.stop();
38
- const job = new Cron(
39
- expression,
40
- {
41
- timezone: options?.timezone,
42
- catch: (error: unknown) => console.error(`[scheduler] "${name}" run failed:`, error)
43
- },
44
- () => {
45
- void task();
46
- }
47
- );
48
- jobs.set(name, job);
49
- return {
50
- stop() {
51
- job.stop();
52
- jobs.delete(name);
53
- }
54
- };
55
- }
56
-
57
- function stopSchedules(): void {
58
- for (const job of jobs.values()) job.stop();
59
- jobs.clear();
60
- }
1
+ // ./src/core/utils/scheduler.ts
2
+
3
+ import { Cron } from "croner";
4
+
5
+ /**
6
+ * scheduler.ts - reusable cron scheduling backed by `croner`.
7
+ *
8
+ * Named schedules are unique (same name replaces the old job). Call
9
+ * `cron.stop()` on shutdown for all jobs. Import via the facade:
10
+ * `import { cron } from "@/core/facade.ts"`.
11
+ */
12
+
13
+ const jobs = new Map<string, Cron>();
14
+
15
+ export interface CronHandle {
16
+ stop(): void;
17
+ }
18
+
19
+ /**
20
+ * Cron namespace - schedule/replace unique named jobs and stop them all at
21
+ * shutdown. Access through the facade: `cron.schedule(...)`, `cron.stop()`.
22
+ */
23
+ export const cron = {
24
+ /**
25
+ * Schedule a named cron job. Re-scheduling the same name replaces the old
26
+ * job (and stops it). Returns a handle with `stop()`.
27
+ */
28
+ schedule(name: string, expression: string, task: () => void | Promise<void>, options?: { timezone?: string }): CronHandle {
29
+ return scheduleCron(name, expression, task, options);
30
+ },
31
+
32
+ /** Stop every scheduled job (call on app shutdown). */
33
+ stop(): void {
34
+ stopSchedules();
35
+ }
36
+ };
37
+
38
+ function scheduleCron(name: string, expression: string, task: () => void | Promise<void>, options?: { timezone?: string }): CronHandle {
39
+ jobs.get(name)?.stop();
40
+ const job = new Cron(
41
+ expression,
42
+ {
43
+ timezone: options?.timezone,
44
+ catch: (error: unknown) => console.error(`[scheduler] "${name}" run failed:`, error)
45
+ },
46
+ () => {
47
+ void task();
48
+ }
49
+ );
50
+ jobs.set(name, job);
51
+ return {
52
+ stop() {
53
+ job.stop();
54
+ jobs.delete(name);
55
+ }
56
+ };
57
+ }
58
+
59
+ function stopSchedules(): void {
60
+ for (const job of jobs.values()) job.stop();
61
+ jobs.clear();
62
+ }
@@ -1,3 +1,5 @@
1
+ // ./src/core/utils/storage.ts
2
+
1
3
  import fs from "node:fs/promises";
2
4
  import { createRequire } from "node:module";
3
5
  import { basename, dirname, join, resolve } from "node:path";
@@ -7,7 +9,7 @@ import { appBaseDir } from "@/core/env";
7
9
  function getElectronApp(): { getPath: (name: string) => string; isPackaged: boolean } | undefined {
8
10
  try {
9
11
  // eslint-disable-next-line @typescript-eslint/no-require-imports
10
- const e = (typeof require !== "undefined" ? require : createRequire(process.cwd() + "/"))("electron") as any;
12
+ const e = (typeof require !== "undefined" ? require : createRequire(`${process.cwd()}/`))("electron") as any;
11
13
  if (e && typeof e.app?.getPath === "function") return e.app;
12
14
  } catch {}
13
15
  return undefined;
@@ -1,35 +1,37 @@
1
- import type { z as Zod } from "zod";
2
- import { z } from "zod";
3
-
4
- /**
5
- * validate - centralize schema validation with a consistent error shape.
6
- * Runs safeParseAsync and throws a structured failure on invalid data.
7
- * Mirrors the engine's `framework/http/validation.ts`.
8
- *
9
- * Consumers import from the facade:
10
- * import { validate } from "@/core/facade.ts";
11
- * const data = await validate.run(CreateUserSchema, body);
12
- * const schema = validate.z.object({ name: validate.z.string() });
13
- */
14
- export const validate = {
15
- /** zod - build schemas. */
16
- z,
17
-
18
- /**
19
- * Validate `data` against a zod schema; throws a structured 422-style
20
- * failure when invalid, otherwise returns the parsed data.
21
- */
22
- async run<T>(schema: Zod.ZodType<T>, data: unknown): Promise<T> {
23
- const result = await schema.safeParseAsync(data);
24
-
25
- if (!result.success) {
26
- throw {
27
- status: 422,
28
- message: "Validation failed",
29
- errors: result.error.flatten()
30
- };
31
- }
32
-
33
- return result.data;
34
- }
35
- };
1
+ // ./src/core/utils/validation.ts
2
+
3
+ import type { z as Zod } from "zod";
4
+ import { z } from "zod";
5
+
6
+ /**
7
+ * validate - centralize schema validation with a consistent error shape.
8
+ * Runs safeParseAsync and throws a structured failure on invalid data.
9
+ * Mirrors the engine's `framework/http/validation.ts`.
10
+ *
11
+ * Consumers import from the facade:
12
+ * import { validate } from "@/core/facade.ts";
13
+ * const data = await validate.run(CreateUserSchema, body);
14
+ * const schema = validate.z.object({ name: validate.z.string() });
15
+ */
16
+ export const validate = {
17
+ /** zod - build schemas. */
18
+ z,
19
+
20
+ /**
21
+ * Validate `data` against a zod schema; throws a structured 422-style
22
+ * failure when invalid, otherwise returns the parsed data.
23
+ */
24
+ async run<T>(schema: Zod.ZodType<T>, data: unknown): Promise<T> {
25
+ const result = await schema.safeParseAsync(data);
26
+
27
+ if (!result.success) {
28
+ throw {
29
+ status: 422,
30
+ message: "Validation failed",
31
+ errors: result.error.flatten()
32
+ };
33
+ }
34
+
35
+ return result.data;
36
+ }
37
+ };
@@ -1,3 +1,5 @@
1
+ // ./src/database/schema.ts
2
+
1
3
  /**
2
4
  * schema.ts - GENERATED by `npm run db:schema`. Do NOT edit by hand.
3
5
  * Aggregates every module + core database/models/*.ts into one Drizzle schema.
@@ -1,118 +1,120 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { windowDev, windows } from "@config/winsetup";
4
- import { app, BrowserWindow, dialog } from "electron";
5
- import { bindAll } from "@/core/api/registry";
6
- import { config } from "@/core/config";
7
- import { loadEnv } from "@/core/env";
8
- import { chrome, cron, db, win } from "@/core/facade";
9
- import { storage } from "@/core/utils/storage";
10
-
11
- function logFatal(err: unknown): void {
12
- const msg = err instanceof Error ? `${err.stack || err.message}` : String(err);
13
- console.error("[desktop][fatal]", msg);
14
- const appName = config?.appName || "Deskapp";
15
- const logName = `${config?.appKebab || "deskapp"}-startup.log`;
16
- try {
17
- const logFile = path.join(app.getPath("userData"), logName);
18
- fs.mkdirSync(path.dirname(logFile), { recursive: true });
19
- fs.appendFileSync(logFile, `\n[${new Date().toISOString()}] ${msg}\n`);
20
- } catch {}
21
- try {
22
- dialog.showErrorBox(`${appName} failed to start`, `${msg}\n\nLog: ${path.join(app.getPath("userData"), logName)}`);
23
- } catch {}
24
- }
25
-
26
- process.on("uncaughtException", (err) => logFatal(err));
27
- process.on("unhandledRejection", (reason) => logFatal(reason));
28
-
29
- function getPreloadPath(): string {
30
- return path.join(__dirname, "../preload/index.cjs");
31
- }
32
-
33
- function getRendererIndexPath(): string {
34
- return path.join(app.getAppPath(), "src", "ui", "dist", "index.html");
35
- }
36
-
37
- const gotLock = app.requestSingleInstanceLock();
38
- if (!gotLock) {
39
- app.quit();
40
- } else {
41
- app.on("second-instance", () => {
42
- const w = BrowserWindow.getAllWindows()[0];
43
- if (w) {
44
- if (w.isMinimized()) w.restore();
45
- w.focus();
46
- }
47
- });
48
-
49
- app.whenReady().then(async () => {
50
- try {
51
- // 1. Load .env
52
- loadEnv();
53
-
54
- // 2. Boot the backend
55
- console.log("[desktop] booting local stack (db)");
56
- await db.init();
57
- await storage.init();
58
- bindAll();
59
-
60
- // 3. Handle UI vs Headless
61
- if (config.ui.enabled) {
62
- let isMain = true;
63
- const preloadPath = getPreloadPath();
64
- const isDev = !app.isPackaged && process.env.NODE_ENV === "development";
65
- const devUrl = isDev ? "http://localhost:5173" : undefined;
66
-
67
- console.log(`[desktop] preload: ${preloadPath}`);
68
- for (const [name, preset] of Object.entries(windows)) {
69
- const created = win.createWindow(preset, name, preloadPath);
70
- if (!created) continue;
71
-
72
- // Show when ready to avoid a blank flash.
73
- created.once("ready-to-show", () => {
74
- if (!created.isDestroyed()) created.show();
75
- });
76
-
77
- if (isMain) {
78
- const chromeParts = chrome.resolveChrome(preset.chrome);
79
- chrome.setupDesktopChrome(created, chromeParts);
80
- }
81
- isMain = false;
82
-
83
- if (devUrl) {
84
- const route = preset.route || "/";
85
- await created.loadURL(`${devUrl}${route}`);
86
- } else {
87
- await created.loadFile(getRendererIndexPath());
88
- }
89
-
90
- if (isDev && windowDev.devTools !== "none") {
91
- created.webContents.openDevTools({ mode: windowDev.devTools });
92
- }
93
- }
94
- } else {
95
- // Headless mode: No windows, just a tray icon.
96
- console.log("[desktop] headless mode - running in tray");
97
- chrome.hideDock();
98
- chrome.createHeadlessTray();
99
- }
100
-
101
- app.on("before-quit", () => {
102
- db.close();
103
- cron.stop();
104
- });
105
- } catch (err) {
106
- logFatal(err);
107
- app.quit();
108
- }
109
- });
110
-
111
- // In Electron, if we don't explicitly call app.quit() here,
112
- // the app stays alive in the background (perfect for tray/headless).
113
- app.on("window-all-closed", () => {
114
- if (process.platform !== "darwin" && config.ui.enabled) {
115
- app.quit();
116
- }
117
- });
118
- }
1
+ // ./src/main.ts
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { windowDev, windows } from "@config/winsetup";
6
+ import { app, BrowserWindow, dialog } from "electron";
7
+ import { bindAll } from "@/core/api/registry";
8
+ import { config } from "@/core/config";
9
+ import { loadEnv } from "@/core/env";
10
+ import { chrome, cron, db, win } from "@/core/facade";
11
+ import { storage } from "@/core/utils/storage";
12
+
13
+ function logFatal(err: unknown): void {
14
+ const msg = err instanceof Error ? `${err.stack || err.message}` : String(err);
15
+ console.error("[desktop][fatal]", msg);
16
+ const appName = config?.appName || "Deskapp";
17
+ const logName = `${config?.appKebab || "deskapp"}-startup.log`;
18
+ try {
19
+ const logFile = path.join(app.getPath("userData"), logName);
20
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
21
+ fs.appendFileSync(logFile, `\n[${new Date().toISOString()}] ${msg}\n`);
22
+ } catch {}
23
+ try {
24
+ dialog.showErrorBox(`${appName} failed to start`, `${msg}\n\nLog: ${path.join(app.getPath("userData"), logName)}`);
25
+ } catch {}
26
+ }
27
+
28
+ process.on("uncaughtException", (err) => logFatal(err));
29
+ process.on("unhandledRejection", (reason) => logFatal(reason));
30
+
31
+ function getPreloadPath(): string {
32
+ return path.join(__dirname, "../preload/index.cjs");
33
+ }
34
+
35
+ function getRendererIndexPath(): string {
36
+ return path.join(app.getAppPath(), "src", "ui", "dist", "index.html");
37
+ }
38
+
39
+ const gotLock = app.requestSingleInstanceLock();
40
+ if (!gotLock) {
41
+ app.quit();
42
+ } else {
43
+ app.on("second-instance", () => {
44
+ const w = BrowserWindow.getAllWindows()[0];
45
+ if (w) {
46
+ if (w.isMinimized()) w.restore();
47
+ w.focus();
48
+ }
49
+ });
50
+
51
+ app.whenReady().then(async () => {
52
+ try {
53
+ // 1. Load .env
54
+ loadEnv();
55
+
56
+ // 2. Boot the backend
57
+ console.log("[desktop] booting local stack (db)");
58
+ await db.init();
59
+ await storage.init();
60
+ bindAll();
61
+
62
+ // 3. Handle UI vs Headless
63
+ if (config.ui.enabled) {
64
+ let isMain = true;
65
+ const preloadPath = getPreloadPath();
66
+ const isDev = !app.isPackaged && process.env.NODE_ENV === "development";
67
+ const devUrl = isDev ? "http://localhost:5173" : undefined;
68
+
69
+ console.log(`[desktop] preload: ${preloadPath}`);
70
+ for (const [name, preset] of Object.entries(windows)) {
71
+ const created = win.createWindow(preset, name, preloadPath);
72
+ if (!created) continue;
73
+
74
+ // Show when ready to avoid a blank flash.
75
+ created.once("ready-to-show", () => {
76
+ if (!created.isDestroyed()) created.show();
77
+ });
78
+
79
+ if (isMain) {
80
+ const chromeParts = chrome.resolveChrome(preset.chrome);
81
+ chrome.setupDesktopChrome(created, chromeParts);
82
+ }
83
+ isMain = false;
84
+
85
+ if (devUrl) {
86
+ const route = preset.route || "/";
87
+ await created.loadURL(`${devUrl}${route}`);
88
+ } else {
89
+ await created.loadFile(getRendererIndexPath());
90
+ }
91
+
92
+ if (isDev && windowDev.devTools !== "none") {
93
+ created.webContents.openDevTools({ mode: windowDev.devTools });
94
+ }
95
+ }
96
+ } else {
97
+ // Headless mode: No windows, just a tray icon.
98
+ console.log("[desktop] headless mode - running in tray");
99
+ chrome.hideDock();
100
+ chrome.createHeadlessTray();
101
+ }
102
+
103
+ app.on("before-quit", () => {
104
+ db.close();
105
+ cron.stop();
106
+ });
107
+ } catch (err) {
108
+ logFatal(err);
109
+ app.quit();
110
+ }
111
+ });
112
+
113
+ // In Electron, if we don't explicitly call app.quit() here,
114
+ // the app stays alive in the background (perfect for tray/headless).
115
+ app.on("window-all-closed", () => {
116
+ if (process.platform !== "darwin" && config.ui.enabled) {
117
+ app.quit();
118
+ }
119
+ });
120
+ }
@@ -0,0 +1,75 @@
1
+ // ./src/modules/app/__tests__/demo.controller.test.ts
2
+
3
+ import { afterEach, describe, expect, it, vi } from "vitest";
4
+
5
+ const stop = vi.fn();
6
+ vi.mock("@/core/facade", () => {
7
+ return {
8
+ queue: {
9
+ create: (_opts: { concurrency: number }) => ({
10
+ add: (task: () => Promise<any>) => task(),
11
+ }),
12
+ },
13
+ cron: {
14
+ schedule: vi.fn((_name: string, _expr: string, task: () => void) => {
15
+ task();
16
+ task();
17
+ return { stop };
18
+ }),
19
+ stop: vi.fn(),
20
+ },
21
+ };
22
+ });
23
+
24
+ import { destroy, handlers, queue, schedule, table } from "@/modules/app/controllers/demo.controller";
25
+
26
+ describe("app demo.controller", () => {
27
+ afterEach(() => {
28
+ vi.useRealTimers();
29
+ });
30
+
31
+ it("exposes handlers", () => {
32
+ expect(handlers.queue).toBe(queue);
33
+ expect(handlers.schedule).toBe(schedule);
34
+ expect(handlers.table).toBe(table);
35
+ expect(handlers.destroy).toBe(destroy);
36
+ });
37
+
38
+ it("queue runs items via facade queue and returns stats", async () => {
39
+ const res = await queue({ items: ["x", "y"], concurrency: 2, delayMs: 0 });
40
+ expect(res.ok).toBe(true);
41
+ expect(res.concurrency).toBe(2);
42
+ expect(res.results).toEqual(["processed x", "processed y"]);
43
+ expect(typeof res.durationMs).toBe("number");
44
+ });
45
+
46
+ it("schedule uses cron and resolves after duration", async () => {
47
+ vi.useFakeTimers();
48
+ const p = schedule({ seconds: 1 });
49
+ await vi.advanceTimersByTimeAsync(1100);
50
+ const res = await p;
51
+ expect(res.ok).toBe(true);
52
+ expect(res.name).toBe("demo.tick");
53
+ expect(res.seconds).toBe(1);
54
+ expect((res.ticked as number) >= 1).toBe(true);
55
+ expect(stop).toHaveBeenCalled();
56
+ });
57
+
58
+ it("table paginates/searches in-memory rows and destroy removes", () => {
59
+ const page = table({ page: 1, size: 5 }) as any;
60
+ expect(page.data).toHaveLength(5);
61
+ expect(page.current_page).toBe(1);
62
+ expect(page.per_page).toBe(5);
63
+ expect(page.path).toBe("app.demo.table");
64
+
65
+ const filtered = table({ search: "admin", size: 100 }) as any;
66
+ expect(filtered.data.every((r: any) => r.role === "admin")).toBe(true);
67
+
68
+ const firstId = filtered.data[0]?.id;
69
+ if (firstId != null) {
70
+ const res = destroy({ ids: [firstId] }) as any;
71
+ expect(res.ok).toBe(true);
72
+ expect(res.removed).toBeGreaterThanOrEqual(0);
73
+ }
74
+ });
75
+ });
@@ -0,0 +1,65 @@
1
+ // ./src/modules/app/__tests__/net.controller.test.ts
2
+
3
+ import { afterEach, describe, expect, it, vi } from "vitest";
4
+ import { fetchJson, handlers, placeholder } from "@/modules/app/controllers/net.controller";
5
+
6
+ describe("app net.controller", () => {
7
+ const origFetch = globalThis.fetch;
8
+ afterEach(() => {
9
+ globalThis.fetch = origFetch;
10
+ vi.restoreAllMocks();
11
+ });
12
+
13
+ it("exposes handlers", () => {
14
+ expect(handlers.fetchJson).toBe(fetchJson);
15
+ expect(handlers.placeholder).toBe(placeholder);
16
+ });
17
+
18
+ it("rejects invalid urls", async () => {
19
+ expect(await fetchJson("")).toMatchObject({ ok: false });
20
+ expect(await fetchJson("ftp://x")).toMatchObject({ ok: false });
21
+ expect(await fetchJson(undefined)).toMatchObject({ ok: false });
22
+ });
23
+
24
+ it("fetchJson returns parsed json on success", async () => {
25
+ globalThis.fetch = vi.fn(async () => ({
26
+ ok: true,
27
+ status: 200,
28
+ headers: new Headers({ "content-type": "application/json" }),
29
+ json: async () => ({ a: 1 }),
30
+ text: async () => '{"a":1}',
31
+ })) as any;
32
+ const res = await fetchJson("https://example.com/api");
33
+ expect(res.ok).toBe(true);
34
+ expect(res.status).toBe(200);
35
+ expect(res.data).toEqual({ a: 1 });
36
+ });
37
+
38
+ it("fetchJson handles non-ok and fetch errors", async () => {
39
+ globalThis.fetch = vi.fn(async () => ({
40
+ ok: false,
41
+ status: 500,
42
+ headers: new Headers({ "content-type": "text/plain" }),
43
+ text: async () => "boom",
44
+ })) as any;
45
+ expect(await fetchJson("https://example.com/x")).toMatchObject({ ok: false, status: 500 });
46
+
47
+ globalThis.fetch = vi.fn(async () => {
48
+ throw new Error("network");
49
+ }) as any;
50
+ expect(await fetchJson("https://example.com/x")).toMatchObject({ ok: false, error: expect.stringContaining("network") });
51
+ });
52
+
53
+ it("placeholder proxies the jsonplaceholder endpoint", async () => {
54
+ globalThis.fetch = vi.fn(async (url: string) => ({
55
+ ok: true,
56
+ status: 200,
57
+ headers: new Headers({ "content-type": "application/json" }),
58
+ json: async () => ({ title: "x", url }),
59
+ text: async () => "{}",
60
+ })) as any;
61
+ const res = await placeholder();
62
+ expect(res.ok).toBe(true);
63
+ expect(globalThis.fetch).toHaveBeenCalled();
64
+ });
65
+ });
@@ -0,0 +1,50 @@
1
+ // ./src/modules/app/__tests__/playwright.controller.test.ts
2
+
3
+ import { describe, expect, it, vi } from "vitest";
4
+
5
+ const page = { goto: vi.fn(async () => undefined), title: vi.fn(async () => "Example") };
6
+ const browser = { newPage: vi.fn(async () => page), pages: vi.fn(async () => [page]), close: vi.fn(async () => undefined) };
7
+ const chromium = {
8
+ executablePath: () => "C:/chrome.exe",
9
+ launch: vi.fn(async () => browser),
10
+ launchPersistentContext: vi.fn(async () => browser),
11
+ };
12
+
13
+ vi.mock("playwright", () => ({ chromium }));
14
+ vi.mock("@/core/facade", () => ({
15
+ chromium: {
16
+ resolve: () => undefined,
17
+ extensions: () => [],
18
+ exists: () => false,
19
+ },
20
+ }));
21
+ vi.mock("@/core/utils/playwright", () => ({
22
+ ensurePlaywrightBrowser: vi.fn(async () => undefined),
23
+ existsPath: () => true,
24
+ }));
25
+ vi.mock("node:fs/promises", () => ({ mkdtemp: vi.fn(async () => "/tmp/pw") }));
26
+
27
+ import { handlers, play } from "@/modules/app/controllers/playwright.controller";
28
+
29
+ describe("app playwright.controller", () => {
30
+ it("exposes handlers", () => {
31
+ expect(handlers.play).toBe(play);
32
+ });
33
+
34
+ it("launches chromium and returns page info", async () => {
35
+ const res = await play({ url: "https://example.com", seconds: 1, headless: true });
36
+ expect(res.ok).toBe(true);
37
+ expect(res.title).toBe("Example");
38
+ expect(res.chromium).toBe("playwright-registry");
39
+ expect(browser.close).toHaveBeenCalled();
40
+ });
41
+
42
+ it("returns error when playwright is unavailable", async () => {
43
+ // Re-mocking dynamic import failure is tricky in same module context; verify
44
+ // the handler shape at minimum and that errors are caught in normal flow.
45
+ chromium.launch.mockRejectedValueOnce(new Error("launch failed"));
46
+ const res = await play({ seconds: 1 });
47
+ expect(res.ok).toBe(false);
48
+ expect(String(res.error)).toContain("launch failed");
49
+ });
50
+ });