@niyamulahsan/create-deskapp 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +33 -2
  2. package/bin/create.js +136 -0
  3. package/package.json +14 -4
  4. package/template/.env +13 -0
  5. package/template/.env.example +13 -0
  6. package/template/.vscode/extensions.json +6 -0
  7. package/template/.vscode/settings.json +37 -0
  8. package/template/LICENSE +21 -0
  9. package/template/README.md +29 -0
  10. package/template/biome.json +99 -0
  11. package/template/drizzle.config.ts +32 -0
  12. package/template/gitignore-stub +19 -0
  13. package/template/package.json +111 -0
  14. package/template/scripts/build-electron.mjs +55 -0
  15. package/template/scripts/dev-electron.mjs +53 -0
  16. package/template/scripts/installer.nsh +14 -0
  17. package/template/src/config/app.ts +24 -0
  18. package/template/src/core/api/bindings.generated.ts +23 -0
  19. package/template/src/core/api/generate.manifest.ts +86 -0
  20. package/template/src/core/api/registry.ts +48 -0
  21. package/template/src/core/config.ts +99 -0
  22. package/template/src/core/database/aggregate.ts +85 -0
  23. package/template/src/core/database/config.ts +48 -0
  24. package/template/src/core/database/connection.ts +114 -0
  25. package/template/src/core/database/migrate-hooks.ts +84 -0
  26. package/template/src/core/database/paginate.ts +224 -0
  27. package/template/src/core/database/reset.ts +19 -0
  28. package/template/src/core/database/seed.ts +169 -0
  29. package/template/src/core/database/status.ts +32 -0
  30. package/template/src/core/env.ts +106 -0
  31. package/template/src/core/facade.ts +59 -0
  32. package/template/src/core/maker/db/fresh.ts +8 -0
  33. package/template/src/core/maker/db/generate.ts +11 -0
  34. package/template/src/core/maker/db/helpers.ts +96 -0
  35. package/template/src/core/maker/db/migrate.ts +36 -0
  36. package/template/src/core/maker/db/mod.ts +63 -0
  37. package/template/src/core/maker/db/module-migrate.ts +53 -0
  38. package/template/src/core/maker/db/push.ts +21 -0
  39. package/template/src/core/maker/db/reset.ts +6 -0
  40. package/template/src/core/maker/db/seed.ts +7 -0
  41. package/template/src/core/maker/db/status.ts +6 -0
  42. package/template/src/core/maker/help.ts +66 -0
  43. package/template/src/core/maker/make/controller.ts +27 -0
  44. package/template/src/core/maker/make/helpers.ts +93 -0
  45. package/template/src/core/maker/make/mod.ts +68 -0
  46. package/template/src/core/maker/make/model.ts +14 -0
  47. package/template/src/core/maker/make/module.ts +62 -0
  48. package/template/src/core/maker/make/seeder.ts +21 -0
  49. package/template/src/core/maker/make/test.ts +30 -0
  50. package/template/src/core/maker/mod.ts +83 -0
  51. package/template/src/core/maker/run/mod.ts +112 -0
  52. package/template/src/core/maker/stub.ts +24 -0
  53. package/template/src/core/maker/stubs/controller/controller.controller.stub +55 -0
  54. package/template/src/core/maker/stubs/controller/controller.schema.stub +13 -0
  55. package/template/src/core/maker/stubs/model/model.stub +8 -0
  56. package/template/src/core/maker/stubs/seeder/seeder.stub +16 -0
  57. package/template/src/core/maker/stubs/test/test.stub +7 -0
  58. package/template/src/core/maker/sync-config.ts +94 -0
  59. package/template/src/core/utils/password.ts +27 -0
  60. package/template/src/core/utils/playwright.ts +121 -0
  61. package/template/src/core/utils/queue.ts +59 -0
  62. package/template/src/core/utils/scheduler.ts +70 -0
  63. package/template/src/core/utils/storage.ts +599 -0
  64. package/template/src/core/utils/validation.ts +35 -0
  65. package/template/src/database/migrations/sqlite/meta/_journal.json +1 -0
  66. package/template/src/database/schema.ts +6 -0
  67. package/template/src/icons/apple-touch-icon.png +0 -0
  68. package/template/src/icons/deskapp.png +0 -0
  69. package/template/src/icons/favicon-96x96.png +0 -0
  70. package/template/src/icons/favicon.ico +0 -0
  71. package/template/src/icons/favicon.svg +1 -0
  72. package/template/src/icons/site.webmanifest +21 -0
  73. package/template/src/icons/tray.png +0 -0
  74. package/template/src/icons/web-app-manifest-192x192.png +0 -0
  75. package/template/src/icons/web-app-manifest-512x512.png +0 -0
  76. package/template/src/main.ts +116 -0
  77. package/template/src/modules/app/controllers/demo.controller.ts +118 -0
  78. package/template/src/modules/app/controllers/net.controller.ts +48 -0
  79. package/template/src/modules/app/controllers/playwright.controller.ts +140 -0
  80. package/template/src/modules/app/controllers/storage.controller.ts +229 -0
  81. package/template/src/modules/app/controllers/window.controller.ts +107 -0
  82. package/template/src/preload.ts +35 -0
  83. package/template/src/storage/.gitkeep +1 -0
  84. package/template/src/storage/app/private/.gitkeep +1 -0
  85. package/template/src/storage/app/private/samples/.gitkeep +1 -0
  86. package/template/src/storage/app/private/samples/state.json +5 -0
  87. package/template/src/storage/app/private/uploads/.gitkeep +1 -0
  88. package/template/src/storage/app/public/.gitkeep +1 -0
  89. package/template/src/storage/app/tmp/generated/.gitkeep +1 -0
  90. package/template/src/storage/logs/.gitkeep +0 -0
  91. package/template/src/storage/logs/app.log +0 -0
  92. package/template/src/storage/logs/fatal.log +0 -0
  93. package/template/src/ui/.vscode/extensions.json +3 -0
  94. package/template/src/ui/index.html +14 -0
  95. package/template/src/ui/public/icons.svg +24 -0
  96. package/template/src/ui/src/App.vue +3 -0
  97. package/template/src/ui/src/app.ts +23 -0
  98. package/template/src/ui/src/assets/fonts/public-sans/public-sans-latin-ext.woff2 +0 -0
  99. package/template/src/ui/src/assets/fonts/public-sans/public-sans-latin.woff2 +0 -0
  100. package/template/src/ui/src/assets/images/deskapp.png +0 -0
  101. package/template/src/ui/src/assets/images/favicon/favicon.ico +0 -0
  102. package/template/src/ui/src/assets/scss/custom.scss +186 -0
  103. package/template/src/ui/src/bindings.d.ts +16 -0
  104. package/template/src/ui/src/components/Button.vue +32 -0
  105. package/template/src/ui/src/components/Checkbox.vue +29 -0
  106. package/template/src/ui/src/components/Input.vue +227 -0
  107. package/template/src/ui/src/components/Modal.vue +55 -0
  108. package/template/src/ui/src/components/Spinner.vue +42 -0
  109. package/template/src/ui/src/components/Switch.vue +65 -0
  110. package/template/src/ui/src/components/TextArea.vue +121 -0
  111. package/template/src/ui/src/components/Toast.vue +56 -0
  112. package/template/src/ui/src/components/datatable/DataTableSkeleton.vue +98 -0
  113. package/template/src/ui/src/components/datatable/Pagination.vue +125 -0
  114. package/template/src/ui/src/components/datatable/SelectOpption.vue +35 -0
  115. package/template/src/ui/src/components/datatable/index.vue +258 -0
  116. package/template/src/ui/src/env.d.ts +13 -0
  117. package/template/src/ui/src/global.d.ts +35 -0
  118. package/template/src/ui/src/helpers/nformatter.ts +10 -0
  119. package/template/src/ui/src/pages/dashboard/index.vue +687 -0
  120. package/template/src/ui/src/plugins/gum.ts +549 -0
  121. package/template/src/ui/src/plugins/gum.ts.bak +683 -0
  122. package/template/src/ui/src/plugins/pulse.ts +148 -0
  123. package/template/src/ui/src/router/index.ts +25 -0
  124. package/template/src/ui/src/stores/example.ts +27 -0
  125. package/template/src/ui/tsconfig.json +15 -0
  126. package/template/src/ui/vite.config.ts +38 -0
  127. package/template/src/window/config.ts +71 -0
  128. package/template/src/window/dialogs.ts +67 -0
  129. package/template/src/window/manager.ts +139 -0
  130. package/template/src/window/native.ts +215 -0
  131. package/template/tsconfig.json +22 -0
  132. package/template/vitest.config.ts +34 -0
