@ghuri/core 0.0.0-stage → 0.1.0-alpha.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.
- package/LICENSE +21 -0
- package/README.md +477 -2
- package/dist/chunk-BQBV57DI.js +1271 -0
- package/dist/chunk-BQBV57DI.js.map +1 -0
- package/dist/context-Du2IsGtO.d.ts +573 -0
- package/dist/index.d.ts +471 -0
- package/dist/index.js +1473 -0
- package/dist/index.js.map +1 -0
- package/dist/node.d.ts +40 -0
- package/dist/node.js +53 -0
- package/dist/node.js.map +1 -0
- package/dist/testing.d.ts +108 -0
- package/dist/testing.js +270 -0
- package/dist/testing.js.map +1 -0
- package/package.json +83 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ghuri contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,478 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ghuri/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The foundation of [Ghuri](https://github.com/ghurijs/ghuri) — Django for TypeScript, Cloudflare first.
|
|
4
|
+
|
|
5
|
+
`@ghuri/core` gives you Django's project structure on top of [Hono](https://hono.dev): settings,
|
|
6
|
+
installed apps, `urls` with `path()` / `include()` / `reverse()`, function and class-based views,
|
|
7
|
+
middleware (security, CSRF, CORS, …), a per-request context, signals, a cache API, system checks,
|
|
8
|
+
management-command plumbing, a Node adapter and a test client.
|
|
9
|
+
|
|
10
|
+
It runs on **Cloudflare Workers** (with `nodejs_compat`) by default and on **Node.js** with the same code.
|
|
11
|
+
|
|
12
|
+
> Status: alpha (`0.1.0-alpha.0`). APIs may change.
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @ghuri/core@next hono
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Contents
|
|
19
|
+
|
|
20
|
+
- [Quick start](#quick-start)
|
|
21
|
+
- [Settings](#settings)
|
|
22
|
+
- [Apps](#apps)
|
|
23
|
+
- [URLs](#urls)
|
|
24
|
+
- [Views](#views)
|
|
25
|
+
- [Errors](#errors)
|
|
26
|
+
- [Middleware](#middleware)
|
|
27
|
+
- [Request context](#request-context)
|
|
28
|
+
- [Signals](#signals)
|
|
29
|
+
- [Cache](#cache)
|
|
30
|
+
- [Cron triggers and queues](#cron-triggers-and-queues)
|
|
31
|
+
- [Management commands](#management-commands)
|
|
32
|
+
- [System checks](#system-checks)
|
|
33
|
+
- [Running on Node](#running-on-node)
|
|
34
|
+
- [Testing](#testing)
|
|
35
|
+
|
|
36
|
+
## Quick start
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
// src/settings.ts
|
|
40
|
+
import { CommonMiddleware, CsrfMiddleware, SecurityMiddleware, defineSettings, kvCache } from '@ghuri/core'
|
|
41
|
+
import { BlogConfig } from './blog/app'
|
|
42
|
+
import { urlpatterns } from './urls'
|
|
43
|
+
|
|
44
|
+
export default defineSettings((env) => ({
|
|
45
|
+
SECRET_KEY: env.SECRET_KEY,
|
|
46
|
+
DEBUG: env.DEBUG === 'true',
|
|
47
|
+
ALLOWED_HOSTS: ['example.com', '.example.com'],
|
|
48
|
+
INSTALLED_APPS: [BlogConfig],
|
|
49
|
+
MIDDLEWARE: [SecurityMiddleware, CommonMiddleware, CsrfMiddleware],
|
|
50
|
+
ROOT_URLCONF: urlpatterns,
|
|
51
|
+
CACHES: { default: kvCache('CACHE') },
|
|
52
|
+
}))
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
// src/urls.ts
|
|
57
|
+
import { include, path } from '@ghuri/core'
|
|
58
|
+
import { blogUrls } from './blog/urls'
|
|
59
|
+
|
|
60
|
+
export const urlpatterns = [
|
|
61
|
+
path('', (c) => c.text('Hello from Ghuri'), { name: 'home' }),
|
|
62
|
+
path('blog/', include(blogUrls)),
|
|
63
|
+
]
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
// src/index.ts — the Worker entry (Django's wsgi.py)
|
|
68
|
+
import { createApp } from '@ghuri/core'
|
|
69
|
+
import settings from './settings'
|
|
70
|
+
|
|
71
|
+
export default createApp(settings)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`wrangler dev` and you're running. The same app runs on Node with `serve()` from `@ghuri/core/node`.
|
|
75
|
+
|
|
76
|
+
## Settings
|
|
77
|
+
|
|
78
|
+
Settings are a function of the runtime environment: Worker bindings and vars on Cloudflare,
|
|
79
|
+
`process.env` on Node. `defineSettings()` resolves them once per `env` object, applies defaults and
|
|
80
|
+
validates them.
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
export default defineSettings((env) => ({ SECRET_KEY: env.SECRET_KEY, INSTALLED_APPS: [], ROOT_URLCONF: [] }))
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Read them anywhere inside a request (or after `app.setup(env)`):
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { getSettings, setting } from '@ghuri/core'
|
|
90
|
+
|
|
91
|
+
getSettings().DEBUG
|
|
92
|
+
setting('PAGE_SIZE', 20) // with a fallback
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
| Setting | Default | |
|
|
96
|
+
|---|---|---|
|
|
97
|
+
| `SECRET_KEY` | — (required unless `DEBUG`) | Signing secret. Store it with `wrangler secret put SECRET_KEY`. |
|
|
98
|
+
| `DEBUG` | `false` | Debug error pages, startup system checks. |
|
|
99
|
+
| `ALLOWED_HOSTS` | `['*']` | Host validation (`'.example.com'` matches subdomains). With `DEBUG` and `[]`, localhost is allowed. |
|
|
100
|
+
| `INSTALLED_APPS` | — | `AppConfig` classes or instances. |
|
|
101
|
+
| `MIDDLEWARE` | `[]` | Middleware classes, instances, or plain Hono middleware. |
|
|
102
|
+
| `ROOT_URLCONF` | — | Your URL patterns. |
|
|
103
|
+
| `APPEND_SLASH` | `true` | Redirect `/x` → `/x/` when only the slashed URL exists. |
|
|
104
|
+
| `CACHES` | in-memory | `{ default: kvCache('CACHE') }` |
|
|
105
|
+
| `CSRF_TRUSTED_ORIGINS` | `[]` | e.g. `['https://*.example.com']` |
|
|
106
|
+
| `CORS` | `false` | `{ allowOrigins: ['https://app.example.com'], allowCredentials: true }` |
|
|
107
|
+
| `TIME_ZONE` / `USE_TZ` | `'UTC'` / `true` | |
|
|
108
|
+
| `API_PATH_PREFIXES` | `['/api']` | Errors under these paths are always JSON. |
|
|
109
|
+
|
|
110
|
+
Security and CSRF settings use Django's names: `SECURE_SSL_REDIRECT`, `SECURE_HSTS_SECONDS`,
|
|
111
|
+
`SECURE_HSTS_INCLUDE_SUBDOMAINS`, `SECURE_HSTS_PRELOAD`, `SECURE_PROXY_SSL_HEADER`,
|
|
112
|
+
`SECURE_REFERRER_POLICY`, `SECURE_CROSS_ORIGIN_OPENER_POLICY`, `SECURE_CONTENT_TYPE_NOSNIFF`,
|
|
113
|
+
`X_FRAME_OPTIONS`, `USE_X_FORWARDED_HOST`, `PREPEND_WWW`, `CSRF_COOKIE_NAME`, `CSRF_HEADER_NAME`,
|
|
114
|
+
`CSRF_COOKIE_SECURE`, `CSRF_COOKIE_HTTPONLY`, `CSRF_COOKIE_SAMESITE`, `CSRF_COOKIE_AGE`,
|
|
115
|
+
`CSRF_COOKIE_DOMAIN`, `CSRF_COOKIE_PATH`, `SILENCED_SYSTEM_CHECKS`.
|
|
116
|
+
|
|
117
|
+
Other packages add their own keys (`DATABASES`, `STORAGES`, `REST_FRAMEWORK`, …) with declaration merging:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
declare module '@ghuri/core' {
|
|
121
|
+
interface GhuriSettings { MY_FEATURE?: { enabled: boolean } }
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Apps
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
// src/blog/app.ts
|
|
129
|
+
import { AppConfig } from '@ghuri/core'
|
|
130
|
+
import * as models from './models'
|
|
131
|
+
|
|
132
|
+
export class BlogConfig extends AppConfig {
|
|
133
|
+
name = 'blog'
|
|
134
|
+
verboseName = 'Blog'
|
|
135
|
+
models = models
|
|
136
|
+
path = import.meta.dirname // used by the CLI for migrations
|
|
137
|
+
|
|
138
|
+
ready() {
|
|
139
|
+
// connect signals, register cron handlers, …
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`apps.populate(INSTALLED_APPS)` runs once per isolate before the first request: configs are
|
|
145
|
+
instantiated, packages' `onPopulate` hooks run (the ORM registers models), then each `ready()`.
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { apps } from '@ghuri/core'
|
|
149
|
+
apps.getAppConfig('blog'); apps.isInstalled('auth'); apps.getModel('blog.Post')
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## URLs
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
import { include, path, rePath, urlpatterns } from '@ghuri/core'
|
|
156
|
+
|
|
157
|
+
export const blogUrls = urlpatterns('blog', [ // app_name = 'blog'
|
|
158
|
+
path('', postList, { name: 'list' }),
|
|
159
|
+
path('<slug:slug>/', PostDetail, { name: 'detail' }), // View classes are accepted directly
|
|
160
|
+
])
|
|
161
|
+
|
|
162
|
+
export const root = [
|
|
163
|
+
path('', home, { name: 'home' }),
|
|
164
|
+
path('blog/', include(blogUrls)), // namespace 'blog' from appName
|
|
165
|
+
path('v2/blog/', include(blogUrls, { namespace: 'blog-v2' })),
|
|
166
|
+
path('posts/<int:id>/', PostView.asView(), { name: 'post-detail' }),
|
|
167
|
+
rePath('^archive/(?P<year>[0-9]{4})/$', archive, { name: 'archive' }),
|
|
168
|
+
path('upload/', upload, { methods: ['POST'] }), // other methods → 405
|
|
169
|
+
path('page/', page, { kwargs: { template: 'about' } }), // extra kwargs for the view
|
|
170
|
+
path('legacy/', someHonoApp), // escape hatch: mount any Hono app
|
|
171
|
+
]
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
**Converters** (Django's): `<int:x>`, `<str:x>` (default), `<slug:x>`, `<uuid:x>`, `<path:x>`. They are
|
|
175
|
+
compiled to Hono route patterns (`/posts/:id{[0-9]+}/`), so routing stays fast. Raw values are in
|
|
176
|
+
`c.req.param()`; converted values (numbers for `int`) plus extra kwargs come from `kwargs(c)`:
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
import { kwargs } from '@ghuri/core'
|
|
180
|
+
const postDetail = (c: Context) => c.json({ id: kwargs<{ id: number }>(c).id })
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Add your own converter:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
registerConverter('year', { regex: '[0-9]{4}', toJs: Number, toUrl: (v) => String(v).padStart(4, '0') })
|
|
187
|
+
path('archive/<year:y>/', archive)
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Routes Hono can't express (two parameters in one segment, complex `rePath` regexes) fall back to
|
|
191
|
+
regex matching automatically; their parameters are available through `kwargs(c)`.
|
|
192
|
+
|
|
193
|
+
**Reversing** — `reverse(name, params?, { query? })`, with namespaces:
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
reverse('home') // '/'
|
|
197
|
+
reverse('blog:detail', { slug: 'hello' }) // '/blog/hello/'
|
|
198
|
+
reverse('post-detail', [42]) // positional params
|
|
199
|
+
reverse('blog:list', {}, { query: { page: 2 } }) // '/blog/?page=2'
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
`resolve(path)` returns a `ResolverMatch` (`urlName`, `namespace`, `viewName`, `kwargs`, …);
|
|
203
|
+
`resolverMatch(c)` gives the current request's match. Patterns run in order — first match wins.
|
|
204
|
+
|
|
205
|
+
## Views
|
|
206
|
+
|
|
207
|
+
A view is a Hono handler: `(c: Context) => Response | Promise<Response>`. Throwing a `Response` returns it.
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
import { json, redirect, render } from '@ghuri/core'
|
|
211
|
+
|
|
212
|
+
export const home = (c: Context) => render(c, <HomePage user={c.get('user')} />)
|
|
213
|
+
export const api = (c: Context) => json(c, { ok: true }, 201) // bigint/Map/Set aware
|
|
214
|
+
export const go = (c: Context) => redirect(c, 'blog:detail', { slug: 'x' }) // name, URL or obj.getAbsoluteUrl()
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
**Class-based views** — a new instance per request; `asView(initkwargs)` overrides attributes:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
import { RedirectView, TemplateView, View } from '@ghuri/core'
|
|
221
|
+
|
|
222
|
+
class PostView extends View {
|
|
223
|
+
greeting = 'Hello'
|
|
224
|
+
async get(c: Context) {
|
|
225
|
+
return json(c, { id: this.kwargs.id, greeting: this.greeting })
|
|
226
|
+
}
|
|
227
|
+
async post(c: Context) { /* … */ }
|
|
228
|
+
}
|
|
229
|
+
path('posts/<int:id>/', PostView.asView({ greeting: 'Hi' }))
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Missing methods answer **405** with an `Allow` header; `HEAD` uses `get()`; `OPTIONS` answers with `Allow`.
|
|
233
|
+
Override `dispatch(c)` or `setup(c)` for cross-cutting logic, like Django.
|
|
234
|
+
|
|
235
|
+
`TemplateView` renders a Hono JSX component with `getContextData()`:
|
|
236
|
+
|
|
237
|
+
```tsx
|
|
238
|
+
class About extends TemplateView {
|
|
239
|
+
template = (p: { title: string }) => (
|
|
240
|
+
<html lang="en"><body><h1>{p.title}</h1></body></html>
|
|
241
|
+
)
|
|
242
|
+
async getContextData() {
|
|
243
|
+
return { ...(await super.getContextData()), title: 'About us' }
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
JSX output is escaped; use `html` from `hono/html` for trusted raw markup. `render()` adds
|
|
249
|
+
`<!DOCTYPE html>` when the output starts with `<html`.
|
|
250
|
+
|
|
251
|
+
`RedirectView.asView({ patternName: 'blog:list' })` or `{ url: '/posts/{id}/', permanent: true, queryString: true }`.
|
|
252
|
+
|
|
253
|
+
## Errors
|
|
254
|
+
|
|
255
|
+
Raise errors anywhere in a view; Ghuri maps them to responses:
|
|
256
|
+
|
|
257
|
+
| Error | Status |
|
|
258
|
+
|---|---|
|
|
259
|
+
| `Http404`, `ObjectDoesNotExist` | 404 |
|
|
260
|
+
| `PermissionDenied`, `CsrfFailure` | 403 |
|
|
261
|
+
| `BadRequest`, `SuspiciousOperation`, `DisallowedHost` | 400 |
|
|
262
|
+
| `ValidationError` | 400 with `{ detail, errors: { field: [messages] } }` |
|
|
263
|
+
| `MethodNotAllowed` | 405 with `Allow` |
|
|
264
|
+
| Hono `HTTPException` | its status / response |
|
|
265
|
+
| anything else | 500 |
|
|
266
|
+
|
|
267
|
+
Responses are JSON (`{ "detail": "…" }`) when the client accepts JSON but not HTML, sends JSON, or the
|
|
268
|
+
path is under `/api`; HTML otherwise. With `DEBUG`, 500s show a debug page with the stack trace,
|
|
269
|
+
request and (masked) settings, and 404s list the URL patterns that were tried — like Django.
|
|
270
|
+
Production pages never reveal details.
|
|
271
|
+
|
|
272
|
+
Packages and projects can map their own errors:
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
registerExceptionHandler(MyError, (err, c) => c.json({ code: err.code }, 409))
|
|
276
|
+
// or per app: createApp(settings, { onError: (err, c) => … })
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
## Middleware
|
|
280
|
+
|
|
281
|
+
```ts
|
|
282
|
+
MIDDLEWARE: [SecurityMiddleware, CommonMiddleware, CorsMiddleware, CsrfMiddleware, SessionMiddleware, AuthenticationMiddleware]
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
Write your own Django-style — it wraps the rest of the chain:
|
|
286
|
+
|
|
287
|
+
```ts
|
|
288
|
+
import { Middleware } from '@ghuri/core'
|
|
289
|
+
|
|
290
|
+
export class TimingMiddleware extends Middleware {
|
|
291
|
+
async handle(c: Context, next: Next) {
|
|
292
|
+
const started = Date.now()
|
|
293
|
+
await next()
|
|
294
|
+
c.header('Server-Timing', `app;dur=${Date.now() - started}`)
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
Return a `Response` to short-circuit (before `next()`) or replace the response (after it).
|
|
300
|
+
`MIDDLEWARE` also accepts configured instances (`new CorsMiddleware({ allowOrigins: '*' })`) and plain
|
|
301
|
+
Hono middleware (`logger()`).
|
|
302
|
+
|
|
303
|
+
Built-ins:
|
|
304
|
+
|
|
305
|
+
- **`SecurityMiddleware`** — `X-Content-Type-Options`, `Referrer-Policy`, `Cross-Origin-Opener-Policy`,
|
|
306
|
+
HSTS over https when `SECURE_HSTS_SECONDS > 0`, `SECURE_SSL_REDIRECT`.
|
|
307
|
+
- **`CommonMiddleware`** — `ALLOWED_HOSTS` (also enforced by the app itself), `PREPEND_WWW`, `APPEND_SLASH`.
|
|
308
|
+
- **`CorsMiddleware`** — uses the `CORS` setting; handles preflight requests.
|
|
309
|
+
- **`CsrfMiddleware`** — Django's CSRF protection: unsafe requests must send the `csrftoken` cookie's
|
|
310
|
+
token in the `X-CSRFToken` header or the `csrfmiddlewaretoken` form field; `Origin` (and on https
|
|
311
|
+
`Referer`) must match the host or `CSRF_TRUSTED_ORIGINS`. Tokens are Django-compatible (masked).
|
|
312
|
+
- **`XFrameOptionsMiddleware`** — `X-Frame-Options: DENY` (setting `X_FRAME_OPTIONS`).
|
|
313
|
+
- **`GZipMiddleware`** — compression on Node; a no-op on Workers (Cloudflare compresses at the edge).
|
|
314
|
+
|
|
315
|
+
CSRF helpers:
|
|
316
|
+
|
|
317
|
+
```tsx
|
|
318
|
+
<input type="hidden" name="csrfmiddlewaretoken" value={getCsrfToken(c)} />
|
|
319
|
+
|
|
320
|
+
path('webhooks/stripe/', csrfExempt(stripeWebhook)) // also works on mounted Hono apps
|
|
321
|
+
path('spa/', ensureCsrfCookie(spaShell)) // always set the cookie
|
|
322
|
+
rotateCsrfToken(c) // e.g. after login
|
|
323
|
+
await enforceCsrf(c) // manual check (REST session auth)
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
## Request context
|
|
327
|
+
|
|
328
|
+
Every request runs inside an `AsyncLocalStorage` context, so settings, env and per-request state are
|
|
329
|
+
available without passing `c` around:
|
|
330
|
+
|
|
331
|
+
```ts
|
|
332
|
+
import { getContext, getEnv, getSettings, getUser } from '@ghuri/core'
|
|
333
|
+
|
|
334
|
+
const ctx = getContext() // { env, settings, request, hono, executionCtx, state }
|
|
335
|
+
ctx.state.set(MY_KEY, value) // per-request cache (the ORM keeps DB connections here)
|
|
336
|
+
ctx.executionCtx?.waitUntil(sendAnalytics())
|
|
337
|
+
getEnv().MY_BINDING
|
|
338
|
+
getUser(c) // RequestUser, AnonymousUser by default
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
The Hono context also carries it: `c.get('ghuri')`, and `c.get('user')` (typed via `ContextVariableMap`).
|
|
342
|
+
Outside requests (CLI, scripts, tests) call `await app.setup(env)` first, or wrap code in
|
|
343
|
+
`runWithContext(ctx, fn)`.
|
|
344
|
+
|
|
345
|
+
## Signals
|
|
346
|
+
|
|
347
|
+
```ts
|
|
348
|
+
import { Signal, receiver, requestStarted, requestFinished } from '@ghuri/core'
|
|
349
|
+
|
|
350
|
+
requestFinished.connect(async ({ request, response }) => { /* … */ })
|
|
351
|
+
|
|
352
|
+
export const orderPlaced = new Signal<{ order: Order }>('orderPlaced')
|
|
353
|
+
receiver(orderPlaced)(async ({ order, sender }) => sendReceipt(order))
|
|
354
|
+
await orderPlaced.send(OrderService, { order })
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
Receivers run sequentially and are awaited. `connect(fn, { sender, uid })`, `disconnect(fnOrUid)`.
|
|
358
|
+
The ORM adds `preSave`, `postSave`, `preDelete`, `postDelete`, `m2mChanged`.
|
|
359
|
+
|
|
360
|
+
## Cache
|
|
361
|
+
|
|
362
|
+
```ts
|
|
363
|
+
import { cache, caches, cfCache, kvCache, memoryCache } from '@ghuri/core'
|
|
364
|
+
|
|
365
|
+
CACHES: {
|
|
366
|
+
default: kvCache('CACHE', { keyPrefix: 'v1' }), // Workers KV binding
|
|
367
|
+
local: memoryCache({ timeout: 60 }), // per isolate / process
|
|
368
|
+
edge: cfCache(), // Cloudflare Cache API (per data center)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
await cache.set('greeting', { text: 'hi' }, 300) // TTL seconds (default 300; null = forever)
|
|
372
|
+
await cache.get('greeting') // undefined when missing
|
|
373
|
+
await cache.getOrSet('stats', () => computeStats(), 60)
|
|
374
|
+
await cache.add('lock', true, 30) // only if missing
|
|
375
|
+
await cache.incr('hits')
|
|
376
|
+
await caches.get('local').clear()
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
Values are JSON-serialized. KV is eventually consistent and has a 60-second minimum TTL (shorter
|
|
380
|
+
TTLs are rounded up). Without `CACHES`, the default cache is in-memory. A cache config is just
|
|
381
|
+
`{ backend: string, create(env): CacheBackend }`, so custom backends are easy.
|
|
382
|
+
|
|
383
|
+
## Cron triggers and queues
|
|
384
|
+
|
|
385
|
+
`createApp()` also exports `scheduled` and `queue` handlers that dispatch to registered handlers,
|
|
386
|
+
inside a Ghuri context:
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
import { onQueue, onSchedule } from '@ghuri/core'
|
|
390
|
+
|
|
391
|
+
class BlogConfig extends AppConfig {
|
|
392
|
+
name = 'blog'
|
|
393
|
+
ready() {
|
|
394
|
+
onSchedule('0 * * * *', async (event) => { await publishScheduledPosts() }) // or '*' for all crons
|
|
395
|
+
onQueue<{ postId: number }>('emails', async (batch) => {
|
|
396
|
+
for (const msg of batch.messages) { await sendEmail(msg.body); msg.ack() }
|
|
397
|
+
})
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
## Management commands
|
|
403
|
+
|
|
404
|
+
```ts
|
|
405
|
+
import { BaseCommand, type ArgumentParser, type CommandIO } from '@ghuri/core'
|
|
406
|
+
|
|
407
|
+
export class Greet extends BaseCommand {
|
|
408
|
+
static help = 'Say hello'
|
|
409
|
+
addArguments(parser: ArgumentParser) {
|
|
410
|
+
parser.argument('name').option('--shout', { help: 'Use capitals' })
|
|
411
|
+
}
|
|
412
|
+
async handle(args: Record<string, unknown>, io: CommandIO) {
|
|
413
|
+
const msg = `Hello ${args.name}`
|
|
414
|
+
io.stdout(io.style.success(args.shout ? msg.toUpperCase() : msg))
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// in your AppConfig: commands = { greet: Greet } → npx ghuri greet World --shout
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
`callCommand('greet', { name: 'x' })` runs a command programmatically (`bufferIO()` captures output).
|
|
422
|
+
|
|
423
|
+
## System checks
|
|
424
|
+
|
|
425
|
+
```ts
|
|
426
|
+
import { checks, runChecks } from '@ghuri/core'
|
|
427
|
+
|
|
428
|
+
checks.register(({ settings }) =>
|
|
429
|
+
settings.MY_FEATURE ? [] : [checks.warning('MY_FEATURE is not configured.', { id: 'myapp.W001' })],
|
|
430
|
+
)
|
|
431
|
+
const messages = await runChecks({ deploy: true }) // `ghuri check --deploy`
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
Checks run at startup when `DEBUG` is on; errors stop the app with a clear message. Built-in checks
|
|
435
|
+
cover URL patterns, middleware entries, and (with `deploy: true`) Django's security warnings.
|
|
436
|
+
Silence ids with `SILENCED_SYSTEM_CHECKS`.
|
|
437
|
+
|
|
438
|
+
## Running on Node
|
|
439
|
+
|
|
440
|
+
```ts
|
|
441
|
+
// src/server.ts
|
|
442
|
+
import { serve } from '@ghuri/core/node'
|
|
443
|
+
import { createApp } from '@ghuri/core'
|
|
444
|
+
import settings from './settings'
|
|
445
|
+
|
|
446
|
+
serve(createApp(settings), { port: 8000, env: process.env })
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
`serve()` uses `@hono/node-server` (install it), passes `env` to the app, provides a `waitUntil`
|
|
450
|
+
shim, and shuts down gracefully on SIGINT/SIGTERM.
|
|
451
|
+
|
|
452
|
+
## Testing
|
|
453
|
+
|
|
454
|
+
```ts
|
|
455
|
+
import { createTestClient } from '@ghuri/core/testing'
|
|
456
|
+
import app from '../src/index'
|
|
457
|
+
|
|
458
|
+
const client = createTestClient(app, { env: { SECRET_KEY: 'test', DEBUG: 'false' } })
|
|
459
|
+
|
|
460
|
+
const res = await client.post('/api/posts/', { json: { title: 'Hi' } })
|
|
461
|
+
expect(res.status).toBe(201)
|
|
462
|
+
expect(await res.json()).toMatchObject({ title: 'Hi' })
|
|
463
|
+
|
|
464
|
+
await client.get('/search/', { query: { q: 'ghuri' }, headers: { accept: 'text/html' } })
|
|
465
|
+
await client.post('/contact/', { form: { email: 'a@b.c', attachment: new File(['x'], 'x.txt') } })
|
|
466
|
+
const followed = await client.get('/old/', { follow: true }) // followed.redirectChain
|
|
467
|
+
await client.forceLogin(user) // provided by @ghuri/auth
|
|
468
|
+
await client.withContext(async () => { /* ORM calls with the app's settings */ })
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
The client keeps cookies between requests and sends the CSRF token automatically on unsafe requests
|
|
472
|
+
(`csrf: false` to test CSRF failures). Requests go to `http://testserver` (change with `baseUrl`). It
|
|
473
|
+
is fetch-based, so it works in Node and in `@cloudflare/vitest-pool-workers`. Packages extend it
|
|
474
|
+
with `registerTestClientHook(name, fn)`.
|
|
475
|
+
|
|
476
|
+
## License
|
|
477
|
+
|
|
478
|
+
MIT
|