kreftjs 0.0.0-stage → 0.0.2-beta
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.
- package/README.md +103 -2
- package/bin/add.js +1074 -0
- package/bin/artisan-more.js +994 -0
- package/bin/artisan.js +1877 -0
- package/bin/backend/app.js +161 -0
- package/bin/backend/cache.js +196 -0
- package/bin/backend/collection.js +117 -0
- package/bin/backend/command.js +45 -0
- package/bin/backend/config.js +234 -0
- package/bin/backend/error-page.js +773 -0
- package/bin/backend/events.js +49 -0
- package/bin/backend/factory.js +223 -0
- package/bin/backend/fake.js +180 -0
- package/bin/backend/form.js +102 -0
- package/bin/backend/gate.js +79 -0
- package/bin/backend/gc.js +69 -0
- package/bin/backend/html.js +322 -0
- package/bin/backend/http.js +652 -0
- package/bin/backend/index.js +452 -0
- package/bin/backend/mail.js +77 -0
- package/bin/backend/mcp.js +433 -0
- package/bin/backend/migrator.js +370 -0
- package/bin/backend/model.js +781 -0
- package/bin/backend/namespace.js +213 -0
- package/bin/backend/notifications.js +68 -0
- package/bin/backend/qr.js +164 -0
- package/bin/backend/query.js +387 -0
- package/bin/backend/queue.js +412 -0
- package/bin/backend/redis.js +479 -0
- package/bin/backend/schedule.js +112 -0
- package/bin/backend/schema.js +321 -0
- package/bin/backend/seo-pages.js +100 -0
- package/bin/backend/storage.js +153 -0
- package/bin/backend/support.js +567 -0
- package/bin/backend/typescript.js +166 -0
- package/bin/build.js +540 -0
- package/bin/db-api.js +249 -0
- package/bin/db.js +275 -0
- package/bin/deps.js +138 -0
- package/bin/electron.js +509 -0
- package/bin/env.js +97 -0
- package/bin/guard.js +80 -0
- package/bin/kreftjs-config.js +40 -0
- package/bin/kreftjs.js +1373 -0
- package/bin/lang.js +241 -0
- package/bin/layout.js +74 -0
- package/bin/no-auth.js +162 -0
- package/bin/prerender.js +258 -0
- package/bin/safe-json.js +24 -0
- package/bin/server-routes.js +154 -0
- package/bin/ssr.js +133 -0
- package/bin/terminal.js +195 -0
- package/bin/to-ts.js +36 -0
- package/bin/update.js +237 -0
- package/bin/urls-file.js +27 -0
- package/bin/vite.js +228 -0
- package/docs/Docs.kreftjs +557 -0
- package/docs/README.md +2302 -0
- package/docs/markdown.js +186 -0
- package/editors/vscode/README.md +13 -0
- package/editors/vscode/extension.js +183 -0
- package/editors/vscode/language-configuration.json +17 -0
- package/editors/vscode/package.json +57 -0
- package/editors/vscode/snippets/kreftjs.json +21 -0
- package/editors/vscode/syntaxes/kreftjs.tmLanguage.json +207 -0
- package/kreftjs.d.ts +579 -0
- package/kreftjs.js +5108 -0
- package/package.json +97 -4
- package/server.d.ts +1028 -0
- package/server.js +8 -0
- package/templates/app/README.md +127 -0
- package/templates/app/_env.example +64 -0
- package/templates/app/_gitignore +5 -0
- package/templates/app/_vscode/settings.json +9 -0
- package/templates/app/backend/app/Auth/Session.js +177 -0
- package/templates/app/backend/app/Auth/Throttle.js +29 -0
- package/templates/app/backend/app/Console/Commands/.gitkeep +0 -0
- package/templates/app/backend/app/Events/.gitkeep +0 -0
- package/templates/app/backend/app/Http/Controllers/Admin/DashboardController.js +34 -0
- package/templates/app/backend/app/Http/Controllers/Admin/UserController.js +53 -0
- package/templates/app/backend/app/Http/Controllers/Auth/ApiTokenController.js +47 -0
- package/templates/app/backend/app/Http/Controllers/Auth/AuthenticatedSessionController.js +41 -0
- package/templates/app/backend/app/Http/Controllers/Auth/ConfirmablePasswordController.js +14 -0
- package/templates/app/backend/app/Http/Controllers/Auth/EmailVerificationController.js +23 -0
- package/templates/app/backend/app/Http/Controllers/Auth/NewPasswordController.js +29 -0
- package/templates/app/backend/app/Http/Controllers/Auth/PasswordResetLinkController.js +20 -0
- package/templates/app/backend/app/Http/Controllers/Auth/RegisteredUserController.js +19 -0
- package/templates/app/backend/app/Http/Controllers/Auth/SessionController.js +36 -0
- package/templates/app/backend/app/Http/Controllers/Auth/TwoFactorChallengeController.js +41 -0
- package/templates/app/backend/app/Http/Controllers/Auth/TwoFactorController.js +63 -0
- package/templates/app/backend/app/Http/Controllers/ProfileController.js +66 -0
- package/templates/app/backend/app/Http/Kernel.js +8 -0
- package/templates/app/backend/app/Http/Middleware/Authenticate.js +84 -0
- package/templates/app/backend/app/Http/Middleware/CheckAbilities.js +17 -0
- package/templates/app/backend/app/Http/Middleware/CheckForAnyAbility.js +12 -0
- package/templates/app/backend/app/Http/Middleware/EnsureEmailIsVerified.js +11 -0
- package/templates/app/backend/app/Http/Middleware/EnsureHasRole.js +11 -0
- package/templates/app/backend/app/Http/Middleware/EnsureIsAdmin.js +11 -0
- package/templates/app/backend/app/Http/Middleware/RequirePassword.js +15 -0
- package/templates/app/backend/app/Http/Requests/Auth/LoginRequest.js +45 -0
- package/templates/app/backend/app/Http/Resources/.gitkeep +1 -0
- package/templates/app/backend/app/Jobs/.gitkeep +0 -0
- package/templates/app/backend/app/Listeners/.gitkeep +0 -0
- package/templates/app/backend/app/Mail/.gitkeep +0 -0
- package/templates/app/backend/app/Models/PersonalAccessToken.js +21 -0
- package/templates/app/backend/app/Models/User.js +64 -0
- package/templates/app/backend/app/Notifications/.gitkeep +0 -0
- package/templates/app/backend/app/Observers/.gitkeep +0 -0
- package/templates/app/backend/app/Policies/.gitkeep +0 -0
- package/templates/app/backend/app/Providers/AppServiceProvider.js +12 -0
- package/templates/app/backend/app/Rules/.gitkeep +1 -0
- package/templates/app/backend/config/app.js +16 -0
- package/templates/app/backend/config/auth.js +34 -0
- package/templates/app/backend/config/database.js +38 -0
- package/templates/app/backend/config/redis.js +28 -0
- package/templates/app/backend/config/session.js +36 -0
- package/templates/app/backend/database/migrations/0001_01_01_000000_create_users_table.js +49 -0
- package/templates/app/backend/database/migrations/0001_01_01_000001_create_cache_table.js +13 -0
- package/templates/app/backend/database/migrations/0001_01_01_000002_create_jobs_table.js +26 -0
- package/templates/app/backend/database/migrations/0001_01_01_000003_create_notifications_table.js +18 -0
- package/templates/app/backend/database/seeders/DatabaseSeeder.js +15 -0
- package/templates/app/backend/lang/ar/messages.json +10 -0
- package/templates/app/backend/lang/ar/validation.json +21 -0
- package/templates/app/backend/lang/en/messages.json +10 -0
- package/templates/app/backend/lang/en/validation.json +19 -0
- package/templates/app/backend/routes/api.js +25 -0
- package/templates/app/backend/routes/auth.js +52 -0
- package/templates/app/backend/routes/console.js +15 -0
- package/templates/app/frontend/App.kreftjs +4 -0
- package/templates/app/frontend/components/Field.kreftjs +19 -0
- package/templates/app/frontend/components/StatCard.kreftjs +47 -0
- package/templates/app/frontend/components/profile/ApiTokens.kreftjs +70 -0
- package/templates/app/frontend/components/profile/Sessions.kreftjs +42 -0
- package/templates/app/frontend/components/profile/TwoFactor.kreftjs +90 -0
- package/templates/app/frontend/errors/ErrorMonitor.kreftjs +264 -0
- package/templates/app/frontend/index.html +79 -0
- package/templates/app/frontend/kreftjs.d.ts +579 -0
- package/templates/app/frontend/kreftjs.js +5108 -0
- package/templates/app/frontend/layouts/app.kreftjs +718 -0
- package/templates/app/frontend/layouts/docs.kreftjs +37 -0
- package/templates/app/frontend/layouts/guest.kreftjs +18 -0
- package/templates/app/frontend/pages/Dashboard.kreftjs +273 -0
- package/templates/app/frontend/pages/ErrorMonitor.kreftjs +96 -0
- package/templates/app/frontend/pages/Home.kreftjs +617 -0
- package/templates/app/frontend/pages/Profile.kreftjs +104 -0
- package/templates/app/frontend/pages/Users.kreftjs +240 -0
- package/templates/app/frontend/pages/auth/ConfirmPassword.kreftjs +33 -0
- package/templates/app/frontend/pages/auth/ForgotPassword.kreftjs +36 -0
- package/templates/app/frontend/pages/auth/Login.kreftjs +89 -0
- package/templates/app/frontend/pages/auth/Register.kreftjs +48 -0
- package/templates/app/frontend/pages/auth/ResetPassword.kreftjs +45 -0
- package/templates/app/frontend/pages/auth/VerifyEmail.kreftjs +59 -0
- package/templates/app/frontend/routes/web.kreftjs +34 -0
- package/templates/app/frontend/tests/components/Counter.kreftjs +15 -0
- package/templates/app/frontend/tests/pages/About.kreftjs +12 -0
- package/templates/app/frontend/tests/pages/Test.kreftjs +31 -0
- package/templates/app/frontend/ui.css +517 -0
- package/templates/app/lang/ar/auth.json +6 -0
- package/templates/app/lang/ar/messages.json +6 -0
- package/templates/app/lang/ar/pagination.json +5 -0
- package/templates/app/lang/ar/passwords.json +8 -0
- package/templates/app/lang/ar/validation.json +22 -0
- package/templates/app/lang/ar.json +10 -0
- package/templates/app/lang/en/auth.json +6 -0
- package/templates/app/lang/en/messages.json +6 -0
- package/templates/app/lang/en/pagination.json +5 -0
- package/templates/app/lang/en/passwords.json +8 -0
- package/templates/app/lang/en/validation.json +22 -0
- package/templates/app/lang/en.json +10 -0
- package/templates/errors/401.kreftjs +11 -0
- package/templates/errors/402.kreftjs +11 -0
- package/templates/errors/403.kreftjs +11 -0
- package/templates/errors/404.kreftjs +11 -0
- package/templates/errors/419.kreftjs +11 -0
- package/templates/errors/429.kreftjs +11 -0
- package/templates/errors/500.kreftjs +11 -0
- package/templates/errors/503.kreftjs +11 -0
- package/templates/errors/ErrorMonitor.kreftjs +502 -0
- package/templates/errors/error.kreftjs +11 -0
- package/templates/errors/minimal.kreftjs +25 -0
- package/tools/dev-client.js +125 -0
- package/tools/devtools.js +172 -0
- package/tools/vite-plugin-kreftjs.d.ts +52 -0
- package/tools/vite-plugin-kreftjs.js +466 -0
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The app's own classes, found by folder (auto-discovery and namespace indexing):
|
|
3
|
+
* app/Models, app/Jobs, app/Events, app/Listeners, app/Mail, app/Notifications, app/Policies,
|
|
4
|
+
* app/Console/Commands, app/Observers, app/Http/Controllers, app/Http/Middleware
|
|
5
|
+
* Queued jobs, listeners, mails and notifications are stored by class name and found again here.
|
|
6
|
+
*/
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const { EXTS, registerTypeScript } = require('./typescript.js');
|
|
10
|
+
|
|
11
|
+
const state = { baseDir: null, index: new Map(), booted: false };
|
|
12
|
+
const unwrap = (m) => (m && m.default ? m.default : m);
|
|
13
|
+
|
|
14
|
+
function scan(dir, kind, out, subPath = '') {
|
|
15
|
+
if (!fs.existsSync(dir)) return;
|
|
16
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
17
|
+
const full = path.join(dir, e.name);
|
|
18
|
+
if (e.isDirectory()) {
|
|
19
|
+
scan(full, kind, out, subPath ? `${subPath}/${e.name}` : e.name);
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
const ext = path.extname(e.name);
|
|
23
|
+
if (!EXTS.includes(ext) || e.name.endsWith('.d.ts')) continue;
|
|
24
|
+
const baseName = path.basename(e.name, ext);
|
|
25
|
+
const relName = subPath ? `${subPath}/${baseName}` : baseName;
|
|
26
|
+
const nsBackslash = relName.replace(/\//g, '\\');
|
|
27
|
+
const nsForward = relName;
|
|
28
|
+
|
|
29
|
+
out.set(`${kind}:${baseName}`, full);
|
|
30
|
+
if (!out.has(baseName)) out.set(baseName, full);
|
|
31
|
+
|
|
32
|
+
if (subPath) {
|
|
33
|
+
out.set(`${kind}:${nsBackslash}`, full);
|
|
34
|
+
out.set(`${kind}:${nsForward}`, full);
|
|
35
|
+
out.set(nsBackslash, full);
|
|
36
|
+
out.set(nsForward, full);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Index full PHP namespace paths:
|
|
40
|
+
// e.g. App\Models\User, App\Http\Controllers\Admin\UserController
|
|
41
|
+
const folderName = kind === 'command' ? 'Console\\Commands' : kind.startsWith('http_') ? `Http\\${kind.slice(5).charAt(0).toUpperCase() + kind.slice(6)}s` : `${kind.charAt(0).toUpperCase() + kind.slice(1)}s`;
|
|
42
|
+
const fullNamespaceBack = `App\\${folderName}\\${nsBackslash}`;
|
|
43
|
+
const fullNamespaceFwd = fullNamespaceBack.replace(/\\/g, '/');
|
|
44
|
+
out.set(fullNamespaceBack, full);
|
|
45
|
+
out.set(fullNamespaceFwd, full);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const KINDS = {
|
|
50
|
+
Models: 'model',
|
|
51
|
+
Jobs: 'job',
|
|
52
|
+
Events: 'event',
|
|
53
|
+
Listeners: 'listener',
|
|
54
|
+
Mail: 'mail',
|
|
55
|
+
Notifications: 'notification',
|
|
56
|
+
Policies: 'policy',
|
|
57
|
+
Observers: 'observer',
|
|
58
|
+
'Console/Commands': 'command',
|
|
59
|
+
'Http/Controllers': 'http_controller',
|
|
60
|
+
'Http/Middleware': 'http_middleware',
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// boot(baseDir): index the classes, register listeners, observers and policies (again after a change)
|
|
64
|
+
function boot(baseDir) {
|
|
65
|
+
registerTypeScript(baseDir);
|
|
66
|
+
state.baseDir = baseDir;
|
|
67
|
+
state.index = new Map();
|
|
68
|
+
const appDirs = [
|
|
69
|
+
path.join(baseDir, 'app'),
|
|
70
|
+
path.join(baseDir, 'backend', 'app')
|
|
71
|
+
];
|
|
72
|
+
try {
|
|
73
|
+
const { layout } = require('../layout.js');
|
|
74
|
+
const lay = layout(baseDir);
|
|
75
|
+
if (lay.backend) appDirs.push(path.join(lay.backend, 'app'));
|
|
76
|
+
} catch (_) {}
|
|
77
|
+
|
|
78
|
+
const seen = new Set();
|
|
79
|
+
for (const aDir of appDirs) {
|
|
80
|
+
let real = aDir;
|
|
81
|
+
try { real = fs.realpathSync(aDir); } catch (_) {}
|
|
82
|
+
if (fs.existsSync(aDir) && !seen.has(real)) {
|
|
83
|
+
seen.add(real);
|
|
84
|
+
for (const [folder, kind] of Object.entries(KINDS)) scan(path.join(aDir, ...folder.split('/')), kind, state.index);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
require('./model.js').setBaseDir(baseDir);
|
|
89
|
+
require('./support.js').Log.setDirectory(path.join(baseDir, 'storage', 'logs'));
|
|
90
|
+
require('./support.js').Lang.setDirectory(path.join(baseDir, 'lang'));
|
|
91
|
+
const { Event } = require('./events.js');
|
|
92
|
+
Event.reset();
|
|
93
|
+
for (const file of filesOf('listener')) {
|
|
94
|
+
let L;
|
|
95
|
+
try { L = unwrap(require(file)); } catch (e) { console.error(` Error in ${path.relative(process.cwd(), file)}: ${e.message}`); continue; }
|
|
96
|
+
if (L && L.event) for (const ev of [].concat(L.event)) Event.listen(ev, L);
|
|
97
|
+
}
|
|
98
|
+
// app/Policies/PostPolicy.js guards the Post model (Gate.authorize('update', post))
|
|
99
|
+
const gate = require('./gate.js');
|
|
100
|
+
gate.Gate.resetPolicies();
|
|
101
|
+
for (const file of filesOf('policy')) {
|
|
102
|
+
const name = path.basename(file, path.extname(file));
|
|
103
|
+
gate.Gate.policyFile(name.replace(/Policy$/, ''), file);
|
|
104
|
+
}
|
|
105
|
+
// app/Providers/*.js: boot() runs now
|
|
106
|
+
const pdir = path.join(baseDir, 'app', 'Providers');
|
|
107
|
+
if (fs.existsSync(pdir)) for (const f of fs.readdirSync(pdir).sort()) {
|
|
108
|
+
if (!EXTS.includes(path.extname(f)) || f.endsWith('.d.ts')) continue;
|
|
109
|
+
try { const P = unwrap(require(path.join(pdir, f))); const p = typeof P === 'function' ? new P() : P; if (p && typeof p.boot === 'function') p.boot(); }
|
|
110
|
+
catch (e) { console.error(` Error in app/Providers/${f}: ${e.message}`); }
|
|
111
|
+
}
|
|
112
|
+
state.booted = true;
|
|
113
|
+
return state;
|
|
114
|
+
}
|
|
115
|
+
function filesOf(kind) { return [...state.index].filter(([k]) => k.startsWith(kind + ':')).map(([, f]) => f); }
|
|
116
|
+
function isInsideDir(targetPath, baseDir) {
|
|
117
|
+
const resolvedTarget = path.resolve(targetPath);
|
|
118
|
+
const resolvedBase = path.resolve(baseDir);
|
|
119
|
+
if (resolvedTarget === resolvedBase || resolvedTarget.startsWith(resolvedBase + path.sep)) return true;
|
|
120
|
+
try {
|
|
121
|
+
const realTarget = fs.realpathSync(resolvedTarget);
|
|
122
|
+
const realBase = fs.realpathSync(resolvedBase);
|
|
123
|
+
return realTarget === realBase || realTarget.startsWith(realBase + path.sep);
|
|
124
|
+
} catch (_) {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function find(name, kind) {
|
|
129
|
+
if (!name || typeof name !== 'string' || name.includes('\0')) return null;
|
|
130
|
+
if (name === '__proto__' || name === 'constructor' || name === 'prototype') return null;
|
|
131
|
+
const normal = name.replace(/\\/g, '/').replace(/^\/+/, '');
|
|
132
|
+
const backslash = normal.replace(/\//g, '\\');
|
|
133
|
+
const key = kind ? `${kind}:${name}` : name;
|
|
134
|
+
let file = state.index.get(key)
|
|
135
|
+
|| state.index.get(name)
|
|
136
|
+
|| state.index.get(normal)
|
|
137
|
+
|| state.index.get(backslash);
|
|
138
|
+
|
|
139
|
+
if (!file && state.baseDir) {
|
|
140
|
+
const rel = normal.replace(/^App\//i, '');
|
|
141
|
+
const segments = rel.split('/');
|
|
142
|
+
if (segments.some((seg) => !seg || seg === '.' || seg === '..' || seg === '__proto__' || seg === 'constructor' || seg === 'prototype')) {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
let appRoot = path.join(state.baseDir, 'app');
|
|
146
|
+
if (!fs.existsSync(appRoot) && fs.existsSync(path.join(state.baseDir, 'backend', 'app'))) {
|
|
147
|
+
appRoot = path.join(state.baseDir, 'backend', 'app');
|
|
148
|
+
}
|
|
149
|
+
const { findFile } = require('./typescript.js');
|
|
150
|
+
const candidate = findFile(path.join(appRoot, rel))
|
|
151
|
+
|| (kind === 'model' ? findFile(path.join(appRoot, 'Models', rel)) : null)
|
|
152
|
+
|| (kind === 'http_controller' ? findFile(path.join(appRoot, 'Http', 'Controllers', rel)) : null);
|
|
153
|
+
if (candidate && isInsideDir(candidate, appRoot)) {
|
|
154
|
+
file = candidate;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return file ? unwrap(require(file)) : null;
|
|
158
|
+
}
|
|
159
|
+
const baseDir = () => state.baseDir;
|
|
160
|
+
|
|
161
|
+
module.exports = { boot, find, filesOf, baseDir, unwrap, state };
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Cache: key-value caching with multiple storage drivers.
|
|
3
|
+
*
|
|
4
|
+
* await Cache.put('stats', data, 600) // 10 minutes
|
|
5
|
+
* const stats = await Cache.remember('stats', 600, () => loadStats())
|
|
6
|
+
* await Cache.get('stats', fallback) Cache.has('stats') Cache.forget('stats') Cache.flush()
|
|
7
|
+
* await Cache.increment('visits') Cache.rememberForever('settings', fn) Cache.pull('once')
|
|
8
|
+
* const lock = await Cache.lock('report', 30); if (lock) { …; await lock.release() }
|
|
9
|
+
*
|
|
10
|
+
* CACHE_STORE in .env: database (the cache table, shared by every process), file (backend/storage/cache)
|
|
11
|
+
* or memory (this process only, gone on restart). Without the cache table, database falls back to memory.
|
|
12
|
+
*/
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const path = require('path');
|
|
15
|
+
const crypto = require('crypto');
|
|
16
|
+
const { Builder, getConnection } = require('./query.js');
|
|
17
|
+
const { parseJson } = require('../safe-json.js');
|
|
18
|
+
|
|
19
|
+
const nowSec = () => Math.floor(Date.now() / 1000);
|
|
20
|
+
const expiry = (seconds) => (seconds == null ? 0 : nowSec() + Math.max(1, Math.floor(seconds instanceof Date ? (seconds - Date.now()) / 1000 : seconds)));
|
|
21
|
+
|
|
22
|
+
function memoryStore() {
|
|
23
|
+
const map = new Map();
|
|
24
|
+
return {
|
|
25
|
+
async get(key) { const e = map.get(key); if (!e) return undefined; if (e.exp && e.exp <= nowSec()) { map.delete(key); return undefined; } return e.value; },
|
|
26
|
+
async put(key, value, exp) { map.set(key, { value, exp }); },
|
|
27
|
+
async add(key, value, exp) { if ((await this.get(key)) !== undefined) return false; map.set(key, { value, exp }); return true; },
|
|
28
|
+
async forget(key) { return map.delete(key); },
|
|
29
|
+
async flush() { map.clear(); },
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function fileStore(dir) {
|
|
33
|
+
const file = (key) => path.join(dir, crypto.createHash('sha1').update(key).digest('hex'));
|
|
34
|
+
return {
|
|
35
|
+
async get(key) {
|
|
36
|
+
try { const e = parseJson(fs.readFileSync(file(key), 'utf8')); if (e.exp && e.exp <= nowSec()) { fs.rmSync(file(key), { force: true }); return undefined; } return e.value; } catch (_) { return undefined; }
|
|
37
|
+
},
|
|
38
|
+
async put(key, value, exp) { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file(key), JSON.stringify({ value, exp })); },
|
|
39
|
+
async add(key, value, exp) {
|
|
40
|
+
if ((await this.get(key)) !== undefined) return false;
|
|
41
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
42
|
+
try { fs.writeFileSync(file(key), JSON.stringify({ value, exp }), { flag: 'wx' }); return true; } catch (_) { return false; }
|
|
43
|
+
},
|
|
44
|
+
async forget(key) { const f = file(key); const had = fs.existsSync(f); fs.rmSync(f, { force: true }); return had; },
|
|
45
|
+
async flush() { fs.rmSync(dir, { recursive: true, force: true }); },
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function databaseStore() {
|
|
49
|
+
const table = () => new Builder('cache');
|
|
50
|
+
return {
|
|
51
|
+
async get(key) {
|
|
52
|
+
const row = await table().where('key', key).first();
|
|
53
|
+
if (!row) return undefined;
|
|
54
|
+
if (Number(row.expiration) && Number(row.expiration) <= nowSec()) { await table().where('key', key).delete(); return undefined; }
|
|
55
|
+
try { return parseJson(row.value); } catch (_) { return row.value; }
|
|
56
|
+
},
|
|
57
|
+
async put(key, value, exp) { await table().updateOrInsert({ key }, { value: JSON.stringify(value), expiration: exp }); },
|
|
58
|
+
async add(key, value, exp) {
|
|
59
|
+
await table().where('key', key).where('expiration', '>', 0).where('expiration', '<=', nowSec()).delete();
|
|
60
|
+
try { await table().insert({ key, value: JSON.stringify(value), expiration: exp }); return true; } catch (_) { return false; } // the key is taken
|
|
61
|
+
},
|
|
62
|
+
async forget(key) { return (await table().where('key', key).delete()) > 0; },
|
|
63
|
+
async flush() { await table().delete(); },
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function redisStore() {
|
|
68
|
+
const { Redis } = require('./redis.js');
|
|
69
|
+
const redis = Redis.connection('cache');
|
|
70
|
+
return {
|
|
71
|
+
async get(key) {
|
|
72
|
+
const v = await redis.get(key);
|
|
73
|
+
if (v == null) return undefined;
|
|
74
|
+
try { return parseJson(v); } catch (_) { return v; }
|
|
75
|
+
},
|
|
76
|
+
async put(key, value, exp) {
|
|
77
|
+
const val = JSON.stringify(value);
|
|
78
|
+
if (exp && exp > 0) {
|
|
79
|
+
const ttl = Math.max(1, exp - nowSec());
|
|
80
|
+
await redis.set(key, val, 'EX', ttl);
|
|
81
|
+
} else {
|
|
82
|
+
await redis.set(key, val);
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
async add(key, value, exp) {
|
|
86
|
+
const val = JSON.stringify(value);
|
|
87
|
+
if (exp && exp > 0) {
|
|
88
|
+
const ttl = Math.max(1, exp - nowSec());
|
|
89
|
+
const res = await redis.set(key, val, 'EX', ttl, 'NX');
|
|
90
|
+
return res === 'OK' || res === 1 || res === true;
|
|
91
|
+
}
|
|
92
|
+
const res = await redis.set(key, val, 'NX');
|
|
93
|
+
return res === 'OK' || res === 1 || res === true;
|
|
94
|
+
},
|
|
95
|
+
async forget(key) {
|
|
96
|
+
const deleted = await redis.del(key);
|
|
97
|
+
return Number(deleted) > 0;
|
|
98
|
+
},
|
|
99
|
+
async flush() {
|
|
100
|
+
await redis.flushdb();
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const stores = {};
|
|
106
|
+
let hasTable = null;
|
|
107
|
+
async function store(name) {
|
|
108
|
+
name = name || (process.env.CACHE_STORE || process.env.CACHE_DRIVER || 'database').toLowerCase();
|
|
109
|
+
if (name === 'database') {
|
|
110
|
+
if (hasTable === null) { try { hasTable = (await getConnection().tables()).some((t) => t.name === 'cache'); } catch (_) { hasTable = false; } }
|
|
111
|
+
if (!hasTable) name = 'memory';
|
|
112
|
+
}
|
|
113
|
+
if (!stores[name]) {
|
|
114
|
+
const base = require('./app.js').baseDir() || process.cwd();
|
|
115
|
+
stores[name] = name === 'file' ? fileStore(path.join(base, 'storage', 'cache'))
|
|
116
|
+
: name === 'database' ? databaseStore()
|
|
117
|
+
: name === 'redis' ? redisStore()
|
|
118
|
+
: memoryStore();
|
|
119
|
+
}
|
|
120
|
+
return stores[name];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function makeCache(storeName) {
|
|
124
|
+
const prefix = process.env.CACHE_PREFIX || '';
|
|
125
|
+
const k = (key) => prefix + key;
|
|
126
|
+
const Cache = {
|
|
127
|
+
store: (name) => makeCache(name),
|
|
128
|
+
async get(key, fallback = null) { const v = await (await store(storeName)).get(k(key)); return v === undefined ? (typeof fallback === 'function' ? fallback() : fallback) : v; },
|
|
129
|
+
async has(key) { return (await (await store(storeName)).get(k(key))) !== undefined; },
|
|
130
|
+
async missing(key) { return !(await Cache.has(key)); },
|
|
131
|
+
async put(key, value, seconds) { await (await store(storeName)).put(k(key), value, expiry(seconds)); return true; },
|
|
132
|
+
set(key, value, seconds) { return Cache.put(key, value, seconds); },
|
|
133
|
+
async add(key, value, seconds) { return (await store(storeName)).add(k(key), value, expiry(seconds)); },
|
|
134
|
+
forever(key, value) { return Cache.put(key, value, null); },
|
|
135
|
+
async remember(key, seconds, fn) {
|
|
136
|
+
const s = await store(storeName);
|
|
137
|
+
const v = await s.get(k(key));
|
|
138
|
+
if (v !== undefined) return v;
|
|
139
|
+
const fresh = await fn();
|
|
140
|
+
await s.put(k(key), fresh, expiry(seconds));
|
|
141
|
+
return fresh;
|
|
142
|
+
},
|
|
143
|
+
rememberForever(key, fn) { return Cache.remember(key, null, fn); },
|
|
144
|
+
async pull(key, fallback = null) { const v = await Cache.get(key, fallback); await Cache.forget(key); return v; },
|
|
145
|
+
async forget(key) { return (await store(storeName)).forget(k(key)); },
|
|
146
|
+
async increment(key, by = 1) { const v = Number(await Cache.get(key, 0)) + by; await Cache.put(key, v); return v; },
|
|
147
|
+
decrement(key, by = 1) { return Cache.increment(key, -by); },
|
|
148
|
+
async flush() { await (await store(storeName)).flush(); return true; },
|
|
149
|
+
// an atomic lock: only one process gets it until it is released or expires
|
|
150
|
+
// Supports:
|
|
151
|
+
// const lock = await Cache.lock('report', 30); if (lock) { ...; await lock.release(); }
|
|
152
|
+
// await Cache.lock('report', 30, async () => { ... })
|
|
153
|
+
// await Cache.lock('report', 30).get(async () => { ... })
|
|
154
|
+
// await Cache.lock('report', 30).block(5, async () => { ... })
|
|
155
|
+
lock(name, seconds = 10, callback = null) {
|
|
156
|
+
const owner = crypto.randomUUID();
|
|
157
|
+
const lockKey = 'lock:' + name;
|
|
158
|
+
const release = async () => {
|
|
159
|
+
if ((await Cache.get(lockKey)) === owner) await Cache.forget(lockKey);
|
|
160
|
+
};
|
|
161
|
+
const tryAcquire = async () => {
|
|
162
|
+
const ok = await (await store(storeName)).add(k(lockKey), owner, expiry(seconds));
|
|
163
|
+
if (!ok) return null;
|
|
164
|
+
return { owner, release, forceRelease: () => Cache.forget(lockKey) };
|
|
165
|
+
};
|
|
166
|
+
const get = async (fn) => {
|
|
167
|
+
const acquired = await tryAcquire();
|
|
168
|
+
if (!acquired) return typeof fn === 'function' ? false : null;
|
|
169
|
+
if (typeof fn !== 'function') return acquired;
|
|
170
|
+
try { return await fn(acquired); } finally { await release(); }
|
|
171
|
+
};
|
|
172
|
+
const block = async (waitSeconds = 5, fn = null) => {
|
|
173
|
+
const deadline = Date.now() + Math.max(0, Number(waitSeconds) || 0) * 1000;
|
|
174
|
+
let acquired = await tryAcquire();
|
|
175
|
+
while (!acquired && Date.now() < deadline) {
|
|
176
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
177
|
+
acquired = await tryAcquire();
|
|
178
|
+
}
|
|
179
|
+
if (!acquired) throw new Error(`Could not acquire lock "${name}" within ${waitSeconds}s.`);
|
|
180
|
+
if (typeof fn !== 'function') return acquired;
|
|
181
|
+
try { return await fn(acquired); } finally { await release(); }
|
|
182
|
+
};
|
|
183
|
+
const promise = typeof callback === 'function' ? get(callback) : tryAcquire();
|
|
184
|
+
promise.get = get;
|
|
185
|
+
promise.block = block;
|
|
186
|
+
promise.release = release;
|
|
187
|
+
promise.forceRelease = () => Cache.forget(lockKey);
|
|
188
|
+
return promise;
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
return Cache;
|
|
192
|
+
}
|
|
193
|
+
const Cache = makeCache();
|
|
194
|
+
const forget = () => { hasTable = null; for (const key of Object.keys(stores)) delete stores[key]; };
|
|
195
|
+
|
|
196
|
+
module.exports = { Cache, forget };
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Collections: a powerful Array wrapper with fluent data-manipulation helpers.
|
|
3
|
+
* a real array (map, filter, for…of and JSON all work as usual).
|
|
4
|
+
*
|
|
5
|
+
* const posts = await Post.all()
|
|
6
|
+
* posts.pluck('title') posts.where('published', true) posts.sortByDesc('likes')
|
|
7
|
+
* posts.groupBy('user_id') posts.keyBy('id') posts.sum('likes')
|
|
8
|
+
* collect([1, 2, 3]).chunk(2) posts.first() posts.isEmpty() posts.unique('user_id')
|
|
9
|
+
*/
|
|
10
|
+
const isBadKey = (k) => k === '__proto__' || k === 'constructor' || k === 'prototype';
|
|
11
|
+
const get = (item, key) => (typeof key === 'function' ? key(item) : key == null ? item : String(key).split('.').reduce((o, k) => (o == null || isBadKey(k) ? undefined : o[k]), item));
|
|
12
|
+
const compare = (a, op, b) => {
|
|
13
|
+
switch (op) {
|
|
14
|
+
case '=': case '==': return a == b; // eslint-disable-line eqeqeq
|
|
15
|
+
case '===': return a === b;
|
|
16
|
+
case '!=': case '<>': return a != b; // eslint-disable-line eqeqeq
|
|
17
|
+
case '!==': return a !== b;
|
|
18
|
+
case '<': return a < b;
|
|
19
|
+
case '>': return a > b;
|
|
20
|
+
case '<=': return a <= b;
|
|
21
|
+
case '>=': return a >= b;
|
|
22
|
+
default: throw new Error(`Unknown operator "${op}"`);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
class Collection extends Array {
|
|
27
|
+
static make(items = []) { return Collection.from(items); }
|
|
28
|
+
|
|
29
|
+
all() { return Array.from(this); }
|
|
30
|
+
toArray() { return Array.from(this, (x) => (x && typeof x.toJSON === 'function' ? x.toJSON() : x)); }
|
|
31
|
+
count() { return this.length; }
|
|
32
|
+
isEmpty() { return this.length === 0; }
|
|
33
|
+
isNotEmpty() { return this.length > 0; }
|
|
34
|
+
|
|
35
|
+
first(fn) { return fn ? this.find(fn) ?? null : this[0] ?? null; }
|
|
36
|
+
last(fn) { const list = fn ? this.filter(fn) : this; return list[list.length - 1] ?? null; }
|
|
37
|
+
firstWhere(key, op, value) { return this.where(key, op, value).first(); }
|
|
38
|
+
pluck(key, by) {
|
|
39
|
+
if (by) return Object.fromEntries(this.map((x) => [get(x, by), get(x, key)]).filter(([k]) => !isBadKey(String(k))));
|
|
40
|
+
return Collection.from(this, (x) => get(x, key));
|
|
41
|
+
}
|
|
42
|
+
where(key, op, value) {
|
|
43
|
+
if (value === undefined) { value = op; op = '='; }
|
|
44
|
+
return this.filter((x) => compare(get(x, key), op, value));
|
|
45
|
+
}
|
|
46
|
+
whereIn(key, values) { const set = new Set(values); return this.filter((x) => set.has(get(x, key))); }
|
|
47
|
+
whereNotIn(key, values) { const set = new Set(values); return this.filter((x) => !set.has(get(x, key))); }
|
|
48
|
+
whereNull(key) { return this.filter((x) => get(x, key) == null); }
|
|
49
|
+
whereNotNull(key) { return this.filter((x) => get(x, key) != null); }
|
|
50
|
+
reject(fn) { return this.filter((x, i) => !fn(x, i)); }
|
|
51
|
+
contains(key, value) {
|
|
52
|
+
if (typeof key === 'function') return this.some(key);
|
|
53
|
+
if (value === undefined) return this.includes(key);
|
|
54
|
+
return this.some((x) => get(x, key) == value); // eslint-disable-line eqeqeq
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
sum(key) { return this.reduce((t, x) => t + (Number(get(x, key)) || 0), 0); }
|
|
58
|
+
avg(key) { return this.length ? this.sum(key) / this.length : null; }
|
|
59
|
+
average(key) { return this.avg(key); }
|
|
60
|
+
min(key) { const v = this.map((x) => get(x, key)).filter((x) => x != null); return v.length ? v.reduce((a, b) => (b < a ? b : a)) : null; }
|
|
61
|
+
max(key) { const v = this.map((x) => get(x, key)).filter((x) => x != null); return v.length ? v.reduce((a, b) => (b > a ? b : a)) : null; }
|
|
62
|
+
|
|
63
|
+
sortBy(key, desc = false) {
|
|
64
|
+
const out = Collection.from(this);
|
|
65
|
+
out.sort((a, b) => { const x = get(a, key), y = get(b, key); return (x > y ? 1 : x < y ? -1 : 0) * (desc ? -1 : 1); });
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
sortByDesc(key) { return this.sortBy(key, true); }
|
|
69
|
+
groupBy(key) {
|
|
70
|
+
const out = {};
|
|
71
|
+
this.forEach((x) => {
|
|
72
|
+
const k = String(get(x, key));
|
|
73
|
+
if (isBadKey(k)) return;
|
|
74
|
+
if (!Object.prototype.hasOwnProperty.call(out, k)) out[k] = new Collection();
|
|
75
|
+
out[k].push(x);
|
|
76
|
+
});
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
keyBy(key) { return Object.fromEntries(this.map((x) => [get(x, key), x]).filter(([k]) => !isBadKey(String(k)))); }
|
|
80
|
+
countBy(key) {
|
|
81
|
+
const out = {};
|
|
82
|
+
this.forEach((x) => {
|
|
83
|
+
const k = String(get(x, key));
|
|
84
|
+
if (isBadKey(k)) return;
|
|
85
|
+
out[k] = (Object.prototype.hasOwnProperty.call(out, k) ? out[k] : 0) + 1;
|
|
86
|
+
});
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
mapWithKeys(fn) { return Object.fromEntries(this.map((x, i) => Object.entries(fn(x, i))[0]).filter((e) => e && !isBadKey(String(e[0])))); }
|
|
90
|
+
unique(key) {
|
|
91
|
+
const seen = new Set();
|
|
92
|
+
return this.filter((x) => { const k = key ? get(x, key) : x; if (seen.has(k)) return false; seen.add(k); return true; });
|
|
93
|
+
}
|
|
94
|
+
chunk(size) {
|
|
95
|
+
size = Math.floor(Number(size));
|
|
96
|
+
const out = new Collection();
|
|
97
|
+
if (!size || size < 1) return out;
|
|
98
|
+
for (let i = 0; i < this.length; i += size) out.push(Collection.from(this.slice(i, i + size)));
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
take(n) { return Collection.from(n < 0 ? this.slice(n) : this.slice(0, n)); }
|
|
102
|
+
skip(n) { return Collection.from(this.slice(n)); }
|
|
103
|
+
partition(fn) { return Collection.of(this.filter(fn), this.filter((x, i) => !fn(x, i))); }
|
|
104
|
+
implode(glue = ', ', key) { return (key ? this.map((x) => get(x, key)) : this).join(glue); }
|
|
105
|
+
each(fn) { for (let i = 0; i < this.length; i++) if (fn(this[i], i) === false) break; return this; }
|
|
106
|
+
tap(fn) { fn(this); return this; }
|
|
107
|
+
pipe(fn) { return fn(this); }
|
|
108
|
+
random() { return this.length ? this[Math.floor(Math.random() * this.length)] : null; }
|
|
109
|
+
shuffle() { const out = Collection.from(this); for (let i = out.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [out[i], out[j]] = [out[j], out[i]]; } return out; }
|
|
110
|
+
only(...keys) { keys = keys.flat(); return this.map((x) => Object.fromEntries(keys.map((k) => [k, get(x, k)]))); }
|
|
111
|
+
except(...keys) { keys = new Set(keys.flat()); return this.map((x) => Object.fromEntries(Object.entries(x && x.toJSON ? x.toJSON() : x).filter(([k]) => !keys.has(k)))); }
|
|
112
|
+
toJSON() { return this.toArray(); }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const collect = (items = []) => Collection.from(items);
|
|
116
|
+
|
|
117
|
+
module.exports = { Collection, collect };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Custom console commands (app/Console/Commands, kreftjs make:command SendReport).
|
|
3
|
+
*
|
|
4
|
+
* class SendReport extends Command {
|
|
5
|
+
* static signature = 'send:report {user} {--queue}'
|
|
6
|
+
* static description = 'Email the report'
|
|
7
|
+
* async handle() { this.info('Sent to ' + this.argument('user')) }
|
|
8
|
+
* }
|
|
9
|
+
*/
|
|
10
|
+
const tty = () => process.stdout.isTTY;
|
|
11
|
+
const green = (s) => (tty() ? `\x1b[32m${s}\x1b[0m` : s);
|
|
12
|
+
const dim = (s) => (tty() ? `\x1b[2m${s}\x1b[0m` : s);
|
|
13
|
+
const yellow = (s) => (tty() ? `\x1b[33m${s}\x1b[0m` : s);
|
|
14
|
+
const red = (s) => (tty() ? `\x1b[31m${s}\x1b[0m` : s);
|
|
15
|
+
|
|
16
|
+
class Command {
|
|
17
|
+
static signature = '';
|
|
18
|
+
static description = '';
|
|
19
|
+
argument(name) { return this.__args[name]; }
|
|
20
|
+
arguments() { return { ...this.__args }; }
|
|
21
|
+
option(name) { return this.__opts[name]; }
|
|
22
|
+
options() { return { ...this.__opts }; }
|
|
23
|
+
line(text = '') { console.log(' ' + text); }
|
|
24
|
+
info(text) { console.log(' ' + green(text)); }
|
|
25
|
+
comment(text) { console.log(' ' + dim(text)); }
|
|
26
|
+
warn(text) { console.log(' ' + yellow(text)); }
|
|
27
|
+
error(text) { console.error(' ' + red(text)); }
|
|
28
|
+
newLine(n = 1) { console.log('\n'.repeat(n - 1)); }
|
|
29
|
+
table(rows, headers) {
|
|
30
|
+
if (!rows.length) return;
|
|
31
|
+
headers = headers || Object.keys(rows[0]);
|
|
32
|
+
const w = headers.map((h, i) => Math.max(String(h).length, ...rows.map((r) => String(Array.isArray(r) ? r[i] : r[h] ?? '').length)));
|
|
33
|
+
const line = (cells) => ' ' + cells.map((c, i) => String(c ?? '').padEnd(w[i])).join(' ');
|
|
34
|
+
console.log(line(headers)); console.log(' ' + w.map((n) => '─'.repeat(n)).join(' '));
|
|
35
|
+
rows.forEach((r) => console.log(line(Array.isArray(r) ? r : headers.map((h) => r[h]))));
|
|
36
|
+
}
|
|
37
|
+
ask(question, fallback) {
|
|
38
|
+
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
|
|
39
|
+
return new Promise((res) => rl.question(` ${question}${fallback ? dim(` [${fallback}]`) : ''} `, (a) => { rl.close(); res(a || fallback || ''); }));
|
|
40
|
+
}
|
|
41
|
+
async confirm(question, fallback = false) { const a = (await this.ask(`${question} (yes/no)`, fallback ? 'yes' : 'no')).toLowerCase(); return a === 'y' || a === 'yes'; }
|
|
42
|
+
call(line) { return require('../artisan-more.js').runCommand(line); }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = { Command };
|