@@ -0,0 +1,70 @@
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(
27
+ name: string,
28
+ expression: string,
29
+ task: () => void | Promise<void>,
30
+ options?: { timezone?: string; },
31
+ ): CronHandle {
32
+ return scheduleCron(name, expression, task, options);
33
+ },
34
+
35
+ /** Stop every scheduled job (call on app shutdown). */
36
+ stop(): void {
37
+ stopSchedules();
38
+ },
39
+ };
40
+
41
+ function scheduleCron(
42
+ name: string,
43
+ expression: string,
44
+ task: () => void | Promise<void>,
45
+ options?: { timezone?: string; },
46
+ ): CronHandle {
47
+ jobs.get(name)?.stop();
48
+ const job = new Cron(
49
+ expression,
50
+ {
51
+ timezone: options?.timezone,
52
+ catch: (error: unknown) => console.error(`[scheduler] "${name}" run failed:`, error),
53
+ },
54
+ () => {
55
+ void task();
56
+ },
57
+ );
58
+ jobs.set(name, job);
59
+ return {
60
+ stop() {
61
+ job.stop();
62
+ jobs.delete(name);
63
+ },
64
+ };
65
+ }
66
+
67
+ function stopSchedules(): void {
68
+ for (const job of jobs.values()) job.stop();
69
+ jobs.clear();
70
+ }
@@ -0,0 +1,599 @@
1
+ import fs from "node:fs/promises";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { createRequire } from "node:module";
5
+ import { appBaseDir } from "@/core/env";
6
+
7
+ function getElectronApp(): { getPath: (name: string) => string; isPackaged: boolean } | undefined {
8
+ try {
9
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
10
+ const e = (typeof require !== "undefined" ? require : createRequire(process.cwd() + "/"))("electron") as any;
11
+ if (e && typeof e.app?.getPath === "function") return e.app;
12
+ } catch {}
13
+ return undefined;
14
+ }
15
+
16
+ type Disk = "private" | "tmp";
17
+ type FileData = string | Uint8Array | ArrayBuffer | Blob | File;
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // 1) USER-FILE LAYER
21
+ // ---------------------------------------------------------------------------
22
+
23
+ async function ensureDir(path: string): Promise<void> {
24
+ await fs.mkdir(path, { recursive: true });
25
+ }
26
+
27
+ async function pathExists(path: string): Promise<boolean> {
28
+ try {
29
+ await fs.stat(path);
30
+ return true;
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+
36
+ async function isFile(path: string): Promise<boolean> {
37
+ try {
38
+ return (await fs.stat(path)).isFile();
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+
44
+ async function isDirectory(path: string): Promise<boolean> {
45
+ try {
46
+ return (await fs.stat(path)).isDirectory();
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+
52
+ async function fileMeta(path: string) {
53
+ try {
54
+ const info = await fs.stat(path);
55
+ return {
56
+ path,
57
+ size: info.size,
58
+ modifiedAt: info.mtime ?? new Date(0),
59
+ isFile: info.isFile(),
60
+ isDirectory: info.isDirectory()
61
+ };
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+
67
+ async function listFiles(path: string): Promise<string[]> {
68
+ const files: string[] = [];
69
+ try {
70
+ const entries = await fs.readdir(path, { withFileTypes: true });
71
+ for (const entry of entries) {
72
+ if (entry.isFile()) files.push(join(path, entry.name));
73
+ }
74
+ } catch {}
75
+ return files.sort();
76
+ }
77
+
78
+ async function listDirectories(path: string): Promise<string[]> {
79
+ const dirs: string[] = [];
80
+ try {
81
+ const entries = await fs.readdir(path, { withFileTypes: true });
82
+ for (const entry of entries) {
83
+ if (entry.isDirectory()) dirs.push(join(path, entry.name));
84
+ }
85
+ } catch {}
86
+ return dirs.sort();
87
+ }
88
+
89
+ function readTextFile(path: string): Promise<string> {
90
+ return fs.readFile(path, "utf-8");
91
+ }
92
+
93
+ async function readTextFileOr(path: string, fallback: string): Promise<string> {
94
+ try {
95
+ return await fs.readFile(path, "utf-8");
96
+ } catch {
97
+ return fallback;
98
+ }
99
+ }
100
+
101
+ function readBinaryFile(path: string): Promise<Buffer> {
102
+ return fs.readFile(path);
103
+ }
104
+
105
+ async function readJson<T>(path: string, fallback: T): Promise<T> {
106
+ try {
107
+ return JSON.parse(await fs.readFile(path, "utf-8")) as T;
108
+ } catch {
109
+ return fallback;
110
+ }
111
+ }
112
+
113
+ async function writeTextFile(path: string, data: string): Promise<void> {
114
+ await writeFileAtomic(path, data);
115
+ }
116
+
117
+ async function writeBinaryFile(path: string, data: Uint8Array): Promise<void> {
118
+ await writeFileAtomic(path, data);
119
+ }
120
+
121
+ async function writeFile(path: string, data: string | Uint8Array): Promise<void> {
122
+ await writeFileAtomic(path, data);
123
+ }
124
+
125
+ async function writeJson(path: string, value: unknown): Promise<void> {
126
+ await writeTextFile(path, `${JSON.stringify(value, null, 2)}\n`);
127
+ }
128
+
129
+ async function writeFileAtomic(path: string, data: string | Uint8Array): Promise<void> {
130
+ await ensureDir(dirname(path));
131
+ const tmp = `${path}.${crypto.randomUUID()}.tmp`;
132
+ try {
133
+ await fs.writeFile(tmp, data);
134
+ await renameReplacing(tmp, path);
135
+ } catch (error) {
136
+ await fs.unlink(tmp).catch(() => {});
137
+ throw error;
138
+ }
139
+ }
140
+
141
+ async function copyFile(from: string, to: string): Promise<void> {
142
+ await ensureDir(dirname(to));
143
+ await fs.copyFile(from, to);
144
+ }
145
+
146
+ async function moveFile(from: string, to: string): Promise<void> {
147
+ await ensureDir(dirname(to));
148
+ await renameReplacing(from, to);
149
+ }
150
+
151
+ async function removePath(path: string): Promise<void> {
152
+ try {
153
+ await fs.rm(path, { recursive: true, force: true });
154
+ } catch {}
155
+ }
156
+
157
+ async function uniquePath(dir: string, name: string): Promise<string> {
158
+ const candidate = join(dir, name);
159
+ if (!(await pathExists(candidate))) return candidate;
160
+ const ext = basename(name).match(/\.(.*)$/)?.[0] ?? "";
161
+ const stem = basename(name).slice(0, basename(name).length - ext.length);
162
+ for (let i = 1; ; i++) {
163
+ const next = join(dir, `${stem} (${i})${ext}`);
164
+ if (!(await pathExists(next))) return next;
165
+ }
166
+ }
167
+
168
+ async function uploadFile(source: string, destDir: string): Promise<string> {
169
+ await ensureDir(destDir);
170
+ const dest = await uniquePath(destDir, basename(source));
171
+ await fs.copyFile(source, dest);
172
+ return dest;
173
+ }
174
+
175
+ async function downloadFile(source: string, destPath: string): Promise<string> {
176
+ const src = normalizeSource(source);
177
+ await ensureDir(dirname(destPath));
178
+ const tmp = `${destPath}.${crypto.randomUUID()}.tmp`;
179
+ try {
180
+ if (src.kind === "network") {
181
+ const res = await fetch(src.value);
182
+ if (!res.ok) throw new Error(`Download failed: ${res.status} ${res.statusText}`);
183
+ const arrayBuffer = await res.arrayBuffer();
184
+ await fs.writeFile(tmp, Buffer.from(arrayBuffer));
185
+ } else {
186
+ await fs.copyFile(src.value, tmp);
187
+ }
188
+ await renameReplacing(tmp, destPath);
189
+ } catch (error) {
190
+ await fs.unlink(tmp).catch(() => {});
191
+ throw error;
192
+ }
193
+ return destPath;
194
+ }
195
+
196
+ type LocalSource = { kind: "network"; value: string } | { kind: "file"; value: string };
197
+
198
+ function normalizeSource(source: string): LocalSource {
199
+ const trimmed = source.trim();
200
+ if (/^[a-zA-Z]:[\\/]/.test(trimmed)) return { kind: "file", value: trimmed };
201
+ const scheme = trimmed.match(/^([a-z][a-z0-9+.-]*):/i)?.[1]?.toLowerCase();
202
+ if (scheme === "http" || scheme === "https") return { kind: "network", value: trimmed };
203
+ if (scheme === "file") {
204
+ return { kind: "file", value: new URL(trimmed).pathname };
205
+ }
206
+ if (scheme === undefined) return { kind: "file", value: trimmed };
207
+ throw new Error(`Url scheme '${scheme}' not supported`);
208
+ }
209
+
210
+ async function renameReplacing(from: string, to: string): Promise<void> {
211
+ try {
212
+ await fs.rename(from, to);
213
+ } catch {
214
+ await fs.unlink(to).catch(() => {});
215
+ await fs.rename(from, to);
216
+ }
217
+ }
218
+
219
+ export const files = {
220
+ ensureDir,
221
+ pathExists,
222
+ isFile,
223
+ isDirectory,
224
+ fileMeta,
225
+ listFiles,
226
+ listDirectories,
227
+ readTextFile,
228
+ readTextFileOr,
229
+ readBinaryFile,
230
+ readJson,
231
+ writeTextFile,
232
+ writeBinaryFile,
233
+ writeFile,
234
+ writeJson,
235
+ copyFile,
236
+ moveFile,
237
+ removePath,
238
+ uniquePath,
239
+ uploadFile,
240
+ downloadFile
241
+ };
242
+
243
+ // ---------------------------------------------------------------------------
244
+ // 2) APP-MANAGED LAYER
245
+ // ---------------------------------------------------------------------------
246
+
247
+ const driver = "local";
248
+ const defaultDisk: Disk = "private";
249
+
250
+ let appRootCache: string | null = null;
251
+ function appRoot(): string {
252
+ if (appRootCache) return appRootCache;
253
+ if (process.env.APP_DATA_DIR) {
254
+ appRootCache = resolve(process.env.APP_DATA_DIR);
255
+ return appRootCache;
256
+ }
257
+ const electronApp = getElectronApp();
258
+ if (electronApp) {
259
+ // Writable per-user data dir (works in dev and packaged installs, incl. Program Files).
260
+ appRootCache = join(electronApp.getPath("userData"), "storage");
261
+ return appRootCache;
262
+ }
263
+ // CLI/dev fallback: project-local storage.
264
+ appRootCache = join(appBaseDir(), "src", "storage", "app");
265
+ return appRootCache;
266
+ }
267
+
268
+ const disks: Record<Disk, () => string> = {
269
+ private: () => join(appRoot(), "private"),
270
+ tmp: () => join(appRoot(), "tmp")
271
+ };
272
+
273
+ function clean(input: string): string {
274
+ const value = input.replace(/\\/g, "/").replace(/^\/+/, "");
275
+ if (!value || value.includes("..")) throw new Error("Invalid storage path");
276
+ return value;
277
+ }
278
+
279
+ function diskAbs(disk: Disk, file: string): string {
280
+ return join(disks[disk](), clean(file));
281
+ }
282
+
283
+ async function diskToBuffer(data: FileData): Promise<Buffer> {
284
+ if (typeof data === "string") return Buffer.from(data);
285
+ if (data instanceof Uint8Array) return Buffer.from(data);
286
+ if (data instanceof ArrayBuffer) return Buffer.from(data);
287
+ if (data instanceof Blob) return Buffer.from(await data.arrayBuffer());
288
+ return Buffer.from([]);
289
+ }
290
+
291
+ async function diskPut(disk: Disk, file: string, data: FileData): Promise<string> {
292
+ const filePath = diskAbs(disk, file);
293
+ await fs.mkdir(dirname(filePath), { recursive: true });
294
+ await fs.writeFile(filePath, await diskToBuffer(data));
295
+ return clean(file);
296
+ }
297
+
298
+ async function diskPutFile(disk: Disk, directory: string, file: File, name?: string): Promise<string> {
299
+ const finalName = name || `${Date.now()}-${crypto.randomUUID()}-${file.name}`;
300
+ return await diskPut(disk, join(clean(directory), finalName), file);
301
+ }
302
+
303
+ async function diskWriteGeneratedTemp(prefix: string, extension: string, data: FileData): Promise<string> {
304
+ const safePrefix = clean(prefix).replace(/\//g, "-");
305
+ const safeExtension = extension.replace(/[^a-zA-Z0-9]/g, "").toLowerCase() || "tmp";
306
+ const fileName = `${Date.now()}-${crypto.randomUUID()}-${safePrefix}.${safeExtension}`;
307
+ const file = join("generated", fileName);
308
+ await diskPut("tmp", file, data);
309
+ return file;
310
+ }
311
+
312
+ async function diskConsumeGeneratedTemp(file: string): Promise<Buffer> {
313
+ const target = diskAbs("tmp", clean(file));
314
+ const content = await fs.readFile(target);
315
+ try {
316
+ await fs.unlink(target);
317
+ } catch {}
318
+ return content;
319
+ }
320
+
321
+ async function diskExists(disk: Disk, file: string): Promise<boolean> {
322
+ try {
323
+ await fs.stat(diskAbs(disk, file));
324
+ return true;
325
+ } catch {
326
+ return false;
327
+ }
328
+ }
329
+
330
+ async function diskRemove(disk: Disk, file: string): Promise<void> {
331
+ try {
332
+ await fs.unlink(diskAbs(disk, file));
333
+ } catch {}
334
+ }
335
+
336
+ function diskRead(disk: Disk, file: string): Promise<Buffer> {
337
+ return fs.readFile(diskAbs(disk, file));
338
+ }
339
+
340
+ async function diskCopy(disk: Disk, from: string, to: string): Promise<string> {
341
+ await fs.mkdir(dirname(diskAbs(disk, to)), { recursive: true });
342
+ await fs.copyFile(diskAbs(disk, from), diskAbs(disk, to));
343
+ return clean(to);
344
+ }
345
+
346
+ async function diskMove(disk: Disk, from: string, to: string): Promise<string> {
347
+ await fs.mkdir(dirname(diskAbs(disk, to)), { recursive: true });
348
+ await fs.rename(diskAbs(disk, from), diskAbs(disk, to));
349
+ return clean(to);
350
+ }
351
+
352
+ async function diskMetadata(disk: Disk, file: string) {
353
+ const stat = await fs.stat(diskAbs(disk, file));
354
+ return {
355
+ size: stat.size,
356
+ mimeType: "application/octet-stream",
357
+ lastModified: stat.mtime.getTime()
358
+ };
359
+ }
360
+
361
+ function diskFileUrl(disk: Disk, file: string): string {
362
+ return pathToFileURL(diskAbs(disk, file)).href;
363
+ }
364
+
365
+ async function diskReadStream(disk: Disk, file: string): Promise<ReadableStream<Uint8Array>> {
366
+ const bytes = await fs.readFile(diskAbs(disk, file));
367
+ return new ReadableStream({
368
+ start(controller) {
369
+ controller.enqueue(new Uint8Array(bytes));
370
+ controller.close();
371
+ }
372
+ });
373
+ }
374
+
375
+ async function diskWriteStream(disk: Disk, file: string, stream: ReadableStream<Uint8Array>): Promise<string> {
376
+ const reader = stream.getReader();
377
+ const chunks: Uint8Array[] = [];
378
+
379
+ while (true) {
380
+ const { done, value } = await reader.read();
381
+ if (done) break;
382
+ if (value) chunks.push(value);
383
+ }
384
+
385
+ const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
386
+ const out = new Uint8Array(total);
387
+ let offset = 0;
388
+ for (const chunk of chunks) {
389
+ out.set(chunk, offset);
390
+ offset += chunk.length;
391
+ }
392
+ return await diskPut(disk, file, out);
393
+ }
394
+
395
+ async function diskMakeDirectory(disk: Disk, directory: string): Promise<string> {
396
+ const dir = clean(directory);
397
+ await fs.mkdir(diskAbs(disk, dir), { recursive: true });
398
+ return dir;
399
+ }
400
+
401
+ async function diskDeleteDirectory(disk: Disk, directory: string): Promise<void> {
402
+ try {
403
+ await fs.rm(diskAbs(disk, directory), { recursive: true, force: true });
404
+ } catch {}
405
+ }
406
+
407
+ async function diskListFiles(disk: Disk, directory = ""): Promise<string[]> {
408
+ const dir = clean(directory || "root").replace(/^root$/, "");
409
+ const files: string[] = [];
410
+ try {
411
+ const entries = await fs.readdir(diskAbs(disk, dir || "."), { withFileTypes: true });
412
+ for (const entry of entries) {
413
+ if (entry.isFile()) files.push(dir ? `${dir}/${entry.name}` : entry.name);
414
+ }
415
+ } catch {}
416
+ return files;
417
+ }
418
+
419
+ async function diskListDirectories(disk: Disk, directory = ""): Promise<string[]> {
420
+ const dir = directory.trim() ? clean(directory) : "";
421
+ const dirs: string[] = [];
422
+ try {
423
+ const entries = await fs.readdir(diskAbs(disk, dir || "."), { withFileTypes: true });
424
+ for (const entry of entries) {
425
+ if (entry.isDirectory()) dirs.push(dir ? `${dir}/${entry.name}` : entry.name);
426
+ }
427
+ } catch {}
428
+ return dirs;
429
+ }
430
+
431
+ export interface StorageDisk {
432
+ put(file: string, data: FileData): Promise<string>;
433
+ putFile(directory: string, file: File, name?: string): Promise<string>;
434
+ get(file: string): Promise<Buffer>;
435
+ delete(file: string): Promise<void>;
436
+ copy(from: string, to: string): Promise<string>;
437
+ move(from: string, to: string): Promise<string>;
438
+ exists(file: string): Promise<boolean>;
439
+ missing(file: string): Promise<boolean>;
440
+ size(file: string): Promise<number>;
441
+ mimeType(file: string): Promise<string>;
442
+ lastModified(file: string): Promise<number>;
443
+ files(directory?: string): Promise<string[]>;
444
+ directories(directory?: string): Promise<string[]>;
445
+ makeDirectory(directory: string): Promise<string>;
446
+ deleteDirectory(directory: string): Promise<void>;
447
+ readStream(file: string): Promise<ReadableStream<Uint8Array>>;
448
+ writeStream(file: string, stream: ReadableStream<Uint8Array>): Promise<string>;
449
+ temporaryUrl(file: string): string;
450
+ path(file: string): string;
451
+ url(file: string): string;
452
+ }
453
+
454
+ function disk(disk: Disk): StorageDisk {
455
+ return {
456
+ put: (file: string, data: FileData) => diskPut(disk, file, data),
457
+ putFile: (directory: string, file: File, name?: string) => diskPutFile(disk, directory, file, name),
458
+ get: (file: string) => diskRead(disk, file),
459
+ delete: (file: string) => diskRemove(disk, file),
460
+ copy: (from: string, to: string) => diskCopy(disk, from, to),
461
+ move: (from: string, to: string) => diskMove(disk, from, to),
462
+ exists: (file: string) => diskExists(disk, file),
463
+ missing: async (file: string) => !(await diskExists(disk, file)),
464
+ size: async (file: string) => (await diskMetadata(disk, file)).size,
465
+ mimeType: async (file: string) => (await diskMetadata(disk, file)).mimeType,
466
+ lastModified: async (file: string) => (await diskMetadata(disk, file)).lastModified,
467
+ files: (directory = "") => diskListFiles(disk, directory),
468
+ directories: (directory = "") => diskListDirectories(disk, directory),
469
+ makeDirectory: (directory: string) => diskMakeDirectory(disk, directory),
470
+ deleteDirectory: (directory: string) => diskDeleteDirectory(disk, directory),
471
+ readStream: (file: string) => diskReadStream(disk, file),
472
+ writeStream: (file: string, stream: ReadableStream<Uint8Array>) => diskWriteStream(disk, file, stream),
473
+ temporaryUrl: (file: string) => diskFileUrl(disk, file),
474
+ path: (file: string) => diskAbs(disk, file),
475
+ url: (file: string) => diskFileUrl(disk, file)
476
+ };
477
+ }
478
+
479
+ export interface StorageFacade {
480
+ init(): Promise<void>;
481
+ driver: string;
482
+ defaultDisk: Disk;
483
+ disk(disk: Disk): StorageDisk;
484
+ put(file: string, data: FileData): Promise<string>;
485
+ putFile(directory: string, file: File, name?: string): Promise<string>;
486
+ get(file: string): Promise<Buffer>;
487
+ delete(file: string): Promise<void>;
488
+ copy(from: string, to: string): Promise<string>;
489
+ move(from: string, to: string): Promise<string>;
490
+ exists(file: string): Promise<boolean>;
491
+ missing(file: string): Promise<boolean>;
492
+ size(file: string): Promise<number>;
493
+ mime(file: string): Promise<string>;
494
+ mimeType(file: string): Promise<string>;
495
+ lastModified(file: string): Promise<number>;
496
+ files(directory?: string): Promise<string[]>;
497
+ directories(directory?: string): Promise<string[]>;
498
+ makeDirectory(directory: string): Promise<string>;
499
+ deleteDirectory(directory: string): Promise<void>;
500
+ readStream(file: string): Promise<ReadableStream<Uint8Array>>;
501
+ writeStream(file: string, stream: ReadableStream<Uint8Array>): Promise<string>;
502
+ url(file: string): string;
503
+ temporaryUrl(file: string): string;
504
+ download(c: unknown, file: string, filename?: string): Promise<Response>;
505
+ generateForDownload(options: { prefix: string; extension: string; data: FileData }): Promise<string>;
506
+ consumeGenerated(file: string): Promise<Buffer>;
507
+ }
508
+
509
+ export const storage: StorageFacade = {
510
+ async init() {
511
+ await Promise.all(["private", "tmp"].map((d) => fs.mkdir(disks[d as Disk](), { recursive: true })));
512
+ },
513
+
514
+ driver,
515
+ defaultDisk,
516
+ disk,
517
+
518
+ put(file: string, data: FileData) {
519
+ return storage.disk(defaultDisk).put(file, data);
520
+ },
521
+ putFile(directory: string, file: File, name?: string) {
522
+ return storage.disk(defaultDisk).putFile(directory, file, name);
523
+ },
524
+ get(file: string) {
525
+ return storage.disk(defaultDisk).get(file);
526
+ },
527
+ delete(file: string) {
528
+ return storage.disk(defaultDisk).delete(file);
529
+ },
530
+ copy(from: string, to: string) {
531
+ return storage.disk(defaultDisk).copy(from, to);
532
+ },
533
+ move(from: string, to: string) {
534
+ return storage.disk(defaultDisk).move(from, to);
535
+ },
536
+ exists(file: string) {
537
+ return storage.disk(defaultDisk).exists(file);
538
+ },
539
+ missing(file: string) {
540
+ return storage.disk(defaultDisk).missing(file);
541
+ },
542
+ size(file: string) {
543
+ return storage.disk(defaultDisk).size(file);
544
+ },
545
+ mime(file: string) {
546
+ return storage.disk(defaultDisk).mimeType(file);
547
+ },
548
+ mimeType(file: string) {
549
+ return storage.disk(defaultDisk).mimeType(file);
550
+ },
551
+ lastModified(file: string) {
552
+ return storage.disk(defaultDisk).lastModified(file);
553
+ },
554
+ files(directory = "") {
555
+ return storage.disk(defaultDisk).files(directory);
556
+ },
557
+ directories(directory = "") {
558
+ return storage.disk(defaultDisk).directories(directory);
559
+ },
560
+ makeDirectory(directory: string) {
561
+ return storage.disk(defaultDisk).makeDirectory(directory);
562
+ },
563
+ deleteDirectory(directory: string) {
564
+ return storage.disk(defaultDisk).deleteDirectory(directory);
565
+ },
566
+ readStream(file: string) {
567
+ return storage.disk(defaultDisk).readStream(file);
568
+ },
569
+ writeStream(file: string, stream: ReadableStream<Uint8Array>) {
570
+ return storage.disk(defaultDisk).writeStream(file, stream);
571
+ },
572
+ url(file: string) {
573
+ return storage.disk(defaultDisk).url(file);
574
+ },
575
+ temporaryUrl(file: string) {
576
+ return storage.disk(defaultDisk).temporaryUrl(file);
577
+ },
578
+
579
+ async download(_c: unknown, file: string, filename?: string) {
580
+ const bytes = await diskRead(defaultDisk, file);
581
+ return new Response(new Uint8Array(bytes), {
582
+ status: 200,
583
+ headers: {
584
+ "content-type": "application/octet-stream",
585
+ "content-disposition": `attachment; filename=${filename || clean(file).split("/").pop()}`
586
+ }
587
+ });
588
+ },
589
+
590
+ async generateForDownload(options: { prefix: string; extension: string; data: FileData }) {
591
+ return await diskWriteGeneratedTemp(options.prefix, options.extension, options.data);
592
+ },
593
+
594
+ async consumeGenerated(file: string) {
595
+ return await diskConsumeGeneratedTemp(file);
596
+ }
597
+ };
598
+
599
+ export type { Disk, FileData };
@@ -0,0 +1,35 @@
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
+ };
@@ -0,0 +1 @@
1
+ {"version":"7","dialect":"sqlite","entries":[]}