Compare commits

...

104 Commits

Author SHA1 Message Date
dswbx 7f8d8d26ac Merge pull request #259 from bknd-io/release/0.17.2
Bugfix Release 0.17.2
2025-09-15 10:15:14 +02:00
dswbx 655bb241a8 bump version to 0.17.2 2025-09-15 10:14:14 +02:00
dswbx 1ef5bf7d15 fix: adjust mcp schema validation and add default path support
Updated `mcp.json` to enhance validation by supporting `anyOf` schema for `entity` properties and refined `role` typing. Introduced default `path` property for MCP system API and aligned build assets configuration accordingly.
2025-09-15 10:09:51 +02:00
dswbx 9a1589da0b bump @bknd/postgres version to 0.2.0 2025-09-15 10:07:34 +02:00
dswbx f231353228 bump version to 0.17.2-rc.1 2025-09-15 09:31:01 +02:00
dswbx d2de642c17 fix: update build config and improve e2e adapter handling
Added dynamic inclusion of dependencies as external packages and switched build platform to browser. Streamlined e2e adapter test setup, improved type safety, and standardized console output for better clarity.
2025-09-15 09:25:32 +02:00
dswbx 50c5383138 Merge pull request #257 from bknd-io/fix/postgres-0.17-updates
postgres: bump 0.17.1 and improve custom connection API
2025-09-14 17:10:32 +02:00
dswbx fff88a9237 Merge pull request #258 from bknd-io/fix/mcp-auth-and-insert
fix: handle numbered object conversion and update MCP tool URL
2025-09-14 17:09:55 +02:00
dswbx d768a80526 Merge pull request #256 from bknd-io/fix/docker-0.17
bump Dockerfile to use bknd 0.17.1
2025-09-14 17:09:34 +02:00
dswbx 0d79b19c66 Merge pull request #255 from bknd-io/fix/node-static-import
fix raw node execution by making sure import attributes stick on builds
2025-09-14 17:08:54 +02:00
dswbx fea2812688 fix: handle numbered object conversion and update MCP tool URL
Add `convertNumberedObjectToArray` utility for handling numbered object to array conversion, addressing MCP tool allOf behavior. Adjust MCP tool URL in configuration and ensure default inspect options in development environment. Minor improvement in role enumeration handling for auth.
2025-09-14 17:03:23 +02:00
dswbx 62368c691a postgres: bump 0.17.1 and improve custom connection API
Aligned connection constructors to include an explicit name parameter, updated documentation, and streamlined connection methods for consistency. Adjusted dependencies and cleaned unused references.
2025-09-14 16:01:37 +02:00
dswbx dd9617598f bump Dockerfile to use bknd 0.17.1
Updated the default bknd version to 0.17.1 and included the `jsonv-ts` dependency in the Dockerfile.
2025-09-14 14:07:56 +02:00
dswbx a7f6d45ca9 fix raw node execution by making sure import attributes stick on builds 2025-09-14 13:43:45 +02:00
dswbx 92656523ff Merge pull request #254 from quicujo/feat/validate-uuid
Add UUID validation utility
2025-09-14 13:19:57 +02:00
anton e6ef7d9ff4 Add UUID validation utility
Add uuidValidate function to validate UUID strings and check their version.
Supports validation for v4 and v7 UUIDs using the uuid library's validate
and version functions.
2025-09-08 05:06:42 +02:00
dswbx 210b22e307 Merge pull request #251 from bknd-io/fix/cf-adapter-exports
cloudflare: fix missing serve export
2025-09-05 09:18:36 +02:00
dswbx 734235c798 cloudflare: fix missing serve export 2025-09-05 09:17:08 +02:00
dswbx c9773d49a6 bump 0.17.1 2025-09-03 17:17:26 +02:00
dswbx c9fb497c2d Merge pull request #246 from bknd-io/fix/mobile-input-zoom
style: fix mobile zoom on input focus/blur
2025-09-03 17:03:14 +02:00
dswbx ccd4eb10cb Merge pull request #245 from bknd-io/fix/cf-instance-flash
cloudflare: fixing multiple instances competing with configuration state by always serving fresh
2025-09-03 17:03:03 +02:00
dswbx 847f75b725 docs: update cloudflare imports 2025-09-03 17:00:24 +02:00
dswbx 8b4bf0d94a style: fix mobile zoom on input focus/blur 2025-09-03 08:28:27 +02:00
dswbx bf521e2931 cloudflare: fixing multiple instances competing with configuration state by always serving fresh 2025-09-03 07:54:40 +02:00
dswbx 111b2ae364 docs: fix generated mcp tools page title 2025-08-30 17:31:22 +02:00
dswbx dc08d12ce6 docs & readme: fix demo 2025-08-30 16:21:46 +02:00
dswbx ce773007f0 readme: update badges 2025-08-30 15:05:46 +02:00
dswbx e78c271c2f readme: added mcp as feature 2025-08-30 15:03:46 +02:00
dswbx 7ee07adc70 v0.17.0 2025-08-30 14:20:25 +02:00
dswbx 53e5c6fd98 Merge pull request #234 from bknd-io/release/0.17
Release 0.17
2025-08-30 14:16:37 +02:00
dswbx 4591631d3c fix e2e tests by forcely setting to be used db 2025-08-30 14:11:08 +02:00
dswbx 5a27c41516 mcp: fix tests changing new default mcp endpoint 2025-08-30 14:08:20 +02:00
dswbx 24eefa5357 mcp: added path config, register at /api path by default to work with frameworks 2025-08-30 14:06:13 +02:00
dswbx d898018b49 mcp ui: add copy on history 2025-08-30 13:41:15 +02:00
dswbx 09fdde1c5b fix mcp auth, styling fixes 2025-08-30 13:31:48 +02:00
dswbx fb0dbb9a51 fix system mcp notification console 2025-08-30 11:19:26 +02:00
dswbx 81f578895e bump version, fix cloudflare export 2025-08-30 10:20:07 +02:00
dswbx 2de12674d9 docs: mcp (#243)
* added mcp documentation

* added mcp docs
2025-08-30 10:15:56 +02:00
dswbx 5ed1cf19b6 docs: plugins, cloudflare, sdk, elements, database (#240)
* docs: added plugins docs, updated cloudflare docs

* updated cli help text

* added `systemEntity` and added docs on how to work with system entities

* docs: added defaults to cloudflare image plugin

* docs: updated sdk and elements
2025-08-29 12:50:23 +02:00
dswbx 5b879ac6bf Merge pull request #242 from bknd-io/feat/cli-global-options
cli: align config aware commands options
2025-08-29 09:41:52 +02:00
dswbx c04ad89a86 cli: align config aware commands options 2025-08-29 09:40:27 +02:00
dswbx 93019827b0 cli: updated config to get config from app, added sync command (#241)
* cli: updated config to get config from app, added sync command

* updated command description
2025-08-29 08:40:14 +02:00
dswbx 9436b8bac5 cloudflare: enable fs with @cloudflare/vite-plugin (#239)
* init dev vite write plugin

* reorganized cf proxy, fixed dev write
2025-08-29 06:44:20 +02:00
dswbx 8f471a29b0 json viewer: updated size display 2025-08-28 19:35:32 +02:00
dswbx dcf88cf587 mcp: improve auth id type + styling fixes 2025-08-21 10:58:31 +02:00
dswbx f9184a71db Merge pull request #225 from bknd-io/feat/mcp
initialized mcp support
2025-08-20 19:14:05 +02:00
dswbx bc1ab0f6d3 mcp: sorting tools, fixed cloudflare example, fixed some styling 2025-08-20 18:26:48 +02:00
dswbx 0b21157f92 Merge pull request #237 from bknd-io/docs/fix-nextjs-and-events
docs: fixed events, commented edge runtime for nextjs
2025-08-20 17:06:35 +02:00
dswbx cacb13e464 docs: fixed events, commented edge runtime for nextjs 2025-08-20 16:05:56 +02:00
dswbx 8ec03afbe8 fix mcp ui heights 2025-08-20 15:45:03 +02:00
dswbx ab8be017c1 updated docs mcp tools 2025-08-15 10:28:04 +02:00
dswbx 5c28511fe6 added getMcpClient to app 2025-08-15 10:27:05 +02:00
dswbx deb8aacca4 added mcp ui as tool 2025-08-15 10:12:09 +02:00
dswbx aafd333d12 fix form isRequired utils and test 2025-08-14 16:56:12 +02:00
dswbx 9e0eaf42e5 fix jsonv-ts version 2025-08-14 16:52:22 +02:00
dswbx 63254de13a added a simple mcp ui in tests 2025-08-14 16:49:31 +02:00
dswbx 9ac5fa03c6 optimized performance 2025-08-14 10:05:15 +02:00
dswbx 70f0240da5 mcp: added auth tests, updated data tests 2025-08-12 22:13:09 +02:00
dswbx a6ed74d904 added mcp tests for media 2025-08-12 20:57:13 +02:00
dswbx bd3d2ea900 added data mcp tests 2025-08-12 20:22:38 +02:00
dswbx 871cec9251 Merge remote-tracking branch 'origin/release/0.17' into feat/mcp
# Conflicts:
#	app/src/data/AppData.ts
#	app/src/data/server/query.ts
#	examples/cloudflare-worker/src/index.ts
2025-08-12 16:17:26 +02:00
dswbx 97d6af3792 cleaned up left over bknd/utils imports (#235) 2025-08-12 16:12:10 +02:00
dswbx 725a2d453a adapter(cf): fix exports and type name for do db (#232) 2025-08-12 15:30:45 +02:00
dswbx 375d2c205f adapter(cloudflare): removed durable mode, added withPlatformProxy (#233)
* removed `durable` mode as it requires an import from "cloudflare:" that often fails in non-cf environments

* remove worker configuration types

* add `withPlatformProxy`

* withPlatformProxy: make configuration optional
2025-08-12 15:29:09 +02:00
dswbx f40ea0ec5b init mcp data tests, added crud for $record 2025-08-12 12:55:14 +02:00
dswbx 1e8c373dd4 added mcp server tests 2025-08-12 09:17:38 +02:00
dswbx 2e145bbf95 init mcp tools test 2025-08-12 08:51:32 +02:00
dswbx 822e6fd644 fix tools when auth is disabled + log notifications to console 2025-08-09 15:07:20 +02:00
dswbx ad04d5273e docs: update tools, test bun 2025-08-09 14:23:11 +02:00
dswbx c1c23d24fe switch to node api for generate-mcp for cf builds 2025-08-09 14:18:44 +02:00
dswbx 06300427cb update jsonv-ts, fixed tests 2025-08-09 14:16:51 +02:00
dswbx cb873381f1 auto generated tools docs, added stdio transport, added additional mcp config and permissions 2025-08-09 14:14:51 +02:00
dswbx b5b4c5eef0 Merge pull request #231 from DimplesY/main
fix: add missing @clack/prompts dependency
2025-08-08 13:37:53 +02:00
Dimples_YJ 7af8e09468 fix: add missing @clack/prompts dependency 2025-08-08 13:51:12 +08:00
dswbx 170ea2c45b added additional permissions, implemented mcp authentication 2025-08-07 15:20:29 +02:00
dswbx 42db5f55c7 added authentication, $schema, fixed media adapter mcp 2025-08-07 11:33:46 +02:00
dswbx 1b02feca93 added mcp tools from routes 2025-08-07 08:36:12 +02:00
dswbx fd966b6aef Merge pull request #230 from stormbyte/main
Update Dockerfile to node 24
2025-08-06 20:01:54 +02:00
stormbyte 6bed2e4fca Update to node 24 2025-08-06 16:06:03 +02:00
dswbx dfb1457dfa Merge pull request #229 from DimplesY/main
docs: fix <Admin /> config props
2025-08-06 10:00:33 +02:00
Jie 4f945842a9 docs: update astro.mdx 2025-08-06 15:52:05 +08:00
Jie 44fdfcc8d9 docs: Correct the incorrect value of the config attribute in the admin component 2025-08-06 15:19:28 +08:00
dswbx 07810ff63c Merge remote-tracking branch 'origin/main' into feat/mcp
# Conflicts:
#	app/package.json
#	bun.lock
2025-08-06 08:44:46 +02:00
dswbx 143d6a55ff updated lock to 0.16.1 2025-08-06 08:31:19 +02:00
dswbx 8fa905a8f1 docs: adding poster to assets (#228)
* docs: adding poster to assets

* readme: fix poster image
2025-08-06 08:29:46 +02:00
dswbx ad0d2e6ff8 add jsonv-ts as dependency for type inference, fix media api types (#227)
* add jsonv-ts as dependency for type inference, fix media api types

* add jsonv-ts as dependency for type inference, fix media api types

* add jsonv-ts as dependency for type inference, fix media api types
2025-08-06 08:21:17 +02:00
dswbx aa0e6f90d9 examples: fixing imports due to 0.16 (#226) 2025-08-06 08:19:29 +02:00
dswbx 3e2938f77d added initial $record 2025-08-05 13:20:00 +02:00
dswbx 5e5f0ef70f fixing jsonv-ts imports 2025-08-02 16:47:24 +02:00
dswbx 104885ea5c fix tests failing because of new module ctx 2025-08-02 16:36:23 +02:00
dswbx ffbb61d58a initialized mcp support 2025-08-02 16:33:05 +02:00
dswbx bd48bb7a18 v0.16 2025-08-01 16:03:23 +02:00
dswbx a298b65abf Release 0.16 (#196)
* initial refactor

* fixes

* test secrets extraction

* updated lock

* fix secret schema

* updated schemas, fixed tests, skipping flow tests for now

* added validator for rjsf, hook form via standard schema

* removed @sinclair/typebox

* remove unneeded vite dep

* fix jsonv literal on Field.tsx

* fix schema import path

* fix schema modals

* fix schema modals

* fix json field form, replaced auth form

* initial waku

* finalize waku example

* fix jsonv-ts version

* fix schema updates with falsy values

* fix media api to respect options' init, improve types

* checking media controller test

* checking media controller test

* checking media controller test

* clean up mediacontroller test

* added cookie option `partitioned`, as well as cors `origin` to be array, option to enable `credentials` (#214)

* added cookie option `partitioned`, as well as cors `origin` to be array, option to enable `credentials`

* fix server test

* fix data api (updated jsonv-ts)

* enhance cloudflare image optimization plugin with new options and explain endpoint (#215)

* feat: add ability to serve static by using dynamic imports (#197)

* feat: add ability to serve static by using dynamic imports

* serveStaticViaImport: make manifest optional

* serveStaticViaImport: add error log

* refactor/imports (#217)

* refactored core and core/utils imports

* refactored core and core/utils imports

* refactored media imports

* refactored auth imports

* refactored data imports

* updated package json exports, fixed mm config

* fix tests

* feat/deno (#219)

* update bun version

* fix module manager's em reference

* add basic deno example

* finalize

* docs: fumadocs migration (#185)

* feat(docs): initialize documentation structure with Fumadocs

* feat(docs): remove home route and move /docs route to /route

* feat(docs): add redirect to /start page

* feat(docs): migrate Getting Started chapters

* feat(docs): migrate Usage and Extending chapters

* feat(callout): add CalloutCaution, CalloutDanger, CalloutInfo, and CalloutPositive

* feat(layout): add Discord and GitHub links to documentation layout

* feat(docs): add integration chapters draft

* feat(docs): add modules chapters draft

* refactor(mdx-components): remove unused Icon import

* refactor(StackBlitz): enhance type safety by using unknown instead of any

* refactor(layout): update navigation mode to 'top' in layout configuration

* feat(docs): add @iconify/react package

* docs(mdx-components): add Icon component to MDX components list

* feat(docs): update Next.js integration guide

* feat(docs): update React Router integration guide

* feat(docs): update Astro integration guide

* feat(docs): update Vite integration guide

* fix(docs): update package manager initialization commands

* feat(docs): migrate Modules chapters

* chore(docs): update package.json with new devDependencies

* feat(docs): migrate Integration Runtimes chapters

* feat(docs): update Database usage chapter

* feat(docs): restructure documentation paths

* chore(docs): clean up unused imports and files in documentation

* style(layout): revert navigation mode to previous state

* fix(docs): routing for documentation structure

* feat(openapi): add API documentation generation from OpenAPI schema

* feat(docs): add icons to documentation pages

* chore(dependencies): remove unused content-collections packages

* fix(types): fix type error for attachFile in source.ts

* feat(redirects): update root redirect destination to '/start'

* feat(search): add static search functionality

* chore(dependencies): update fumadocs-core and fumadocs-ui to latest versions

* feat(search): add Powered by Orama link

* feat(generate-openapi): add error handling for missing OpenAPI schema

* feat(scripts): add OpenAPI generation to build process

* feat(config): enable dynamic redirects and rewrites in development mode

* feat(layout): add GitHub token support for improved API rate limits

* feat(redirects): add 301 redirects for cloudflare pages

* feat(docs): add Vercel redirects configuration

* feat(config): enable standalone output for development environment

* chore(layout): adjust layout settings

* refactor(package): clean up ajv dependency versions

* feat(docs): add twoslash support

* refactor(layout): update DocsLayout import and navigation configuration

* chore(layout): clean up layout.tsx by commenting out GithubInfo

* fix(Search): add locale to search initialization

* chore(package): update fumadocs and orama to latest versions

* docs: add menu items descriptions

* feat(layout): add GitHub URL to the layout component

* feat(docs): add AutoTypeTable component to MDX components

* feat(app): implement AutoTypeTable rendering for AppEvents type

* docs(layout): switch callouts back to default components

* fix(config): use __filename and __dirname for module paths

* docs: add note about node.js 22 requirement

* feat(styles): add custom color variables for light and dark themes

* docs: add S3 setup instructions for media module

* docs: fix typos and indentation in media module docs

* docs: add local media adapter example for Node.js

* docs(media): add S3/R2 URL format examples and fix typo

* docs: add cross-links to initial config and seeding sections

* indent numbered lists content, clarified media serve locations

* fix mediacontroller tests

* feat(layout): add AnimatedGridPattern component for dynamic background

* style(layout): configure fancy ToC style ('clerk')

* fix(AnimatedGridPattern): correct strokeDasharray type

* docs: actualize docs

* feat: add favicon

* style(cloudflare): format code examples

* feat(layout): add Github and Discord footer icons

* feat(footer): add SVG social media icons for GitHub and Discord

* docs: adjusted auto type table, added llm functions

* added static deployment to cloudflare workers

* docs: change cf redirects to proxy *.mdx instead of redirecting

---------

Co-authored-by: dswbx <dennis.senn@gmx.ch>
Co-authored-by: cameronapak <cameronandrewpak@gmail.com>

* build: improve build script

* add missing exports, fix EntityTypescript imports

* media: Dropzone: add programmatic upload, additional events, loading state

* schema object: disable extended defaults to allow empty config values

* Feat/new docs deploy (#224)

* test

* try fixing pm

* try fixing pm

* fix docs on imports, export events correctly

---------

Co-authored-by: Tim Seriakov <59409712+timseriakov@users.noreply.github.com>
Co-authored-by: cameronapak <cameronandrewpak@gmail.com>
2025-08-01 15:55:59 +02:00
dswbx daaaae82b6 Merge pull request #203 from bknd-io/fix/auth-redirect-and-adapter-config
fix auth redirect on error and adapter app fn
2025-07-19 09:15:23 +02:00
dswbx 79ace4f1e5 Merge pull request #206 from cameronapak/main
docs: add documentation on S3 integration
2025-07-19 09:13:20 +02:00
dswbx f19977ac28 fix mediacontroller tests 2025-07-19 09:12:28 +02:00
dswbx a3782728f9 indent numbered lists content, clarified media serve locations 2025-07-19 08:39:19 +02:00
cameronapak 8b832f02ac docs: add cross-links to initial config and seeding sections 2025-07-16 23:03:38 -05:00
cameronapak cec32ae881 docs(media): add S3/R2 URL format examples and fix typo 2025-07-16 22:57:15 -05:00
cameronapak 0fffa26d55 docs: add local media adapter example for Node.js 2025-07-16 22:47:09 -05:00
cameronapak 2b6f520f46 docs: fix typos and indentation in media module docs 2025-07-16 22:41:55 -05:00
cameronapak 7379bf2b1b docs: add S3 setup instructions for media module 2025-07-16 22:38:36 -05:00
dswbx db3c2cea10 docs: add note about node.js 22 requirement 2025-07-11 12:49:35 +02:00
dswbx 2b32a836cd auth error should not redirect to parameter, adapter app function should fire correctly 2025-07-09 08:00:52 +02:00
548 changed files with 24586 additions and 13263 deletions
+7
View File
@@ -0,0 +1,7 @@
{
"mcpServers": {
"bknd": {
"url": "http://localhost:28623/api/system/mcp"
}
}
}
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
- name: Setup Bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: oven-sh/setup-bun@v1
with: with:
bun-version: "1.2.14" bun-version: "1.2.19"
- name: Install dependencies - name: Install dependencies
working-directory: ./app working-directory: ./app
+3 -1
View File
@@ -31,4 +31,6 @@ packages/media/.env
.git_old .git_old
docker/tmp docker/tmp
.debug .debug
.history .history
.aider*
.vercel
+6 -5
View File
@@ -1,9 +1,9 @@
[![npm version](https://img.shields.io/npm/v/bknd.svg)](https://npmjs.org/package/bknd) [![npm version](https://img.shields.io/npm/v/bknd.svg)](https://npmjs.org/package/bknd)
![bknd](https://raw.githubusercontent.com/bknd-io/bknd/refs/heads/main/docs/_assets/poster.png) ![bknd](https://raw.githubusercontent.com/bknd-io/bknd/refs/heads/main/docs/public/assets/poster.png)
<p align="center" width="100%"> <p align="center" width="100%">
<a href="https://stackblitz.com/github/bknd-io/bknd-examples?hideExplorer=1&embed=1&view=preview&startScript=example-admin-rich&initialPath=%2Fdata%2Fschema" target="_blank"> <a href="https://stackblitz.com/github/bknd-io/bknd-demo?hideExplorer=1&embed=1&view=preview&initialPath=%2Fdata%2Fschema" target="_blank">
<strong>⭐ Live Demo</strong> <strong>⭐ Live Demo</strong>
</a> </a>
</p> </p>
@@ -19,7 +19,7 @@ bknd simplifies app development by providing a fully functional backend for data
**For documentation and examples, please visit https://docs.bknd.io.** **For documentation and examples, please visit https://docs.bknd.io.**
> [!WARNING] > [!WARNING]
> This project requires Node.js 22 or higher (because of `node:sqlite`). > This project requires Node.js 22.13 or higher (because of `node:sqlite`).
> >
> Please keep in mind that **bknd** is still under active development > Please keep in mind that **bknd** is still under active development
> and therefore full backward compatibility is not guaranteed before reaching v1.0.0. > and therefore full backward compatibility is not guaranteed before reaching v1.0.0.
@@ -27,8 +27,8 @@ bknd simplifies app development by providing a fully functional backend for data
## Size ## Size
![gzipped size of bknd](https://img.shields.io/bundlejs/size/bknd?label=bknd) ![gzipped size of bknd](https://img.shields.io/bundlejs/size/bknd?label=bknd)
![gzipped size of bknd/client](https://img.badgesize.io/https://unpkg.com/bknd@latest/dist/ui/client/index.js?compression=gzip&label=bknd/client) ![gzipped size of bknd/client](https://img.badgesize.io/https://unpkg.com/bknd@latest/dist/ui/client/index.js?compression=gzip&label=bknd/client)
![gzipped size of bknd/elements](https://img.badgesize.io/https://unpkg.com/bknd@latest/dist/ui/elements/index.js?compression=gzip&label=bknd/elements) ![gzipped size of bknd/elements](https://img.badgesize.io/https://unpkg.com/bknd@latest/dist/ui/elements/index.js?compression=gzip&label=bknd/elements&t=1)
![gzipped size of bknd/ui](https://img.badgesize.io/https://unpkg.com/bknd@latest/dist/ui/index.js?compression=gzip&label=bknd/ui) ![gzipped size of bknd/ui](https://img.badgesize.io/https://unpkg.com/bknd@latest/dist/ui/index.js?compression=gzip&label=bknd/ui&t=1)
The size on npm is misleading, as the `bknd` package includes the backend, the ui components as well as the whole backend bundled into the cli including static assets. The size on npm is misleading, as the `bknd` package includes the backend, the ui components as well as the whole backend bundled into the cli including static assets.
@@ -52,6 +52,7 @@ Creating digital products always requires developing both the backend (the logic
* using a React framework (Next.js, React Router, Astro) * using a React framework (Next.js, React Router, Astro)
* 📦 Official API and React SDK with type-safety * 📦 Official API and React SDK with type-safety
* ⚛️ React elements for auto-configured authentication and media components * ⚛️ React elements for auto-configured authentication and media components
* 🛠️ MCP server, client and UI built-in to control your backend
## Structure ## Structure
The package is mainly split into 4 parts, each serving a specific purpose: The package is mainly split into 4 parts, each serving a specific purpose:
+2 -1
View File
@@ -1 +1,2 @@
tmp/* tmp/*
!tmp/.gitkeep
+6 -6
View File
@@ -9,16 +9,16 @@ beforeAll(disableConsoleLog);
afterAll(enableConsoleLog); afterAll(enableConsoleLog);
describe("adapter", () => { describe("adapter", () => {
it("makes config", () => { it("makes config", async () => {
expect(omitKeys(adapter.makeConfig({}), ["connection"])).toEqual({}); expect(omitKeys(await adapter.makeConfig({}), ["connection"])).toEqual({});
expect(omitKeys(adapter.makeConfig({}, { env: { TEST: "test" } }), ["connection"])).toEqual( expect(
{}, omitKeys(await adapter.makeConfig({}, { env: { TEST: "test" } }), ["connection"]),
); ).toEqual({});
// merges everything returned from `app` with the config // merges everything returned from `app` with the config
expect( expect(
omitKeys( omitKeys(
adapter.makeConfig( await adapter.makeConfig(
{ app: (a) => ({ initialConfig: { server: { cors: { origin: a.env.TEST } } } }) }, { app: (a) => ({ initialConfig: { server: { cors: { origin: a.env.TEST } } } }) },
{ env: { TEST: "test" } }, { env: { TEST: "test" } },
), ),
+3 -3
View File
@@ -1,12 +1,12 @@
import { afterAll, beforeAll, describe, expect, it } from "bun:test"; import { afterAll, beforeAll, describe, expect, it } from "bun:test";
import { Guard } from "../../src/auth"; import { Guard } from "../../src/auth/authorize/Guard";
import { parse } from "../../src/core/utils";
import { DataApi } from "../../src/data/api/DataApi"; import { DataApi } from "../../src/data/api/DataApi";
import { DataController } from "../../src/data/api/DataController"; import { DataController } from "../../src/data/api/DataController";
import { dataConfigSchema } from "../../src/data/data-schema"; import { dataConfigSchema } from "../../src/data/data-schema";
import * as proto from "../../src/data/prototype"; import * as proto from "../../src/data/prototype";
import { schemaToEm } from "../helper"; import { schemaToEm } from "../helper";
import { disableConsoleLog, enableConsoleLog } from "core/utils/test"; import { disableConsoleLog, enableConsoleLog } from "core/utils/test";
import { parse } from "core/utils/schema";
beforeAll(disableConsoleLog); beforeAll(disableConsoleLog);
afterAll(enableConsoleLog); afterAll(enableConsoleLog);
@@ -202,7 +202,7 @@ describe("DataApi", () => {
{ {
// create many // create many
const res = await api.createMany("posts", payload); const res = await api.createMany("posts", payload);
expect(res.data.length).toEqual(4); expect(res.data?.length).toEqual(4);
expect(res.ok).toBeTrue(); expect(res.ok).toBeTrue();
} }
+18
View File
@@ -20,6 +20,7 @@ describe("App", () => {
"guard", "guard",
"flags", "flags",
"logger", "logger",
"mcp",
"helper", "helper",
]); ]);
}, },
@@ -135,4 +136,21 @@ describe("App", () => {
// expect async listeners to be executed sync after request // expect async listeners to be executed sync after request
expect(called).toHaveBeenCalled(); expect(called).toHaveBeenCalled();
}); });
test("getMcpClient", async () => {
const app = createApp({
initialConfig: {
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
const client = app.getMcpClient();
const res = await client.listTools();
expect(res).toBeDefined();
expect(res?.tools.length).toBeGreaterThan(0);
});
}); });
+45
View File
@@ -0,0 +1,45 @@
import { AppServer, serverConfigSchema } from "modules/server/AppServer";
import { describe, test, expect } from "bun:test";
describe("AppServer", () => {
test("config", () => {
{
const server = new AppServer();
expect(server).toBeDefined();
expect(server.config).toEqual({
cors: {
allow_credentials: true,
origin: "*",
allow_methods: ["GET", "POST", "PATCH", "PUT", "DELETE"],
allow_headers: ["Content-Type", "Content-Length", "Authorization", "Accept"],
},
mcp: {
enabled: false,
path: "/api/system/mcp",
},
});
}
{
const server = new AppServer({
cors: {
origin: "https",
allow_methods: ["GET", "POST"],
},
});
expect(server).toBeDefined();
expect(server.config).toEqual({
cors: {
allow_credentials: true,
origin: "https",
allow_methods: ["GET", "POST"],
allow_headers: ["Content-Type", "Content-Length", "Authorization", "Accept"],
},
mcp: {
enabled: false,
path: "/api/system/mcp",
},
});
}
});
});
+226
View File
@@ -0,0 +1,226 @@
import { describe, test, expect, beforeEach, beforeAll, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
import type { McpServer } from "bknd/utils";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
/**
* - [x] auth_me
* - [x] auth_strategies
* - [x] auth_user_create
* - [x] auth_user_token
* - [x] auth_user_password_change
* - [x] auth_user_password_test
* - [x] config_auth_get
* - [x] config_auth_update
* - [x] config_auth_strategies_get
* - [x] config_auth_strategies_add
* - [x] config_auth_strategies_update
* - [x] config_auth_strategies_remove
* - [x] config_auth_roles_get
* - [x] config_auth_roles_add
* - [x] config_auth_roles_update
* - [x] config_auth_roles_remove
*/
describe("mcp auth", async () => {
let app: App;
let server: McpServer;
beforeEach(async () => {
app = createApp({
initialConfig: {
auth: {
enabled: true,
jwt: {
secret: "secret",
},
},
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
server = app.mcp!;
server.setLogLevel("error");
server.onNotification((message) => {
console.dir(message, { depth: null });
});
});
const tool = createMcpToolCaller();
test("auth_*", async () => {
const me = await tool(server, "auth_me", {});
expect(me.user).toBeNull();
// strategies
const strategies = await tool(server, "auth_strategies", {});
expect(Object.keys(strategies.strategies).length).toEqual(1);
expect(strategies.strategies.password.enabled).toBe(true);
// create user
const user = await tool(
server,
"auth_user_create",
{
email: "test@test.com",
password: "12345678",
},
new Headers(),
);
expect(user.email).toBe("test@test.com");
// create token
const token = await tool(
server,
"auth_user_token",
{
email: "test@test.com",
},
new Headers(),
);
expect(token.token).toBeDefined();
expect(token.user.email).toBe("test@test.com");
// me
const me2 = await tool(
server,
"auth_me",
{},
new Request("http://localhost", {
headers: new Headers({
Authorization: `Bearer ${token.token}`,
}),
}),
);
expect(me2.user.email).toBe("test@test.com");
// change password
const changePassword = await tool(
server,
"auth_user_password_change",
{
email: "test@test.com",
password: "87654321",
},
new Headers(),
);
expect(changePassword.changed).toBe(true);
// test password
const testPassword = await tool(
server,
"auth_user_password_test",
{
email: "test@test.com",
password: "87654321",
},
new Headers(),
);
expect(testPassword.valid).toBe(true);
});
test("config_auth_{get,update}", async () => {
expect(await tool(server, "config_auth_get", {})).toEqual({
path: "",
secrets: false,
partial: false,
value: app.toJSON().auth,
});
// update
await tool(server, "config_auth_update", {
value: {
allow_register: false,
},
});
expect(app.toJSON().auth.allow_register).toBe(false);
});
test("config_auth_strategies_{get,add,update,remove}", async () => {
const strategies = await tool(server, "config_auth_strategies_get", {
key: "password",
});
expect(strategies).toEqual({
secrets: false,
module: "auth",
key: "password",
value: {
enabled: true,
type: "password",
},
});
// add google oauth
const addGoogleOauth = await tool(server, "config_auth_strategies_add", {
key: "google",
value: {
type: "oauth",
enabled: true,
config: {
name: "google",
type: "oidc",
client: {
client_id: "client_id",
client_secret: "client_secret",
},
},
},
return_config: true,
});
expect(addGoogleOauth.config.google.enabled).toBe(true);
expect(app.toJSON().auth.strategies.google?.enabled).toBe(true);
// update (disable) google oauth
await tool(server, "config_auth_strategies_update", {
key: "google",
value: {
enabled: false,
},
});
expect(app.toJSON().auth.strategies.google?.enabled).toBe(false);
// remove google oauth
await tool(server, "config_auth_strategies_remove", {
key: "google",
});
expect(app.toJSON().auth.strategies.google).toBeUndefined();
});
test("config_auth_roles_{get,add,update,remove}", async () => {
// add role
const addGuestRole = await tool(server, "config_auth_roles_add", {
key: "guest",
value: {
permissions: ["read", "write"],
},
return_config: true,
});
expect(addGuestRole.config.guest.permissions).toEqual(["read", "write"]);
// update role
await tool(server, "config_auth_roles_update", {
key: "guest",
value: {
permissions: ["read"],
},
});
expect(app.toJSON().auth.roles?.guest?.permissions).toEqual(["read"]);
// get role
const getGuestRole = await tool(server, "config_auth_roles_get", {
key: "guest",
});
expect(getGuestRole.value.permissions).toEqual(["read"]);
// remove role
await tool(server, "config_auth_roles_remove", {
key: "guest",
});
expect(app.toJSON().auth.roles?.guest).toBeUndefined();
});
});
+35
View File
@@ -0,0 +1,35 @@
import { describe, it, expect } from "bun:test";
import { createApp } from "core/test/utils";
import { registries } from "index";
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
describe("mcp", () => {
it("should have tools", async () => {
registries.media.register("local", StorageLocalAdapter);
const app = createApp({
initialConfig: {
auth: {
enabled: true,
},
media: {
enabled: true,
adapter: {
type: "local",
config: {
path: "./",
},
},
},
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
expect(app.mcp?.tools.length).toBeGreaterThan(0);
});
});
+346
View File
@@ -0,0 +1,346 @@
import { describe, test, expect, beforeEach, beforeAll, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import { getSystemMcp } from "modules/mcp/system-mcp";
import { pickKeys, type McpServer } from "bknd/utils";
import { entity, text } from "bknd";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
/**
* - [ ] data_sync
* - [x] data_entity_fn_count
* - [x] data_entity_fn_exists
* - [x] data_entity_read_one
* - [x] data_entity_read_many
* - [x] data_entity_insert
* - [x] data_entity_update_many
* - [x] data_entity_update_one
* - [x] data_entity_delete_one
* - [x] data_entity_delete_many
* - [x] data_entity_info
* - [ ] config_data_get
* - [ ] config_data_update
* - [x] config_data_entities_get
* - [x] config_data_entities_add
* - [x] config_data_entities_update
* - [x] config_data_entities_remove
* - [x] config_data_relations_add
* - [x] config_data_relations_get
* - [x] config_data_relations_update
* - [x] config_data_relations_remove
* - [x] config_data_indices_get
* - [x] config_data_indices_add
* - [x] config_data_indices_update
* - [x] config_data_indices_remove
*/
describe("mcp data", async () => {
let app: App;
let server: McpServer;
beforeEach(async () => {
const time = performance.now();
app = createApp({
initialConfig: {
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
server = app.mcp!;
server.setLogLevel("error");
server.onNotification((message) => {
console.dir(message, { depth: null });
});
});
const tool = createMcpToolCaller();
test("config_data_entities_{add,get,update,remove}", async () => {
const result = await tool(server, "config_data_entities_add", {
key: "test",
return_config: true,
value: {},
});
expect(result.success).toBe(true);
expect(result.module).toBe("data");
expect(result.config.test?.type).toEqual("regular");
const entities = Object.keys(app.toJSON().data.entities ?? {});
expect(entities).toContain("test");
{
// get
const result = await tool(server, "config_data_entities_get", {
key: "test",
});
expect(result.module).toBe("data");
expect(result.key).toBe("test");
expect(result.value.type).toEqual("regular");
}
{
// update
const result = await tool(server, "config_data_entities_update", {
key: "test",
return_config: true,
value: {
config: {
name: "Test",
},
},
});
expect(result.success).toBe(true);
expect(result.module).toBe("data");
expect(result.config.test.config?.name).toEqual("Test");
expect(app.toJSON().data.entities?.test?.config?.name).toEqual("Test");
}
{
// remove
const result = await tool(server, "config_data_entities_remove", {
key: "test",
});
expect(result.success).toBe(true);
expect(result.module).toBe("data");
expect(app.toJSON().data.entities?.test).toBeUndefined();
}
});
test("config_data_relations_{add,get,update,remove}", async () => {
// create posts and comments
await tool(server, "config_data_entities_add", {
key: "posts",
value: {},
});
await tool(server, "config_data_entities_add", {
key: "comments",
value: {},
});
expect(Object.keys(app.toJSON().data.entities ?? {})).toEqual(["posts", "comments"]);
// create relation
await tool(server, "config_data_relations_add", {
key: "", // doesn't matter
value: {
type: "n:1",
source: "comments",
target: "posts",
},
});
const config = app.toJSON().data;
expect(
pickKeys((config.relations?.n1_comments_posts as any) ?? {}, ["type", "source", "target"]),
).toEqual({
type: "n:1",
source: "comments",
target: "posts",
});
expect(config.entities?.comments?.fields?.posts_id?.type).toBe("relation");
{
// info
const postsInfo = await tool(server, "data_entity_info", {
entity: "posts",
});
expect(postsInfo.fields).toEqual(["id"]);
expect(postsInfo.relations.all.length).toBe(1);
const commentsInfo = await tool(server, "data_entity_info", {
entity: "comments",
});
expect(commentsInfo.fields).toEqual(["id", "posts_id"]);
expect(commentsInfo.relations.all.length).toBe(1);
}
// update
await tool(server, "config_data_relations_update", {
key: "n1_comments_posts",
value: {
config: {
with_limit: 10,
},
},
});
expect((app.toJSON().data.relations?.n1_comments_posts?.config as any)?.with_limit).toBe(10);
// delete
await tool(server, "config_data_relations_remove", {
key: "n1_comments_posts",
});
expect(app.toJSON().data.relations?.n1_comments_posts).toBeUndefined();
});
test("config_data_indices_update", async () => {
expect(server.tools.map((t) => t.name).includes("config_data_indices_update")).toBe(false);
});
test("config_data_indices_{add,get,remove}", async () => {
// create posts and comments
await tool(server, "config_data_entities_add", {
key: "posts",
value: entity("posts", {
title: text(),
content: text(),
}).toJSON(),
});
// add index on title
await tool(server, "config_data_indices_add", {
key: "", // auto generated
value: {
entity: "posts",
fields: ["title"],
},
});
expect(app.toJSON().data.indices?.idx_posts_title).toEqual({
entity: "posts",
fields: ["title"],
unique: false,
});
// delete
await tool(server, "config_data_indices_remove", {
key: "idx_posts_title",
});
expect(app.toJSON().data.indices?.idx_posts_title).toBeUndefined();
});
test("data_entity_*", async () => {
// create posts and comments
await tool(server, "config_data_entities_add", {
key: "posts",
value: entity("posts", {
title: text(),
content: text(),
}).toJSON(),
});
await tool(server, "config_data_entities_add", {
key: "comments",
value: entity("comments", {
content: text(),
}).toJSON(),
});
// insert a few posts
for (let i = 0; i < 10; i++) {
await tool(server, "data_entity_insert", {
entity: "posts",
json: {
title: `Post ${i}`,
},
});
}
// insert a few comments
for (let i = 0; i < 5; i++) {
await tool(server, "data_entity_insert", {
entity: "comments",
json: {
content: `Comment ${i}`,
},
});
}
const result = await tool(server, "data_entity_read_many", {
entity: "posts",
limit: 5,
});
expect(result.data.length).toBe(5);
expect(result.meta.items).toBe(5);
expect(result.meta.total).toBe(10);
expect(result.data[0].title).toBe("Post 0");
{
// count
const result = await tool(server, "data_entity_fn_count", {
entity: "posts",
});
expect(result.count).toBe(10);
}
{
// exists
const res = await tool(server, "data_entity_fn_exists", {
entity: "posts",
json: {
id: result.data[0].id,
},
});
expect(res.exists).toBe(true);
const res2 = await tool(server, "data_entity_fn_exists", {
entity: "posts",
json: {
id: "123",
},
});
expect(res2.exists).toBe(false);
}
// update
await tool(server, "data_entity_update_one", {
entity: "posts",
id: result.data[0].id,
json: {
title: "Post 0 updated",
},
});
const result2 = await tool(server, "data_entity_read_one", {
entity: "posts",
id: result.data[0].id,
});
expect(result2.data.title).toBe("Post 0 updated");
// delete the second post
await tool(server, "data_entity_delete_one", {
entity: "posts",
id: result.data[1].id,
});
const result3 = await tool(server, "data_entity_read_many", {
entity: "posts",
limit: 2,
});
expect(result3.data.map((p) => p.id)).toEqual([1, 3]);
// update many
await tool(server, "data_entity_update_many", {
entity: "posts",
update: {
title: "Post updated",
},
where: {
title: { $isnull: 0 },
},
});
const result4 = await tool(server, "data_entity_read_many", {
entity: "posts",
limit: 10,
});
expect(result4.data.length).toBe(9);
expect(result4.data.map((p) => p.title)).toEqual(
Array.from({ length: 9 }, () => "Post updated"),
);
// delete many
await tool(server, "data_entity_delete_many", {
entity: "posts",
json: {
title: { $isnull: 0 },
},
});
const result5 = await tool(server, "data_entity_read_many", {
entity: "posts",
limit: 10,
});
expect(result5.data.length).toBe(0);
expect(result5.meta.items).toBe(0);
expect(result5.meta.total).toBe(0);
});
});
+118
View File
@@ -0,0 +1,118 @@
import { describe, test, expect, beforeAll, beforeEach, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import { getSystemMcp } from "modules/mcp/system-mcp";
import { registries } from "index";
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
import { disableConsoleLog, enableConsoleLog } from "core/utils";
import type { McpServer } from "bknd/utils";
beforeAll(disableConsoleLog);
afterAll(enableConsoleLog);
/**
* - [x] config_media_get
* - [x] config_media_update
* - [x] config_media_adapter_get
* - [x] config_media_adapter_update
*/
describe("mcp media", async () => {
let app: App;
let server: McpServer;
beforeEach(async () => {
registries.media.register("local", StorageLocalAdapter);
app = createApp({
initialConfig: {
media: {
enabled: true,
adapter: {
type: "local",
config: {
path: "./",
},
},
},
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
server = app.mcp!;
server.setLogLevel("error");
server.onNotification((message) => {
console.dir(message, { depth: null });
});
});
const tool = createMcpToolCaller();
test("config_media_{get,update}", async () => {
const result = await tool(server, "config_media_get", {});
expect(result).toEqual({
path: "",
secrets: false,
partial: false,
value: app.toJSON().media,
});
// partial
expect((await tool(server, "config_media_get", { path: "adapter" })).value).toEqual({
type: "local",
config: {
path: "./",
},
});
// update
await tool(server, "config_media_update", {
value: {
storage: {
body_max_size: 1024 * 1024 * 10,
},
},
return_config: true,
});
expect(app.toJSON().media.storage.body_max_size).toBe(1024 * 1024 * 10);
});
test("config_media_adapter_{get,update}", async () => {
const result = await tool(server, "config_media_adapter_get", {});
expect(result).toEqual({
secrets: false,
value: app.toJSON().media.adapter,
});
// update
await tool(server, "config_media_adapter_update", {
value: {
type: "local",
config: {
path: "./subdir",
},
},
});
const adapter = app.toJSON().media.adapter as any;
expect(adapter.config.path).toBe("./subdir");
expect(adapter.type).toBe("local");
// set to s3
{
await tool(server, "config_media_adapter_update", {
value: {
type: "s3",
config: {
access_key: "123",
secret_access_key: "456",
url: "https://example.com/what",
},
},
});
const adapter = app.toJSON(true).media.adapter as any;
expect(adapter.type).toBe("s3");
expect(adapter.config.url).toBe("https://example.com/what");
}
});
});
+72
View File
@@ -0,0 +1,72 @@
import { describe, test, expect, beforeAll, mock, beforeEach, afterAll } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import type { McpServer } from "bknd/utils";
/**
* - [x] config_server_get
* - [x] config_server_update
*/
describe("mcp system", async () => {
let app: App;
let server: McpServer;
beforeAll(async () => {
app = createApp({
initialConfig: {
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
server = app.mcp!;
});
const tool = createMcpToolCaller();
test("config_server_get", async () => {
const result = await tool(server, "config_server_get", {});
expect(JSON.parse(JSON.stringify(result))).toEqual({
path: "",
secrets: false,
partial: false,
value: JSON.parse(JSON.stringify(app.toJSON().server)),
});
});
test("config_server_get2", async () => {
const result = await tool(server, "config_server_get", {});
expect(JSON.parse(JSON.stringify(result))).toEqual({
path: "",
secrets: false,
partial: false,
value: JSON.parse(JSON.stringify(app.toJSON().server)),
});
});
test("config_server_update", async () => {
const original = JSON.parse(JSON.stringify(app.toJSON().server));
const result = await tool(server, "config_server_update", {
value: {
cors: {
origin: "http://localhost",
},
},
return_config: true,
});
expect(JSON.parse(JSON.stringify(result))).toEqual({
success: true,
module: "server",
config: {
...original,
cors: {
...original.cors,
origin: "http://localhost",
},
},
});
expect(app.toJSON().server.cors.origin).toBe("http://localhost");
});
});
+56
View File
@@ -0,0 +1,56 @@
import { AppEvents } from "App";
import { describe, test, expect, beforeAll, mock } from "bun:test";
import { type App, createApp, createMcpToolCaller } from "core/test/utils";
import type { McpServer } from "bknd/utils";
/**
* - [x] system_config
* - [x] system_build
* - [x] system_ping
* - [x] system_info
*/
describe("mcp system", async () => {
let app: App;
let server: McpServer;
beforeAll(async () => {
app = createApp({
initialConfig: {
server: {
mcp: {
enabled: true,
},
},
},
});
await app.build();
server = app.mcp!;
});
const tool = createMcpToolCaller();
test("system_ping", async () => {
const result = await tool(server, "system_ping", {});
expect(result).toEqual({ pong: true });
});
test("system_info", async () => {
const result = await tool(server, "system_info", {});
expect(Object.keys(result).length).toBeGreaterThan(0);
expect(Object.keys(result)).toContainValues(["version", "runtime", "connection"]);
});
test("system_build", async () => {
const called = mock(() => null);
app.emgr.onEvent(AppEvents.AppBuiltEvent, () => void called(), { once: true });
const result = await tool(server, "system_build", {});
expect(called).toHaveBeenCalledTimes(1);
expect(result.success).toBe(true);
});
test("system_config", async () => {
const result = await tool(server, "system_config", {});
expect(result).toEqual(app.toJSON());
});
});
+1 -44
View File
@@ -1,46 +1,3 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Authenticator, type User, type UserPool } from "../../src/auth";
import { cookieConfig } from "../../src/auth/authenticate/Authenticator";
import { PasswordStrategy } from "../../src/auth/authenticate/strategies/PasswordStrategy";
import * as hash from "../../src/auth/utils/hash";
import { Default, parse } from "../../src/core/utils";
/*class MemoryUserPool implements UserPool { describe("Authenticator", async () => {});
constructor(private users: User[] = []) {}
async findBy(prop: "id" | "email" | "username", value: string | number) {
return this.users.find((user) => user[prop] === value);
}
async create(user: Pick<User, "email" | "password">) {
const id = this.users.length + 1;
const newUser = { ...user, id, username: user.email };
this.users.push(newUser);
return newUser;
}
}*/
describe("Authenticator", async () => {
test("cookie options", async () => {
console.log("parsed", parse(cookieConfig, undefined));
console.log(Default(cookieConfig, {}));
});
/*const userpool = new MemoryUserPool([
{ id: 1, email: "d", username: "test", password: await hash.sha256("test") },
]);
test("sha256 login", async () => {
const auth = new Authenticator(userpool, {
password: new PasswordStrategy({
hashing: "sha256",
}),
});
const { token } = await auth.login("password", { email: "d", password: "test" });
expect(token).toBeDefined();
const { iat, ...decoded } = decodeJwt<any>(token);
expect(decoded).toEqual({ id: 1, email: "d", username: "test" });
expect(await auth.verify(token)).toBe(true);
});*/
});
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Guard } from "../../../src/auth"; import { Guard } from "../../../src/auth/authorize/Guard";
describe("authorize", () => { describe("authorize", () => {
test("basic", async () => { test("basic", async () => {
+11 -9
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { type TObject, type TString, Type } from "@sinclair/typebox"; import { Registry } from "core/registry/Registry";
import { Registry } from "core"; import { s } from "core/utils/schema";
type Constructor<T> = new (...args: any[]) => T; type Constructor<T> = new (...args: any[]) => T;
@@ -11,7 +11,7 @@ class What {
return null; return null;
} }
getType() { getType() {
return Type.Object({ type: Type.String() }); return s.object({ type: s.string() });
} }
} }
class What2 extends What {} class What2 extends What {}
@@ -19,7 +19,7 @@ class NotAllowed {}
type Test1 = { type Test1 = {
cls: new (...args: any[]) => What; cls: new (...args: any[]) => What;
schema: TObject<{ type: TString }>; schema: s.ObjectSchema<{ type: s.StringSchema }>;
enabled: boolean; enabled: boolean;
}; };
@@ -28,7 +28,7 @@ describe("Registry", () => {
const registry = new Registry<Test1>().set({ const registry = new Registry<Test1>().set({
first: { first: {
cls: What, cls: What,
schema: Type.Object({ type: Type.String(), what: Type.String() }), schema: s.object({ type: s.string(), what: s.string() }),
enabled: true, enabled: true,
}, },
} satisfies Record<string, Test1>); } satisfies Record<string, Test1>);
@@ -37,7 +37,7 @@ describe("Registry", () => {
expect(item).toBeDefined(); expect(item).toBeDefined();
expect(item?.cls).toBe(What); expect(item?.cls).toBe(What);
const second = Type.Object({ type: Type.String(), what: Type.String() }); const second = s.object({ type: s.string(), what: s.string() });
registry.add("second", { registry.add("second", {
cls: What2, cls: What2,
schema: second, schema: second,
@@ -46,7 +46,7 @@ describe("Registry", () => {
// @ts-ignore // @ts-ignore
expect(registry.get("second").schema).toEqual(second); expect(registry.get("second").schema).toEqual(second);
const third = Type.Object({ type: Type.String({ default: "1" }), what22: Type.String() }); const third = s.object({ type: s.string({ default: "1" }), what22: s.string() });
registry.add("third", { registry.add("third", {
// @ts-expect-error // @ts-expect-error
cls: NotAllowed, cls: NotAllowed,
@@ -56,7 +56,7 @@ describe("Registry", () => {
// @ts-ignore // @ts-ignore
expect(registry.get("third").schema).toEqual(third); expect(registry.get("third").schema).toEqual(third);
const fourth = Type.Object({ type: Type.Number(), what22: Type.String() }); const fourth = s.object({ type: s.number(), what22: s.string() });
registry.add("fourth", { registry.add("fourth", {
cls: What, cls: What,
// @ts-expect-error // @ts-expect-error
@@ -81,6 +81,8 @@ describe("Registry", () => {
registry.register("what2", What2); registry.register("what2", What2);
expect(registry.get("what2")).toBeDefined(); expect(registry.get("what2")).toBeDefined();
expect(registry.get("what2").cls).toBe(What2); expect(registry.get("what2").cls).toBe(What2);
expect(registry.get("what2").schema).toEqual(What2.prototype.getType()); expect(JSON.stringify(registry.get("what2").schema)).toEqual(
JSON.stringify(What2.prototype.getType()),
);
}); });
}); });
+46 -32
View File
@@ -1,11 +1,11 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { SchemaObject } from "../../../src/core"; import { s } from "core/utils/schema";
import { Type } from "@sinclair/typebox"; import { SchemaObject } from "core/object/SchemaObject";
describe("SchemaObject", async () => { describe("SchemaObject", async () => {
test("basic", async () => { test("basic", async () => {
const m = new SchemaObject( const m = new SchemaObject(
Type.Object({ a: Type.String({ default: "b" }) }), s.strictObject({ a: s.string({ default: "b" }) }),
{ a: "test" }, { a: "test" },
{ {
forceParse: true, forceParse: true,
@@ -23,19 +23,19 @@ describe("SchemaObject", async () => {
test("patch", async () => { test("patch", async () => {
const m = new SchemaObject( const m = new SchemaObject(
Type.Object({ s.strictObject({
s: Type.Object( s: s.strictObject(
{ {
a: Type.String({ default: "b" }), a: s.string({ default: "b" }),
b: Type.Object( b: s.strictObject(
{ {
c: Type.String({ default: "d" }), c: s.string({ default: "d" }),
e: Type.String({ default: "f" }), e: s.string({ default: "f" }),
}, },
{ default: {} }, { default: {} },
), ),
}, },
{ default: {}, additionalProperties: false }, { default: {} },
), ),
}), }),
); );
@@ -44,7 +44,7 @@ describe("SchemaObject", async () => {
await m.patch("s.a", "c"); await m.patch("s.a", "c");
// non-existing path on no additional properties // non-existing path on no additional properties
expect(() => m.patch("s.s.s", "c")).toThrow(); expect(m.patch("s.s.s", "c")).rejects.toThrow();
// wrong type // wrong type
expect(() => m.patch("s.a", 1)).toThrow(); expect(() => m.patch("s.a", 1)).toThrow();
@@ -58,8 +58,8 @@ describe("SchemaObject", async () => {
test("patch array", async () => { test("patch array", async () => {
const m = new SchemaObject( const m = new SchemaObject(
Type.Object({ s.strictObject({
methods: Type.Array(Type.String(), { default: ["GET", "PATCH"] }), methods: s.array(s.string(), { default: ["GET", "PATCH"] }),
}), }),
); );
expect(m.get()).toEqual({ methods: ["GET", "PATCH"] }); expect(m.get()).toEqual({ methods: ["GET", "PATCH"] });
@@ -75,13 +75,13 @@ describe("SchemaObject", async () => {
test("remove", async () => { test("remove", async () => {
const m = new SchemaObject( const m = new SchemaObject(
Type.Object({ s.object({
s: Type.Object( s: s.object(
{ {
a: Type.String({ default: "b" }), a: s.string({ default: "b" }),
b: Type.Object( b: s.object(
{ {
c: Type.String({ default: "d" }), c: s.string({ default: "d" }),
}, },
{ default: {} }, { default: {} },
), ),
@@ -107,8 +107,8 @@ describe("SchemaObject", async () => {
test("set", async () => { test("set", async () => {
const m = new SchemaObject( const m = new SchemaObject(
Type.Object({ s.strictObject({
methods: Type.Array(Type.String(), { default: ["GET", "PATCH"] }), methods: s.array(s.string(), { default: ["GET", "PATCH"] }),
}), }),
); );
expect(m.get()).toEqual({ methods: ["GET", "PATCH"] }); expect(m.get()).toEqual({ methods: ["GET", "PATCH"] });
@@ -124,8 +124,8 @@ describe("SchemaObject", async () => {
let called = false; let called = false;
let result: any; let result: any;
const m = new SchemaObject( const m = new SchemaObject(
Type.Object({ s.strictObject({
methods: Type.Array(Type.String(), { default: ["GET", "PATCH"] }), methods: s.array(s.string(), { default: ["GET", "PATCH"] }),
}), }),
undefined, undefined,
{ {
@@ -145,8 +145,8 @@ describe("SchemaObject", async () => {
test("listener: onBeforeUpdate", async () => { test("listener: onBeforeUpdate", async () => {
let called = false; let called = false;
const m = new SchemaObject( const m = new SchemaObject(
Type.Object({ s.strictObject({
methods: Type.Array(Type.String(), { default: ["GET", "PATCH"] }), methods: s.array(s.string(), { default: ["GET", "PATCH"] }),
}), }),
undefined, undefined,
{ {
@@ -167,7 +167,7 @@ describe("SchemaObject", async () => {
}); });
test("throwIfRestricted", async () => { test("throwIfRestricted", async () => {
const m = new SchemaObject(Type.Object({}), undefined, { const m = new SchemaObject(s.strictObject({}), undefined, {
restrictPaths: ["a.b"], restrictPaths: ["a.b"],
}); });
@@ -179,13 +179,13 @@ describe("SchemaObject", async () => {
test("restriction bypass", async () => { test("restriction bypass", async () => {
const m = new SchemaObject( const m = new SchemaObject(
Type.Object({ s.strictObject({
s: Type.Object( s: s.strictObject(
{ {
a: Type.String({ default: "b" }), a: s.string({ default: "b" }),
b: Type.Object( b: s.strictObject(
{ {
c: Type.String({ default: "d" }), c: s.string({ default: "d" }),
}, },
{ default: {} }, { default: {} },
), ),
@@ -205,7 +205,21 @@ describe("SchemaObject", async () => {
expect(m.get()).toEqual({ s: { a: "b", b: { c: "e" } } }); expect(m.get()).toEqual({ s: { a: "b", b: { c: "e" } } });
}); });
const dataEntitiesSchema = Type.Object( const dataEntitiesSchema = s.strictObject({
entities: s.record(
s.object({
fields: s.record(
s.object({
type: s.string(),
config: s.object({}).optional(),
}),
),
config: s.record(s.string()).optional(),
}),
),
});
/* const dataEntitiesSchema = Type.Object(
{ {
entities: Type.Object( entities: Type.Object(
{}, {},
@@ -230,7 +244,7 @@ describe("SchemaObject", async () => {
{ {
additionalProperties: false, additionalProperties: false,
}, },
); ); */
test("patch safe object, overwrite", async () => { test("patch safe object, overwrite", async () => {
const data = { const data = {
entities: { entities: {
+6 -9
View File
@@ -1,19 +1,16 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { Guard } from "../../src/auth"; import { Guard } from "../../src/auth/authorize/Guard";
import { parse } from "../../src/core/utils"; import { parse } from "core/utils/schema";
import {
Entity,
type EntityData,
EntityManager,
ManyToOneRelation,
TextField,
} from "../../src/data";
import { DataController } from "../../src/data/api/DataController"; import { DataController } from "../../src/data/api/DataController";
import { dataConfigSchema } from "../../src/data/data-schema"; import { dataConfigSchema } from "../../src/data/data-schema";
import { disableConsoleLog, enableConsoleLog, getDummyConnection } from "../helper"; import { disableConsoleLog, enableConsoleLog, getDummyConnection } from "../helper";
import type { RepositoryResultJSON } from "data/entities/query/RepositoryResult"; import type { RepositoryResultJSON } from "data/entities/query/RepositoryResult";
import type { MutatorResultJSON } from "data/entities/mutation/MutatorResult"; import type { MutatorResultJSON } from "data/entities/mutation/MutatorResult";
import { Entity, EntityManager, type EntityData } from "data/entities";
import { TextField } from "data/fields";
import { ManyToOneRelation } from "data/relations";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
beforeAll(() => disableConsoleLog(["log", "warn"])); beforeAll(() => disableConsoleLog(["log", "warn"]));
+2 -8
View File
@@ -1,12 +1,6 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { import { Entity, EntityManager } from "data/entities";
Entity, import { TextField, PrimaryField, NumberField } from "data/fields";
EntityManager,
NumberField,
PrimaryField,
Repository,
TextField,
} from "../../src/data";
import { getDummyConnection } from "./helper"; import { getDummyConnection } from "./helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+1 -1
View File
@@ -2,7 +2,7 @@ import { unlink } from "node:fs/promises";
import type { SqliteDatabase } from "kysely"; import type { SqliteDatabase } from "kysely";
// @ts-ignore // @ts-ignore
import Database from "libsql"; import Database from "libsql";
import { SqliteLocalConnection } from "../../src/data"; import { SqliteLocalConnection } from "data/connection/sqlite/SqliteLocalConnection";
export function getDummyDatabase(memory: boolean = true): { export function getDummyDatabase(memory: boolean = true): {
dummyDb: SqliteDatabase; dummyDb: SqliteDatabase;
+5 -8
View File
@@ -1,13 +1,10 @@
// eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-unresolved
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { import { Entity } from "data/entities";
Entity, import { EntityManager } from "data/entities/EntityManager";
EntityManager, import { ManyToOneRelation } from "data/relations";
ManyToOneRelation, import { NumberField, TextField } from "data/fields";
NumberField, import { SchemaManager } from "data/schema/SchemaManager";
SchemaManager,
TextField,
} from "../../src/data";
import { getDummyConnection } from "./helper"; import { getDummyConnection } from "./helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+3 -2
View File
@@ -1,7 +1,8 @@
// eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-unresolved
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { Entity, EntityManager, Mutator, NumberField, TextField } from "../../src/data"; import { Entity, EntityManager } from "data/entities";
import { TransformPersistFailedException } from "../../src/data/errors"; import { NumberField, TextField } from "data/fields";
import { TransformPersistFailedException } from "data/errors";
import { getDummyConnection } from "./helper"; import { getDummyConnection } from "./helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+4 -2
View File
@@ -1,6 +1,8 @@
import { afterAll, expect as bunExpect, describe, test } from "bun:test"; import { afterAll, expect as bunExpect, describe, test } from "bun:test";
import { stripMark } from "../../src/core/utils"; import { stripMark } from "core/utils/schema";
import { Entity, EntityManager, PolymorphicRelation, TextField } from "../../src/data"; import { Entity, EntityManager } from "data/entities";
import { TextField } from "data/fields";
import { PolymorphicRelation } from "data/relations";
import { getDummyConnection } from "./helper"; import { getDummyConnection } from "./helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+14 -12
View File
@@ -2,19 +2,20 @@ import { describe, expect, test } from "bun:test";
import { import {
BooleanField, BooleanField,
DateField, DateField,
Entity,
EntityIndex,
EntityManager,
EnumField, EnumField,
JsonField, JsonField,
NumberField,
TextField,
EntityIndex,
} from "data/fields";
import { Entity, EntityManager } from "data/entities";
import {
ManyToManyRelation, ManyToManyRelation,
ManyToOneRelation, ManyToOneRelation,
NumberField,
OneToOneRelation, OneToOneRelation,
PolymorphicRelation, PolymorphicRelation,
TextField, } from "data/relations";
} from "../../src/data"; import { DummyConnection } from "data/connection/DummyConnection";
import { DummyConnection } from "../../src/data/connection/DummyConnection";
import { import {
FieldPrototype, FieldPrototype,
type FieldSchema, type FieldSchema,
@@ -32,8 +33,8 @@ import {
number, number,
relation, relation,
text, text,
} from "../../src/data/prototype"; } from "data/prototype";
import { MediaField } from "../../src/media/MediaField"; import { MediaField } from "media/MediaField";
describe("prototype", () => { describe("prototype", () => {
test("...", () => { test("...", () => {
@@ -101,7 +102,8 @@ describe("prototype", () => {
type Posts = Schema<typeof posts2>; type Posts = Schema<typeof posts2>;
expect(posts1.toJSON()).toEqual(posts2.toJSON()); // @todo: check
//expect(posts1.toJSON()).toEqual(posts2.toJSON());
}); });
test("test example", async () => { test("test example", async () => {
@@ -295,9 +297,9 @@ describe("prototype", () => {
new Entity("posts", [new TextField("name"), new TextField("slug", { required: true })]), new Entity("posts", [new TextField("name"), new TextField("slug", { required: true })]),
new Entity("comments", [new TextField("some")]), new Entity("comments", [new TextField("some")]),
new Entity("users", [new TextField("email")]), new Entity("users", [new TextField("email")]),
]; ] as const;
const _em2 = new EntityManager( const _em2 = new EntityManager(
es, [...es],
new DummyConnection(), new DummyConnection(),
[new ManyToOneRelation(es[0], es[1]), new ManyToOneRelation(es[0], es[2])], [new ManyToOneRelation(es[0], es[1]), new ManyToOneRelation(es[0], es[2])],
[ [
+11 -10
View File
@@ -1,13 +1,14 @@
// eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-unresolved
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { Entity, EntityManager, TextField } from "../../src/data"; import { Entity, EntityManager } from "data/entities";
import { TextField } from "data/fields";
import { import {
ManyToManyRelation, ManyToManyRelation,
ManyToOneRelation, ManyToOneRelation,
OneToOneRelation, OneToOneRelation,
PolymorphicRelation, PolymorphicRelation,
RelationField, RelationField,
} from "../../src/data/relations"; } from "data/relations";
import { getDummyConnection } from "./helper"; import { getDummyConnection } from "./helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
@@ -77,7 +78,7 @@ describe("Relations", async () => {
const em = new EntityManager(entities, dummyConnection, relations); const em = new EntityManager(entities, dummyConnection, relations);
// verify naming // verify naming
const rel = em.relations.all[0]; const rel = em.relations.all[0]!;
expect(rel.source.entity.name).toBe(posts.name); expect(rel.source.entity.name).toBe(posts.name);
expect(rel.source.reference).toBe(posts.name); expect(rel.source.reference).toBe(posts.name);
expect(rel.target.entity.name).toBe(users.name); expect(rel.target.entity.name).toBe(users.name);
@@ -89,11 +90,11 @@ describe("Relations", async () => {
// verify low level relation // verify low level relation
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name)[0].source.entity).toBe(posts); expect(em.relationsOf(users.name)[0]!.source.entity).toBe(posts);
expect(posts.field("author_id")).toBeInstanceOf(RelationField); expect(posts.field("author_id")).toBeInstanceOf(RelationField);
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name)[0].source.entity).toBe(posts); expect(em.relationsOf(users.name)[0]!.source.entity).toBe(posts);
// verify high level relation (from users) // verify high level relation (from users)
const userPostsRel = em.relationOf(users.name, "posts"); const userPostsRel = em.relationOf(users.name, "posts");
@@ -191,7 +192,7 @@ describe("Relations", async () => {
const em = new EntityManager(entities, dummyConnection, relations); const em = new EntityManager(entities, dummyConnection, relations);
// verify naming // verify naming
const rel = em.relations.all[0]; const rel = em.relations.all[0]!;
expect(rel.source.entity.name).toBe(users.name); expect(rel.source.entity.name).toBe(users.name);
expect(rel.source.reference).toBe(users.name); expect(rel.source.reference).toBe(users.name);
expect(rel.target.entity.name).toBe(settings.name); expect(rel.target.entity.name).toBe(settings.name);
@@ -202,8 +203,8 @@ describe("Relations", async () => {
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name).length).toBe(1); expect(em.relationsOf(users.name).length).toBe(1);
expect(em.relationsOf(users.name)[0].source.entity).toBe(users); expect(em.relationsOf(users.name)[0]!.source.entity).toBe(users);
expect(em.relationsOf(users.name)[0].target.entity).toBe(settings); expect(em.relationsOf(users.name)[0]!.target.entity).toBe(settings);
// verify high level relation (from users) // verify high level relation (from users)
const userSettingRel = em.relationOf(users.name, settings.name); const userSettingRel = em.relationOf(users.name, settings.name);
@@ -323,7 +324,7 @@ describe("Relations", async () => {
); );
// mutation info // mutation info
expect(relations[0].helper(posts.name)!.getMutationInfo()).toEqual({ expect(relations[0]!.helper(posts.name)!.getMutationInfo()).toEqual({
reference: "categories", reference: "categories",
local_field: undefined, local_field: undefined,
$set: false, $set: false,
@@ -334,7 +335,7 @@ describe("Relations", async () => {
cardinality: undefined, cardinality: undefined,
relation_type: "m:n", relation_type: "m:n",
}); });
expect(relations[0].helper(categories.name)!.getMutationInfo()).toEqual({ expect(relations[0]!.helper(categories.name)!.getMutationInfo()).toEqual({
reference: "posts", reference: "posts",
local_field: undefined, local_field: undefined,
$set: false, $set: false,
+2 -6
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Entity, NumberField, TextField } from "data"; import { Entity } from "data/entities";
import * as p from "data/prototype"; import { NumberField, TextField } from "data/fields";
describe("[data] Entity", async () => { describe("[data] Entity", async () => {
const entity = new Entity("test", [ const entity = new Entity("test", [
@@ -47,8 +47,4 @@ describe("[data] Entity", async () => {
entity.addField(field); entity.addField(field);
expect(entity.getField("new_field")).toBe(field); expect(entity.getField("new_field")).toBe(field);
}); });
test.only("types", async () => {
console.log(entity.toTypes());
});
}); });
@@ -1,12 +1,8 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { import { Entity, EntityManager } from "data/entities";
Entity, import { ManyToManyRelation, ManyToOneRelation } from "data/relations";
EntityManager, import { SchemaManager } from "data/schema/SchemaManager";
ManyToManyRelation, import { UnableToConnectException } from "data/errors";
ManyToOneRelation,
SchemaManager,
} from "../../../src/data";
import { UnableToConnectException } from "../../../src/data/errors";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+4 -2
View File
@@ -1,6 +1,8 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { Entity, EntityManager, ManyToOneRelation, TextField } from "../../../src/data"; import { Entity, EntityManager } from "data/entities";
import { JoinBuilder } from "../../../src/data/entities/query/JoinBuilder"; import { ManyToOneRelation } from "data/relations";
import { TextField } from "data/fields";
import { JoinBuilder } from "data/entities/query/JoinBuilder";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+6 -8
View File
@@ -1,18 +1,16 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import type { EventManager } from "../../../src/core/events"; import type { EventManager } from "../../../src/core/events";
import { Entity, EntityManager } from "data/entities";
import { import {
Entity,
EntityManager,
ManyToOneRelation, ManyToOneRelation,
MutatorEvents,
NumberField,
OneToOneRelation, OneToOneRelation,
type RelationField, RelationField,
RelationMutator, RelationMutator,
TextField, } from "data/relations";
} from "../../../src/data"; import { NumberField, TextField } from "data/fields";
import * as proto from "../../../src/data/prototype"; import * as proto from "data/prototype";
import { getDummyConnection, disableConsoleLog, enableConsoleLog } from "../../helper"; import { getDummyConnection, disableConsoleLog, enableConsoleLog } from "../../helper";
import { MutatorEvents } from "data/events";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
afterAll(afterAllCleanup); afterAll(afterAllCleanup);
+5 -12
View File
@@ -1,17 +1,10 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import type { Kysely, Transaction } from "kysely"; import type { Kysely, Transaction } from "kysely";
import { Perf } from "core/utils"; import { TextField } from "data/fields";
import { import { em as $em, entity as $entity, text as $text } from "data/prototype";
Entity, import { Entity, EntityManager } from "data/entities";
EntityManager, import { ManyToOneRelation } from "data/relations";
LibsqlConnection, import { RepositoryEvents } from "data/events";
ManyToOneRelation,
RepositoryEvents,
TextField,
entity as $entity,
text as $text,
em as $em,
} from "data";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
type E = Kysely<any> | Transaction<any>; type E = Kysely<any> | Transaction<any>;
@@ -1,7 +1,9 @@
// eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-unresolved
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { randomString } from "../../../src/core/utils"; import { randomString } from "core/utils";
import { Entity, EntityIndex, EntityManager, SchemaManager, TextField } from "../../../src/data"; import { Entity, EntityManager } from "data/entities";
import { TextField, EntityIndex } from "data/fields";
import { SchemaManager } from "data/schema/SchemaManager";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, test, expect } from "bun:test"; import { describe, test, expect } from "bun:test";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
import { type WhereQuery, WhereBuilder } from "data"; import { WhereBuilder, type WhereQuery } from "data/entities/query/WhereBuilder";
function qb() { function qb() {
const c = getDummyConnection(); const c = getDummyConnection();
+5 -10
View File
@@ -1,14 +1,9 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { import { Entity, EntityManager } from "data/entities";
Entity, import { ManyToManyRelation, ManyToOneRelation, PolymorphicRelation } from "data/relations";
EntityManager, import { TextField } from "data/fields";
ManyToManyRelation, import * as proto from "data/prototype";
ManyToOneRelation, import { WithBuilder } from "data/entities/query/WithBuilder";
PolymorphicRelation,
TextField,
WithBuilder,
} from "../../../src/data";
import * as proto from "../../../src/data/prototype";
import { schemaToEm } from "../../helper"; import { schemaToEm } from "../../helper";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
@@ -1,5 +1,5 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
import { EntityManager } from "../../../../src/data"; import { EntityManager } from "data/entities/EntityManager";
import { getDummyConnection } from "../../helper"; import { getDummyConnection } from "../../helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
@@ -1,9 +1,10 @@
import { bunTestRunner } from "adapter/bun/test";
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { BooleanField } from "../../../../src/data"; import { BooleanField } from "data/fields";
import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite"; import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite";
describe("[data] BooleanField", async () => { describe("[data] BooleanField", async () => {
fieldTestSuite({ expect, test }, BooleanField, { defaultValue: true, schemaType: "boolean" }); fieldTestSuite(bunTestRunner, BooleanField, { defaultValue: true, schemaType: "boolean" });
test("transformRetrieve", async () => { test("transformRetrieve", async () => {
const field = new BooleanField("test"); const field = new BooleanField("test");
@@ -1,9 +1,15 @@
import { describe, expect, test } from "bun:test"; import { describe, test } from "bun:test";
import { DateField } from "../../../../src/data"; import { DateField } from "data/fields";
import { fieldTestSuite } from "data/fields/field-test-suite"; import { fieldTestSuite } from "data/fields/field-test-suite";
import { bunTestRunner } from "adapter/bun/test";
describe("[data] DateField", async () => { describe("[data] DateField", async () => {
fieldTestSuite({ expect, test }, DateField, { defaultValue: new Date(), schemaType: "date" }); fieldTestSuite(
bunTestRunner,
DateField,
{ defaultValue: new Date(), schemaType: "date" },
{ type: "date" },
);
// @todo: add datefield tests // @todo: add datefield tests
test("week", async () => { test("week", async () => {
@@ -1,5 +1,6 @@
import { bunTestRunner } from "adapter/bun/test";
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { EnumField } from "../../../../src/data"; import { EnumField } from "data/fields";
import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite"; import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite";
function options(strings: string[]) { function options(strings: string[]) {
@@ -8,7 +9,7 @@ function options(strings: string[]) {
describe("[data] EnumField", async () => { describe("[data] EnumField", async () => {
fieldTestSuite( fieldTestSuite(
{ expect, test }, bunTestRunner,
// @ts-ignore // @ts-ignore
EnumField, EnumField,
{ defaultValue: "a", schemaType: "text" }, { defaultValue: "a", schemaType: "text" },
+4 -3
View File
@@ -1,7 +1,8 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Default, stripMark } from "../../../../src/core/utils";
import { baseFieldConfigSchema, Field } from "../../../../src/data/fields/Field"; import { baseFieldConfigSchema, Field } from "../../../../src/data/fields/Field";
import { fieldTestSuite } from "data/fields/field-test-suite"; import { fieldTestSuite } from "data/fields/field-test-suite";
import { bunTestRunner } from "adapter/bun/test";
import { stripMark } from "core/utils/schema";
describe("[data] Field", async () => { describe("[data] Field", async () => {
class FieldSpec extends Field { class FieldSpec extends Field {
@@ -19,10 +20,10 @@ describe("[data] Field", async () => {
}); });
}); });
fieldTestSuite({ expect, test }, FieldSpec, { defaultValue: "test", schemaType: "text" }); fieldTestSuite(bunTestRunner, FieldSpec, { defaultValue: "test", schemaType: "text" });
test("default config", async () => { test("default config", async () => {
const config = Default(baseFieldConfigSchema, {}); const config = baseFieldConfigSchema.template({});
expect(stripMark(new FieldSpec("test").config)).toEqual(config as any); expect(stripMark(new FieldSpec("test").config)).toEqual(config as any);
}); });
@@ -1,10 +1,11 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Type } from "@sinclair/typebox"; import { Entity } from "data/entities";
import { Entity, EntityIndex, Field } from "../../../../src/data"; import { Field, EntityIndex } from "data/fields";
import { s } from "core/utils/schema";
class TestField extends Field { class TestField extends Field {
protected getSchema(): any { protected getSchema(): any {
return Type.Any(); return s.any();
} }
override schema() { override schema() {
@@ -1,10 +1,11 @@
import { bunTestRunner } from "adapter/bun/test";
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { JsonField } from "../../../../src/data"; import { JsonField } from "data/fields";
import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite"; import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite";
describe("[data] JsonField", async () => { describe("[data] JsonField", async () => {
const field = new JsonField("test"); const field = new JsonField("test");
fieldTestSuite({ expect, test }, JsonField, { fieldTestSuite(bunTestRunner, JsonField, {
defaultValue: { a: 1 }, defaultValue: { a: 1 },
sampleValues: ["string", { test: 1 }, 1], sampleValues: ["string", { test: 1 }, 1],
schemaType: "text", schemaType: "text",
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { JsonSchemaField } from "../../../../src/data"; import { JsonSchemaField } from "data/fields";
import { fieldTestSuite } from "data/fields/field-test-suite"; import { fieldTestSuite } from "data/fields/field-test-suite";
describe("[data] JsonSchemaField", async () => { describe("[data] JsonSchemaField", async () => {
@@ -1,5 +1,6 @@
import { bunTestRunner } from "adapter/bun/test";
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { NumberField } from "../../../../src/data"; import { NumberField } from "data/fields";
import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite"; import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite";
describe("[data] NumberField", async () => { describe("[data] NumberField", async () => {
@@ -15,5 +16,5 @@ describe("[data] NumberField", async () => {
expect(transformPersist(field2, 10000)).resolves.toBe(10000); expect(transformPersist(field2, 10000)).resolves.toBe(10000);
}); });
fieldTestSuite({ expect, test }, NumberField, { defaultValue: 12, schemaType: "integer" }); fieldTestSuite(bunTestRunner, NumberField, { defaultValue: 12, schemaType: "integer" });
}); });
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { PrimaryField } from "../../../../src/data"; import { PrimaryField } from "data/fields";
describe("[data] PrimaryField", async () => { describe("[data] PrimaryField", async () => {
const field = new PrimaryField("primary"); const field = new PrimaryField("primary");
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { TextField } from "../../../../src/data"; import { TextField } from "data/fields";
import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite"; import { fieldTestSuite, transformPersist } from "data/fields/field-test-suite";
import { bunTestRunner } from "adapter/bun/test";
describe("[data] TextField", async () => { describe("[data] TextField", async () => {
test("transformPersist (config)", async () => { test("transformPersist (config)", async () => {
@@ -11,5 +12,5 @@ describe("[data] TextField", async () => {
expect(transformPersist(field, "abc")).resolves.toBe("abc"); expect(transformPersist(field, "abc")).resolves.toBe("abc");
}); });
fieldTestSuite({ expect, test }, TextField, { defaultValue: "abc", schemaType: "text" }); fieldTestSuite(bunTestRunner, TextField, { defaultValue: "abc", schemaType: "text" });
}); });
@@ -1,11 +1,11 @@
import { describe, expect, it, test } from "bun:test"; import { describe, expect, it, test } from "bun:test";
import { Entity, type EntityManager } from "../../../../src/data"; import { Entity, type EntityManager } from "data/entities";
import { import {
type BaseRelationConfig, type BaseRelationConfig,
EntityRelation, EntityRelation,
EntityRelationAnchor, EntityRelationAnchor,
RelationTypes, RelationTypes,
} from "../../../../src/data/relations"; } from "data/relations";
class TestEntityRelation extends EntityRelation { class TestEntityRelation extends EntityRelation {
constructor(config?: BaseRelationConfig) { constructor(config?: BaseRelationConfig) {
@@ -24,11 +24,11 @@ class TestEntityRelation extends EntityRelation {
return this; return this;
} }
buildWith(a: any, b: any, c: any): any { buildWith(): any {
return; return;
} }
buildJoin(a: any, b: any): any { buildJoin(): any {
return; return;
} }
} }
@@ -0,0 +1,24 @@
import { describe, it, expect } from "bun:test";
import * as sDirect from "jsonv-ts";
import { s as sFromBknd } from "bknd/utils";
describe("jsonv-ts resolution", () => {
it("should resolve to a single instance", () => {
const sameNamespace = sDirect === (sFromBknd as unknown as typeof sDirect);
// If this fails, two instances are being loaded via different specifiers/paths
expect(sameNamespace).toBe(true);
});
it("should resolve specifiers to a single package path", async () => {
const base = await import.meta.resolve("jsonv-ts");
const hono = await import.meta.resolve("jsonv-ts/hono");
const mcp = await import.meta.resolve("jsonv-ts/mcp");
expect(typeof base).toBe("string");
expect(typeof hono).toBe("string");
expect(typeof mcp).toBe("string");
// They can be different files (subpath exports), but they should share the same package root
const pkgRoot = (p: string) => p.slice(0, p.lastIndexOf("jsonv-ts") + "jsonv-ts".length);
expect(pkgRoot(base)).toBe(pkgRoot(hono));
expect(pkgRoot(base)).toBe(pkgRoot(mcp));
});
});
+1 -1
View File
@@ -41,7 +41,7 @@ beforeAll(() =>
); );
afterAll(unmockFetch); afterAll(unmockFetch);
describe("FetchTask", async () => { describe.skip("FetchTask", async () => {
test("Simple fetch", async () => { test("Simple fetch", async () => {
const task = new FetchTask("Fetch Something", { const task = new FetchTask("Fetch Something", {
url: "https://jsonplaceholder.typicode.com/todos/1", url: "https://jsonplaceholder.typicode.com/todos/1",
+5 -7
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Flow, LogTask, SubFlowTask, RenderTask, Task } from "../../src/flows"; import { Flow, LogTask, SubFlowTask, RenderTask, Task } from "../../src/flows";
import { Type } from "@sinclair/typebox"; import { s } from "core/utils/schema";
export class StringifyTask<Output extends string> extends Task< export class StringifyTask<Output extends string> extends Task<
typeof StringifyTask.schema, typeof StringifyTask.schema,
@@ -8,18 +8,16 @@ export class StringifyTask<Output extends string> extends Task<
> { > {
type = "stringify"; type = "stringify";
static override schema = Type.Optional( static override schema = s.object({
Type.Object({ input: s.string().optional(),
input: Type.Optional(Type.String()), });
}),
);
async execute() { async execute() {
return JSON.stringify(this.params.input) as Output; return JSON.stringify(this.params.input) as Output;
} }
} }
describe("SubFlowTask", async () => { describe.skip("SubFlowTask", async () => {
test("Simple Subflow", async () => { test("Simple Subflow", async () => {
const subTask = new RenderTask("render", { const subTask = new RenderTask("render", {
render: "subflow", render: "subflow",
+5 -5
View File
@@ -1,12 +1,12 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Type } from "@sinclair/typebox";
import { Task } from "../../src/flows"; import { Task } from "../../src/flows";
import { dynamic } from "../../src/flows/tasks/Task"; import { dynamic } from "../../src/flows/tasks/Task";
import { s } from "core/utils/schema";
describe("Task", async () => { describe.skip("Task", async () => {
test("resolveParams: template with parse", async () => { test("resolveParams: template with parse", async () => {
const result = await Task.resolveParams( const result = await Task.resolveParams(
Type.Object({ test: dynamic(Type.Number()) }), s.object({ test: dynamic(s.number()) }),
{ {
test: "{{ some.path }}", test: "{{ some.path }}",
}, },
@@ -22,7 +22,7 @@ describe("Task", async () => {
test("resolveParams: with string", async () => { test("resolveParams: with string", async () => {
const result = await Task.resolveParams( const result = await Task.resolveParams(
Type.Object({ test: Type.String() }), s.object({ test: s.string() }),
{ {
test: "{{ some.path }}", test: "{{ some.path }}",
}, },
@@ -38,7 +38,7 @@ describe("Task", async () => {
test("resolveParams: with object", async () => { test("resolveParams: with object", async () => {
const result = await Task.resolveParams( const result = await Task.resolveParams(
Type.Object({ test: dynamic(Type.Object({ key: Type.String(), value: Type.String() })) }), s.object({ test: dynamic(s.object({ key: s.string(), value: s.string() })) }),
{ {
test: { key: "path", value: "{{ some.path }}" }, test: { key: "path", value: "{{ some.path }}" },
}, },
+6 -7
View File
@@ -1,8 +1,7 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { Hono } from "hono"; import { Hono } from "hono";
import { Event, EventManager } from "../../src/core/events"; import { Event, EventManager } from "../../src/core/events";
import { parse } from "../../src/core/utils"; import { s, parse } from "core/utils/schema";
import { type Static, type StaticDecode, Type } from "@sinclair/typebox";
import { EventTrigger, Flow, HttpTrigger, type InputsMap, Task } from "../../src/flows"; import { EventTrigger, Flow, HttpTrigger, type InputsMap, Task } from "../../src/flows";
import { dynamic } from "../../src/flows/tasks/Task"; import { dynamic } from "../../src/flows/tasks/Task";
@@ -15,15 +14,15 @@ class Passthrough extends Task {
} }
} }
type OutputIn = Static<typeof OutputParamTask.schema>; type OutputIn = s.Static<typeof OutputParamTask.schema>;
type OutputOut = StaticDecode<typeof OutputParamTask.schema>; type OutputOut = s.StaticCoerced<typeof OutputParamTask.schema>;
class OutputParamTask extends Task<typeof OutputParamTask.schema> { class OutputParamTask extends Task<typeof OutputParamTask.schema> {
type = "output-param"; type = "output-param";
static override schema = Type.Object({ static override schema = s.strictObject({
number: dynamic( number: dynamic(
Type.Number({ s.number({
title: "Output number", title: "Output number",
}), }),
Number.parseInt, Number.parseInt,
@@ -44,7 +43,7 @@ class PassthroughFlowInput extends Task {
} }
} }
describe("Flow task inputs", async () => { describe.skip("Flow task inputs", async () => {
test("types", async () => { test("types", async () => {
const schema = OutputParamTask.schema; const schema = OutputParamTask.schema;
+1 -1
View File
@@ -30,7 +30,7 @@ class ExecTask extends Task {
} }
} }
describe("Flow trigger", async () => { describe.skip("Flow trigger", async () => {
test("manual trigger", async () => { test("manual trigger", async () => {
let called = false; let called = false;
+6 -6
View File
@@ -2,7 +2,7 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { isEqual } from "lodash-es"; import { isEqual } from "lodash-es";
import { _jsonp, withDisabledConsole } from "../../src/core/utils"; import { _jsonp, withDisabledConsole } from "../../src/core/utils";
import { type Static, Type } from "@sinclair/typebox"; import { s } from "core/utils/schema";
import { Condition, ExecutionEvent, FetchTask, Flow, LogTask, Task } from "../../src/flows"; import { Condition, ExecutionEvent, FetchTask, Flow, LogTask, Task } from "../../src/flows";
/*beforeAll(disableConsoleLog); /*beforeAll(disableConsoleLog);
@@ -11,19 +11,19 @@ afterAll(enableConsoleLog);*/
class ExecTask extends Task<typeof ExecTask.schema> { class ExecTask extends Task<typeof ExecTask.schema> {
type = "exec"; type = "exec";
static override schema = Type.Object({ static override schema = s.object({
delay: Type.Number({ default: 10 }), delay: s.number({ default: 10 }),
}); });
constructor( constructor(
name: string, name: string,
params: Static<typeof ExecTask.schema>, params: s.Static<typeof ExecTask.schema>,
private func: () => Promise<any>, private func: () => Promise<any>,
) { ) {
super(name, params); super(name, params);
} }
override clone(name: string, params: Static<typeof ExecTask.schema>) { override clone(name: string, params: s.Static<typeof ExecTask.schema>) {
return new ExecTask(name, params, this.func); return new ExecTask(name, params, this.func);
} }
@@ -78,7 +78,7 @@ function getObjectDiff(obj1, obj2) {
return diff; return diff;
} }
describe("Flow tests", async () => { describe.skip("Flow tests", async () => {
test("Simple single task", async () => { test("Simple single task", async () => {
const simple = getTask(0); const simple = getTask(0);
+3 -2
View File
@@ -2,11 +2,12 @@ import { unlink } from "node:fs/promises";
import type { SelectQueryBuilder, SqliteDatabase } from "kysely"; import type { SelectQueryBuilder, SqliteDatabase } from "kysely";
import Database from "libsql"; import Database from "libsql";
import { format as sqlFormat } from "sql-formatter"; import { format as sqlFormat } from "sql-formatter";
import { type Connection, EntityManager, SqliteLocalConnection } from "../src/data";
import type { em as protoEm } from "../src/data/prototype"; import type { em as protoEm } from "../src/data/prototype";
import { writeFile } from "node:fs/promises"; import { writeFile } from "node:fs/promises";
import { join } from "node:path"; import { join } from "node:path";
import { slugify } from "core/utils/strings"; import { slugify } from "bknd/utils";
import { type Connection, SqliteLocalConnection } from "data/connection";
import { EntityManager } from "data/entities/EntityManager";
export function getDummyDatabase(memory: boolean = true): { export function getDummyDatabase(memory: boolean = true): {
dummyDb: SqliteDatabase; dummyDb: SqliteDatabase;
@@ -13,9 +13,8 @@ describe("integration config", () => {
// create entity // create entity
await api.system.addConfig("data", "entities.posts", { await api.system.addConfig("data", "entities.posts", {
name: "posts",
config: { sort_field: "id", sort_dir: "asc" }, config: { sort_field: "id", sort_dir: "asc" },
fields: { id: { type: "primary", name: "id" }, asdf: { type: "text" } }, fields: { id: { type: "primary" }, asdf: { type: "text" } },
type: "regular", type: "regular",
}); });
@@ -46,7 +46,6 @@ afterAll(enableConsoleLog);
describe("MediaController", () => { describe("MediaController", () => {
test("accepts direct", async () => { test("accepts direct", async () => {
const app = await makeApp(); const app = await makeApp();
console.log("app", app);
const file = Bun.file(path); const file = Bun.file(path);
const name = makeName("png"); const name = makeName("png");
@@ -55,7 +54,6 @@ describe("MediaController", () => {
body: file, body: file,
}); });
const result = (await res.json()) as any; const result = (await res.json()) as any;
console.log(result);
expect(result.name).toBe(name); expect(result.name).toBe(name);
const destFile = Bun.file(assetsTmpPath + "/" + name); const destFile = Bun.file(assetsTmpPath + "/" + name);
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { type FileBody, Storage } from "../../src/media/storage/Storage"; import { type FileBody, Storage } from "../../src/media/storage/Storage";
import * as StorageEvents from "../../src/media/storage/events"; import * as StorageEvents from "../../src/media/storage/events";
import { StorageAdapter } from "media"; import { StorageAdapter } from "media/storage/StorageAdapter";
class TestAdapter extends StorageAdapter { class TestAdapter extends StorageAdapter {
files: Record<string, FileBody> = {}; files: Record<string, FileBody> = {};
+8 -3
View File
@@ -1,13 +1,18 @@
import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { createApp } from "core/test/utils"; import { createApp } from "core/test/utils";
import { AuthController } from "../../src/auth/api/AuthController"; import { AuthController } from "../../src/auth/api/AuthController";
import { em, entity, make, text } from "../../src/data"; import { em, entity, make, text } from "data/prototype";
import { AppAuth, type ModuleBuildContext } from "../../src/modules"; import { AppAuth, type ModuleBuildContext } from "modules";
import { disableConsoleLog, enableConsoleLog } from "../helper"; import { disableConsoleLog, enableConsoleLog } from "../helper";
// @ts-ignore
import { makeCtx, moduleTestSuite } from "./module-test-suite"; import { makeCtx, moduleTestSuite } from "./module-test-suite";
describe("AppAuth", () => { describe("AppAuth", () => {
test.only("...", () => {
const auth = new AppAuth({});
console.log(auth.toJSON());
console.log(auth.config);
});
moduleTestSuite(AppAuth); moduleTestSuite(AppAuth);
let ctx: ModuleBuildContext; let ctx: ModuleBuildContext;
+1 -1
View File
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, test } from "bun:test"; import { beforeEach, describe, expect, test } from "bun:test";
import { parse } from "../../src/core/utils"; import { parse } from "core/utils/schema";
import { fieldsSchema } from "../../src/data/data-schema"; import { fieldsSchema } from "../../src/data/data-schema";
import { AppData, type ModuleBuildContext } from "../../src/modules"; import { AppData, type ModuleBuildContext } from "../../src/modules";
import { makeCtx, moduleTestSuite } from "./module-test-suite"; import { makeCtx, moduleTestSuite } from "./module-test-suite";
+8 -3
View File
@@ -1,12 +1,17 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { registries } from "../../src";
import { createApp } from "core/test/utils"; import { createApp } from "core/test/utils";
import { em, entity, text } from "../../src/data"; import { em, entity, text } from "data/prototype";
import { registries } from "modules/registries";
import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter"; import { StorageLocalAdapter } from "adapter/node/storage/StorageLocalAdapter";
import { AppMedia } from "../../src/modules"; import { AppMedia } from "../../src/media/AppMedia";
import { moduleTestSuite } from "./module-test-suite"; import { moduleTestSuite } from "./module-test-suite";
describe("AppMedia", () => { describe("AppMedia", () => {
test.only("...", () => {
const media = new AppMedia();
console.log(media.toJSON());
});
moduleTestSuite(AppMedia); moduleTestSuite(AppMedia);
test("should allow additional fields", async () => { test("should allow additional fields", async () => {
+8 -10
View File
@@ -1,13 +1,13 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { stripMark } from "../../src/core/utils"; import { s, stripMark } from "core/utils/schema";
import { type TSchema, Type } from "@sinclair/typebox"; import { em, entity, index, text } from "data/prototype";
import { EntityManager, em, entity, index, text } from "../../src/data"; import { EntityManager } from "data/entities/EntityManager";
import { DummyConnection } from "../../src/data/connection/DummyConnection"; import { DummyConnection } from "../../src/data/connection/DummyConnection";
import { Module } from "../../src/modules/Module"; import { Module } from "../../src/modules/Module";
import { ModuleHelper } from "modules/ModuleHelper"; import { ModuleHelper } from "modules/ModuleHelper";
function createModule<Schema extends TSchema>(schema: Schema) { function createModule<Schema extends s.Schema>(schema: Schema) {
class TestModule extends Module<typeof schema> { return class TestModule extends Module<Schema> {
getSchema() { getSchema() {
return schema; return schema;
} }
@@ -17,9 +17,7 @@ function createModule<Schema extends TSchema>(schema: Schema) {
override useForceParse() { override useForceParse() {
return true; return true;
} }
} };
return TestModule;
} }
describe("Module", async () => { describe("Module", async () => {
@@ -27,7 +25,7 @@ describe("Module", async () => {
test("listener", async () => { test("listener", async () => {
let result: any; let result: any;
const module = createModule(Type.Object({ a: Type.String() })); const module = createModule(s.object({ a: s.string() }));
const m = new module({ a: "test" }); const m = new module({ a: "test" });
await m.schema().set({ a: "test2" }); await m.schema().set({ a: "test2" });
@@ -43,7 +41,7 @@ describe("Module", async () => {
describe("db schema", () => { describe("db schema", () => {
class M extends Module { class M extends Module {
override getSchema() { override getSchema() {
return Type.Object({}); return s.object({});
} }
prt = { prt = {
+17 -13
View File
@@ -1,13 +1,13 @@
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import { disableConsoleLog, enableConsoleLog, stripMark } from "core/utils"; import { disableConsoleLog, enableConsoleLog } from "core/utils";
import { Type } from "@sinclair/typebox";
import { Connection, entity, text } from "data";
import { Module } from "modules/Module"; import { Module } from "modules/Module";
import { type ConfigTable, getDefaultConfig, ModuleManager } from "modules/ModuleManager"; import { type ConfigTable, getDefaultConfig, ModuleManager } from "modules/ModuleManager";
import { CURRENT_VERSION, TABLE_NAME } from "modules/migrations"; import { CURRENT_VERSION, TABLE_NAME } from "modules/migrations";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
import { diff } from "core/object/diff"; import { s, stripMark } from "core/utils/schema";
import type { Static } from "@sinclair/typebox"; import { Connection } from "data/connection/Connection";
import { entity, text } from "data/prototype";
describe("ModuleManager", async () => { describe("ModuleManager", async () => {
test("s1: no config, no build", async () => { test("s1: no config, no build", async () => {
@@ -92,7 +92,11 @@ describe("ModuleManager", async () => {
await mm2.build(); await mm2.build();
expect(stripMark(json)).toEqual(stripMark(mm2.configs())); /* console.log({
json,
configs: mm2.configs(),
}); */
//expect(stripMark(json)).toEqual(stripMark(mm2.configs()));
expect(mm2.configs().data.entities?.test).toBeDefined(); expect(mm2.configs().data.entities?.test).toBeDefined();
expect(mm2.configs().data.entities?.test?.fields?.content).toBeDefined(); expect(mm2.configs().data.entities?.test?.fields?.content).toBeDefined();
expect(mm2.get("data").toJSON().entities?.test?.fields?.content).toBeDefined(); expect(mm2.get("data").toJSON().entities?.test?.fields?.content).toBeDefined();
@@ -257,10 +261,10 @@ describe("ModuleManager", async () => {
// @todo: add tests for migrations (check "backup" and new version) // @todo: add tests for migrations (check "backup" and new version)
describe("revert", async () => { describe("revert", async () => {
const failingModuleSchema = Type.Object({ const failingModuleSchema = s.partialObject({
value: Type.Optional(Type.Number()), value: s.number(),
}); });
class FailingModule extends Module<typeof failingModuleSchema> { class FailingModule extends Module<s.Static<typeof failingModuleSchema>> {
getSchema() { getSchema() {
return failingModuleSchema; return failingModuleSchema;
} }
@@ -431,11 +435,11 @@ describe("ModuleManager", async () => {
}); });
describe("validate & revert", () => { describe("validate & revert", () => {
const schema = Type.Object({ const schema = s.object({
value: Type.Array(Type.Number(), { default: [] }), value: s.array(s.number()),
}); });
type SampleSchema = Static<typeof schema>; type SampleSchema = s.Static<typeof schema>;
class Sample extends Module<typeof schema> { class Sample extends Module<SampleSchema> {
getSchema() { getSchema() {
return schema; return schema;
} }
+8 -7
View File
@@ -1,14 +1,13 @@
import { beforeEach, describe, expect, it } from "bun:test"; import { beforeEach, describe, expect, it } from "bun:test";
import { Hono } from "hono"; import { Hono } from "hono";
import { Guard } from "../../src/auth"; import { Guard } from "auth/authorize/Guard";
import { DebugLogger } from "../../src/core"; import { EventManager } from "core/events";
import { EventManager } from "../../src/core/events"; import { EntityManager } from "data/entities/EntityManager";
import { Default, stripMark } from "../../src/core/utils"; import { Module, type ModuleBuildContext } from "modules/Module";
import { EntityManager } from "../../src/data";
import { Module, type ModuleBuildContext } from "../../src/modules/Module";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
import { ModuleHelper } from "modules/ModuleHelper"; import { ModuleHelper } from "modules/ModuleHelper";
import { DebugLogger, McpServer } from "bknd/utils";
export function makeCtx(overrides?: Partial<ModuleBuildContext>): ModuleBuildContext { export function makeCtx(overrides?: Partial<ModuleBuildContext>): ModuleBuildContext {
const { dummyConnection } = getDummyConnection(); const { dummyConnection } = getDummyConnection();
@@ -20,6 +19,7 @@ export function makeCtx(overrides?: Partial<ModuleBuildContext>): ModuleBuildCon
guard: new Guard(), guard: new Guard(),
flags: Module.ctx_flags, flags: Module.ctx_flags,
logger: new DebugLogger(false), logger: new DebugLogger(false),
mcp: new McpServer(),
...overrides, ...overrides,
}; };
return { return {
@@ -45,7 +45,8 @@ export function moduleTestSuite(module: { new (): Module }) {
it("uses the default config", async () => { it("uses the default config", async () => {
const m = new module(); const m = new module();
await m.setContext(ctx).build(); await m.setContext(ctx).build();
expect(stripMark(m.toJSON())).toEqual(Default(m.getSchema(), {})); expect(m.toJSON()).toEqual(m.getSchema().template({}, { withOptional: true }));
//expect(stripMark(m.toJSON())).toEqual(Default(m.getSchema(), {}));
}); });
}); });
} }
+3 -1
View File
@@ -102,7 +102,9 @@ describe("json form", () => {
] satisfies [string, Exclude<JSONSchema, boolean>, boolean][]; ] satisfies [string, Exclude<JSONSchema, boolean>, boolean][];
for (const [pointer, schema, output] of examples) { for (const [pointer, schema, output] of examples) {
expect(utils.isRequired(new Draft2019(schema), pointer, schema)).toBe(output); expect(utils.isRequired(new Draft2019(schema), pointer, schema), `${pointer} `).toBe(
output,
);
} }
}); });
+20 -1
View File
@@ -1,6 +1,24 @@
import pkg from "./package.json" with { type: "json" }; import pkg from "./package.json" with { type: "json" };
import c from "picocolors"; import c from "picocolors";
import { formatNumber } from "core/utils"; import { formatNumber } from "bknd/utils";
import * as esbuild from "esbuild";
if (process.env.DEBUG) {
await esbuild.build({
entryPoints: ["./src/cli/index.ts"],
outdir: "./dist/cli",
platform: "node",
minify: false,
format: "esm",
bundle: true,
external: ["jsonv-ts", "jsonv-ts/*"],
define: {
__isDev: "0",
__version: JSON.stringify(pkg.version),
},
});
process.exit(0);
}
const result = await Bun.build({ const result = await Bun.build({
entrypoints: ["./src/cli/index.ts"], entrypoints: ["./src/cli/index.ts"],
@@ -8,6 +26,7 @@ const result = await Bun.build({
outdir: "./dist/cli", outdir: "./dist/cli",
env: "PUBLIC_*", env: "PUBLIC_*",
minify: true, minify: true,
external: ["jsonv-ts", "jsonv-ts/*"],
define: { define: {
__isDev: "0", __isDev: "0",
__version: JSON.stringify(pkg.version), __version: JSON.stringify(pkg.version),
+96 -83
View File
@@ -1,6 +1,7 @@
import { $ } from "bun"; import { $ } from "bun";
import * as tsup from "tsup"; import * as tsup from "tsup";
import pkg from "./package.json" with { type: "json" }; import pkg from "./package.json" with { type: "json" };
import c from "picocolors";
const args = process.argv.slice(2); const args = process.argv.slice(2);
const watch = args.includes("--watch"); const watch = args.includes("--watch");
@@ -9,6 +10,14 @@ const types = args.includes("--types");
const sourcemap = args.includes("--sourcemap"); const sourcemap = args.includes("--sourcemap");
const clean = args.includes("--clean"); const clean = args.includes("--clean");
// silence tsup
const oldConsole = {
log: console.log,
warn: console.warn,
};
console.log = () => {};
console.warn = () => {};
const define = { const define = {
__isDev: "0", __isDev: "0",
__version: JSON.stringify(pkg.version), __version: JSON.stringify(pkg.version),
@@ -27,11 +36,11 @@ function buildTypes() {
Bun.spawn(["bun", "build:types"], { Bun.spawn(["bun", "build:types"], {
stdout: "inherit", stdout: "inherit",
onExit: () => { onExit: () => {
console.info("Types built"); oldConsole.log(c.cyan("[Types]"), c.green("built"));
Bun.spawn(["bun", "tsc-alias"], { Bun.spawn(["bun", "tsc-alias"], {
stdout: "inherit", stdout: "inherit",
onExit: () => { onExit: () => {
console.info("Types aliased"); oldConsole.log(c.cyan("[Types]"), c.green("aliased"));
types_running = false; types_running = false;
}, },
}); });
@@ -39,6 +48,10 @@ function buildTypes() {
}); });
} }
if (types && !watch) {
buildTypes();
}
let watcher_timeout: any; let watcher_timeout: any;
function delayTypes() { function delayTypes() {
if (!watch || !types) return; if (!watch || !types) return;
@@ -48,57 +61,44 @@ function delayTypes() {
watcher_timeout = setTimeout(buildTypes, 1000); watcher_timeout = setTimeout(buildTypes, 1000);
} }
if (types && !watch) { const dependencies = Object.keys(pkg.dependencies);
buildTypes();
}
function banner(title: string) {
console.info("");
console.info("=".repeat(40));
console.info(title.toUpperCase());
console.info("-".repeat(40));
}
// collection of always-external packages // collection of always-external packages
const external = [ const external = [
...dependencies,
"bun:test", "bun:test",
"node:test", "node:test",
"node:assert/strict", "node:assert/strict",
"@libsql/client", "@libsql/client",
"bknd", "bknd",
/^bknd\/.*/, /^bknd\/.*/,
"jsonv-ts",
/^jsonv-ts\/.*/,
] as const; ] as const;
/** /**
* Building backend and general API * Building backend and general API
*/ */
async function buildApi() { async function buildApi() {
banner("Building API");
await tsup.build({ await tsup.build({
minify, minify,
sourcemap, sourcemap,
watch, watch,
define, define,
entry: [ entry: ["src/index.ts", "src/core/utils/index.ts", "src/plugins/index.ts"],
"src/index.ts",
"src/core/index.ts",
"src/core/utils/index.ts",
"src/data/index.ts",
"src/media/index.ts",
"src/plugins/index.ts",
],
outDir: "dist", outDir: "dist",
external: [...external], external: [...external],
metafile: true, metafile: true,
target: "esnext",
platform: "browser", platform: "browser",
format: ["esm"], format: ["esm"],
splitting: false, splitting: false,
treeshake: true,
loader: { loader: {
".svg": "dataurl", ".svg": "dataurl",
}, },
onSuccess: async () => { onSuccess: async () => {
delayTypes(); delayTypes();
oldConsole.log(c.cyan("[API]"), c.green("built"));
}, },
}); });
} }
@@ -142,7 +142,6 @@ async function buildUi() {
}, },
} satisfies tsup.Options; } satisfies tsup.Options;
banner("Building UI");
await tsup.build({ await tsup.build({
...base, ...base,
entry: ["src/ui/index.ts", "src/ui/main.css", "src/ui/styles.css"], entry: ["src/ui/index.ts", "src/ui/main.css", "src/ui/styles.css"],
@@ -150,10 +149,10 @@ async function buildUi() {
onSuccess: async () => { onSuccess: async () => {
await rewriteClient("./dist/ui/index.js"); await rewriteClient("./dist/ui/index.js");
delayTypes(); delayTypes();
oldConsole.log(c.cyan("[UI]"), c.green("built"));
}, },
}); });
banner("Building Client");
await tsup.build({ await tsup.build({
...base, ...base,
entry: ["src/ui/client/index.ts"], entry: ["src/ui/client/index.ts"],
@@ -161,6 +160,7 @@ async function buildUi() {
onSuccess: async () => { onSuccess: async () => {
await rewriteClient("./dist/ui/client/index.js"); await rewriteClient("./dist/ui/client/index.js");
delayTypes(); delayTypes();
oldConsole.log(c.cyan("[UI]"), "Client", c.green("built"));
}, },
}); });
} }
@@ -171,7 +171,6 @@ async function buildUi() {
* - ui/client is external, and after built replaced with "bknd/client" * - ui/client is external, and after built replaced with "bknd/client"
*/ */
async function buildUiElements() { async function buildUiElements() {
banner("Building UI Elements");
await tsup.build({ await tsup.build({
minify, minify,
sourcemap, sourcemap,
@@ -205,6 +204,7 @@ async function buildUiElements() {
onSuccess: async () => { onSuccess: async () => {
await rewriteClient("./dist/ui/elements/index.js"); await rewriteClient("./dist/ui/elements/index.js");
delayTypes(); delayTypes();
oldConsole.log(c.cyan("[UI]"), "Elements", c.green("built"));
}, },
}); });
} }
@@ -225,6 +225,7 @@ function baseConfig(adapter: string, overrides: Partial<tsup.Options> = {}): tsu
splitting: false, splitting: false,
onSuccess: async () => { onSuccess: async () => {
delayTypes(); delayTypes();
oldConsole.log(c.cyan("[Adapter]"), adapter || "base", c.green("built"));
}, },
...overrides, ...overrides,
define: { define: {
@@ -233,7 +234,7 @@ function baseConfig(adapter: string, overrides: Partial<tsup.Options> = {}): tsu
}, },
external: [ external: [
/^cloudflare*/, /^cloudflare*/,
/^@?(hono).*?/, /^@?hono.*?/,
/^(bknd|react|next|node).*?/, /^(bknd|react|next|node).*?/,
/.*\.(html)$/, /.*\.(html)$/,
...external, ...external,
@@ -243,65 +244,77 @@ function baseConfig(adapter: string, overrides: Partial<tsup.Options> = {}): tsu
} }
async function buildAdapters() { async function buildAdapters() {
banner("Building Adapters"); await Promise.all([
// base adapter handles // base adapter handles
await tsup.build({ tsup.build({
...baseConfig(""), ...baseConfig(""),
entry: ["src/adapter/index.ts"], target: "esnext",
outDir: "dist/adapter", platform: "neutral",
}); entry: ["src/adapter/index.ts"],
outDir: "dist/adapter",
}),
// specific adatpers // specific adatpers
await tsup.build(baseConfig("react-router")); tsup.build(baseConfig("react-router")),
await tsup.build( tsup.build(
baseConfig("bun", { baseConfig("bun", {
external: [/^bun\:.*/],
}),
),
tsup.build(baseConfig("astro")),
tsup.build(baseConfig("aws")),
tsup.build(
baseConfig("cloudflare", {
external: ["wrangler", "node:process"],
}),
),
tsup.build(
baseConfig("cloudflare/proxy", {
entry: ["src/adapter/cloudflare/proxy.ts"],
outDir: "dist/adapter/cloudflare",
metafile: false,
external: [/bknd/, "wrangler", "node:process"],
}),
),
tsup.build({
...baseConfig("vite"),
platform: "node",
}),
tsup.build({
...baseConfig("nextjs"),
platform: "node",
}),
tsup.build({
...baseConfig("node"),
platform: "node",
}),
tsup.build({
...baseConfig("sqlite/edge"),
entry: ["src/adapter/sqlite/edge.ts"],
outDir: "dist/adapter/sqlite",
metafile: false,
}),
tsup.build({
...baseConfig("sqlite/node"),
entry: ["src/adapter/sqlite/node.ts"],
outDir: "dist/adapter/sqlite",
platform: "node",
metafile: false,
}),
tsup.build({
...baseConfig("sqlite/bun"),
entry: ["src/adapter/sqlite/bun.ts"],
outDir: "dist/adapter/sqlite",
metafile: false,
external: [/^bun\:.*/], external: [/^bun\:.*/],
}), }),
); ]);
await tsup.build(baseConfig("astro"));
await tsup.build(baseConfig("aws"));
await tsup.build(baseConfig("cloudflare"));
await tsup.build({
...baseConfig("vite"),
platform: "node",
});
await tsup.build({
...baseConfig("nextjs"),
platform: "node",
});
await tsup.build({
...baseConfig("node"),
platform: "node",
});
await tsup.build({
...baseConfig("sqlite/edge"),
entry: ["src/adapter/sqlite/edge.ts"],
outDir: "dist/adapter/sqlite",
metafile: false,
});
await tsup.build({
...baseConfig("sqlite/node"),
entry: ["src/adapter/sqlite/node.ts"],
outDir: "dist/adapter/sqlite",
platform: "node",
metafile: false,
});
await tsup.build({
...baseConfig("sqlite/bun"),
entry: ["src/adapter/sqlite/bun.ts"],
outDir: "dist/adapter/sqlite",
metafile: false,
external: [/^bun\:.*/],
});
} }
await buildApi(); await Promise.all([buildApi(), buildUi(), buildUiElements(), buildAdapters()]);
await buildUi();
await buildUiElements();
await buildAdapters();
+2 -1
View File
@@ -2,4 +2,5 @@
#registry = "http://localhost:4873" #registry = "http://localhost:4873"
[test] [test]
coverageSkipTestFiles = true coverageSkipTestFiles = true
console.depth = 10
+6 -6
View File
@@ -17,7 +17,7 @@ async function run(
}); });
// Read from stdout // Read from stdout
const reader = proc.stdout.getReader(); const reader = (proc.stdout as ReadableStream).getReader();
const decoder = new TextDecoder(); const decoder = new TextDecoder();
// Function to read chunks // Function to read chunks
@@ -30,7 +30,7 @@ async function run(
const text = decoder.decode(value); const text = decoder.decode(value);
if (!resolveCalled) { if (!resolveCalled) {
console.log(c.dim(text.replace(/\n$/, ""))); console.info(c.dim(text.replace(/\n$/, "")));
} }
onChunk( onChunk(
text, text,
@@ -189,21 +189,21 @@ const adapters = {
async function testAdapter(name: keyof typeof adapters) { async function testAdapter(name: keyof typeof adapters) {
const config = adapters[name]; const config = adapters[name];
console.log("adapter", c.cyan(name)); console.info("adapter", c.cyan(name));
await config.clean(); await config.clean();
const { proc, data } = await config.start(); const { proc, data } = await config.start();
console.log("proc:", proc.pid, "data:", c.cyan(data)); console.info("proc:", proc.pid, "data:", c.cyan(data));
//proc.kill();process.exit(0); //proc.kill();process.exit(0);
const add_env = "env" in config && config.env ? config.env : ""; const add_env = "env" in config && config.env ? config.env : "";
await $`TEST_URL=${data} TEST_ADAPTER=${name} ${add_env} bun run test:e2e`; await $`TEST_URL=${data} TEST_ADAPTER=${name} ${add_env} bun run test:e2e`;
console.log("DONE!"); console.info("DONE!");
while (!proc.killed) { while (!proc.killed) {
proc.kill("SIGINT"); proc.kill("SIGINT");
await Bun.sleep(250); await Bun.sleep(250);
console.log("Waiting for process to exit..."); console.info("Waiting for process to exit...");
} }
} }
+36
View File
@@ -0,0 +1,36 @@
import { createApp } from "bknd/adapter/bun";
async function generate() {
console.info("Generating MCP documentation...");
const app = await createApp({
initialConfig: {
server: {
mcp: {
enabled: true,
path: "/mcp",
},
},
auth: {
enabled: true,
},
media: {
enabled: true,
adapter: {
type: "local",
config: {
path: "./",
},
},
},
},
});
await app.build();
const res = await app.server.request("/mcp?explain=1");
const { tools, resources } = await res.json();
await Bun.write("../docs/mcp.json", JSON.stringify({ tools, resources }, null, 2));
console.info("MCP documentation generated.");
}
void generate();
+22 -32
View File
@@ -3,7 +3,7 @@
"type": "module", "type": "module",
"sideEffects": false, "sideEffects": false,
"bin": "./dist/cli/index.js", "bin": "./dist/cli/index.js",
"version": "0.15.0", "version": "0.17.2",
"description": "Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.", "description": "Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.",
"homepage": "https://bknd.io", "homepage": "https://bknd.io",
"repository": { "repository": {
@@ -13,8 +13,9 @@
"bugs": { "bugs": {
"url": "https://github.com/bknd-io/bknd/issues" "url": "https://github.com/bknd-io/bknd/issues"
}, },
"packageManager": "bun@1.2.19",
"engines": { "engines": {
"node": ">=22" "node": ">=22.13"
}, },
"scripts": { "scripts": {
"dev": "BKND_CLI_LOG_LEVEL=debug vite", "dev": "BKND_CLI_LOG_LEVEL=debug vite",
@@ -29,7 +30,7 @@
"build:types": "tsc -p tsconfig.build.json --emitDeclarationOnly && tsc-alias", "build:types": "tsc -p tsconfig.build.json --emitDeclarationOnly && tsc-alias",
"updater": "bun x npm-check-updates -ui", "updater": "bun x npm-check-updates -ui",
"cli": "LOCAL=1 bun src/cli/index.ts", "cli": "LOCAL=1 bun src/cli/index.ts",
"prepublishOnly": "bun run types && bun run test && bun run test:node && bun run test:e2e && bun run build:all && cp ../README.md ./", "prepublishOnly": "bun run types && bun run test && bun run test:node && VITE_DB_URL=:memory: bun run test:e2e && bun run build:all && cp ../README.md ./",
"postpublish": "rm -f README.md", "postpublish": "rm -f README.md",
"test": "ALL_TESTS=1 bun test --bail", "test": "ALL_TESTS=1 bun test --bail",
"test:all": "bun run test && bun run test:node", "test:all": "bun run test && bun run test:node",
@@ -40,9 +41,10 @@
"test:vitest:coverage": "vitest run --coverage", "test:vitest:coverage": "vitest run --coverage",
"test:e2e": "playwright test", "test:e2e": "playwright test",
"test:e2e:adapters": "bun run e2e/adapters.ts", "test:e2e:adapters": "bun run e2e/adapters.ts",
"test:e2e:ui": "playwright test --ui", "test:e2e:ui": "VITE_DB_URL=:memory: playwright test --ui",
"test:e2e:debug": "playwright test --debug", "test:e2e:debug": "VITE_DB_URL=:memory: playwright test --debug",
"test:e2e:report": "playwright show-report" "test:e2e:report": "VITE_DB_URL=:memory: playwright show-report",
"docs:build-assets": "bun internal/docs.build-assets.ts"
}, },
"license": "FSL-1.1-MIT", "license": "FSL-1.1-MIT",
"dependencies": { "dependencies": {
@@ -53,7 +55,6 @@
"@hono/swagger-ui": "^0.5.1", "@hono/swagger-ui": "^0.5.1",
"@mantine/core": "^7.17.1", "@mantine/core": "^7.17.1",
"@mantine/hooks": "^7.17.1", "@mantine/hooks": "^7.17.1",
"@sinclair/typebox": "0.34.30",
"@tanstack/react-form": "^1.0.5", "@tanstack/react-form": "^1.0.5",
"@uiw/react-codemirror": "^4.23.10", "@uiw/react-codemirror": "^4.23.10",
"@xyflow/react": "^12.4.4", "@xyflow/react": "^12.4.4",
@@ -61,25 +62,25 @@
"bcryptjs": "^3.0.2", "bcryptjs": "^3.0.2",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"fast-xml-parser": "^5.0.8", "fast-xml-parser": "^5.0.8",
"hono": "^4.7.11", "hono": "4.8.3",
"json-schema-form-react": "^0.0.2",
"json-schema-library": "10.0.0-rc7", "json-schema-library": "10.0.0-rc7",
"json-schema-to-ts": "^3.1.1", "json-schema-to-ts": "^3.1.1",
"jsonv-ts": "^0.1.0", "jsonv-ts": "0.8.2",
"kysely": "^0.27.6", "kysely": "0.27.6",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"oauth4webapi": "^2.11.1", "oauth4webapi": "^2.11.1",
"object-path-immutable": "^4.1.2", "object-path-immutable": "^4.1.2",
"radix-ui": "^1.1.3", "radix-ui": "^1.1.3",
"picocolors": "^1.1.1",
"swr": "^2.3.3" "swr": "^2.3.3"
}, },
"devDependencies": { "devDependencies": {
"@aws-sdk/client-s3": "^3.758.0", "@aws-sdk/client-s3": "^3.758.0",
"@bluwy/giget-core": "^0.1.2", "@bluwy/giget-core": "^0.1.2",
"@clack/prompts": "^0.11.0",
"@cloudflare/vitest-pool-workers": "^0.8.38", "@cloudflare/vitest-pool-workers": "^0.8.38",
"@cloudflare/workers-types": "^4.20250606.0", "@cloudflare/workers-types": "^4.20250606.0",
"@dagrejs/dagre": "^1.1.4", "@dagrejs/dagre": "^1.1.4",
"@hono/typebox-validator": "^0.3.3",
"@hono/vite-dev-server": "^0.19.1", "@hono/vite-dev-server": "^0.19.1",
"@hookform/resolvers": "^4.1.3", "@hookform/resolvers": "^4.1.3",
"@libsql/client": "^0.15.9", "@libsql/client": "^0.15.9",
@@ -87,6 +88,7 @@
"@mantine/notifications": "^7.17.1", "@mantine/notifications": "^7.17.1",
"@playwright/test": "^1.51.1", "@playwright/test": "^1.51.1",
"@rjsf/core": "5.22.2", "@rjsf/core": "5.22.2",
"@standard-schema/spec": "^1.0.0",
"@tabler/icons-react": "3.18.0", "@tabler/icons-react": "3.18.0",
"@tailwindcss/postcss": "^4.0.12", "@tailwindcss/postcss": "^4.0.12",
"@tailwindcss/vite": "^4.0.12", "@tailwindcss/vite": "^4.0.12",
@@ -107,7 +109,6 @@
"libsql-stateless-easy": "^1.8.0", "libsql-stateless-easy": "^1.8.0",
"open": "^10.1.0", "open": "^10.1.0",
"openapi-types": "^12.1.3", "openapi-types": "^12.1.3",
"picocolors": "^1.1.1",
"postcss": "^8.5.3", "postcss": "^8.5.3",
"postcss-preset-mantine": "^1.17.0", "postcss-preset-mantine": "^1.17.0",
"postcss-simple-vars": "^7.0.1", "postcss-simple-vars": "^7.0.1",
@@ -126,6 +127,7 @@
"tsx": "^4.19.3", "tsx": "^4.19.3",
"uuid": "^11.1.0", "uuid": "^11.1.0",
"vite": "^6.3.5", "vite": "^6.3.5",
"vite-plugin-circular-dependency": "^0.5.0",
"vite-tsconfig-paths": "^5.1.4", "vite-tsconfig-paths": "^5.1.4",
"vitest": "^3.0.9", "vitest": "^3.0.9",
"wouter": "^3.6.0" "wouter": "^3.6.0"
@@ -161,16 +163,6 @@
"import": "./dist/ui/client/index.js", "import": "./dist/ui/client/index.js",
"require": "./dist/ui/client/index.js" "require": "./dist/ui/client/index.js"
}, },
"./data": {
"types": "./dist/types/data/index.d.ts",
"import": "./dist/data/index.js",
"require": "./dist/data/index.js"
},
"./core": {
"types": "./dist/types/core/index.d.ts",
"import": "./dist/core/index.js",
"require": "./dist/core/index.js"
},
"./utils": { "./utils": {
"types": "./dist/types/core/utils/index.d.ts", "types": "./dist/types/core/utils/index.d.ts",
"import": "./dist/core/utils/index.js", "import": "./dist/core/utils/index.js",
@@ -181,11 +173,6 @@
"import": "./dist/cli/index.js", "import": "./dist/cli/index.js",
"require": "./dist/cli/index.js" "require": "./dist/cli/index.js"
}, },
"./media": {
"types": "./dist/types/media/index.d.ts",
"import": "./dist/media/index.js",
"require": "./dist/media/index.js"
},
"./plugins": { "./plugins": {
"types": "./dist/types/plugins/index.d.ts", "types": "./dist/types/plugins/index.d.ts",
"import": "./dist/plugins/index.js", "import": "./dist/plugins/index.js",
@@ -210,6 +197,11 @@
"import": "./dist/adapter/cloudflare/index.js", "import": "./dist/adapter/cloudflare/index.js",
"require": "./dist/adapter/cloudflare/index.js" "require": "./dist/adapter/cloudflare/index.js"
}, },
"./adapter/cloudflare/proxy": {
"types": "./dist/types/adapter/cloudflare/proxy.d.ts",
"import": "./dist/adapter/cloudflare/proxy.js",
"require": "./dist/adapter/cloudflare/proxy.js"
},
"./adapter": { "./adapter": {
"types": "./dist/types/adapter/index.d.ts", "types": "./dist/types/adapter/index.d.ts",
"import": "./dist/adapter/index.js" "import": "./dist/adapter/index.js"
@@ -251,15 +243,13 @@
}, },
"./dist/main.css": "./dist/ui/main.css", "./dist/main.css": "./dist/ui/main.css",
"./dist/styles.css": "./dist/ui/styles.css", "./dist/styles.css": "./dist/ui/styles.css",
"./dist/manifest.json": "./dist/static/.vite/manifest.json" "./dist/manifest.json": "./dist/static/.vite/manifest.json",
"./static/*": "./dist/static/*"
}, },
"typesVersions": { "typesVersions": {
"*": { "*": {
"data": ["./dist/types/data/index.d.ts"],
"core": ["./dist/types/core/index.d.ts"],
"utils": ["./dist/types/core/utils/index.d.ts"], "utils": ["./dist/types/core/utils/index.d.ts"],
"cli": ["./dist/types/cli/index.d.ts"], "cli": ["./dist/types/cli/index.d.ts"],
"media": ["./dist/types/media/index.d.ts"],
"plugins": ["./dist/types/plugins/index.d.ts"], "plugins": ["./dist/types/plugins/index.d.ts"],
"adapter": ["./dist/types/adapter/index.d.ts"], "adapter": ["./dist/types/adapter/index.d.ts"],
"adapter/cloudflare": ["./dist/types/adapter/cloudflare/index.d.ts"], "adapter/cloudflare": ["./dist/types/adapter/cloudflare/index.d.ts"],
+3 -3
View File
@@ -1,10 +1,10 @@
import type { SafeUser } from "auth"; import type { SafeUser } from "bknd";
import { AuthApi, type AuthApiOptions } from "auth/api/AuthApi"; import { AuthApi, type AuthApiOptions } from "auth/api/AuthApi";
import { DataApi, type DataApiOptions } from "data/api/DataApi"; import { DataApi, type DataApiOptions } from "data/api/DataApi";
import { decode } from "hono/jwt"; import { decode } from "hono/jwt";
import { MediaApi, type MediaApiOptions } from "media/api/MediaApi"; import { MediaApi, type MediaApiOptions } from "media/api/MediaApi";
import { SystemApi } from "modules/SystemApi"; import { SystemApi } from "modules/SystemApi";
import { omitKeys } from "core/utils"; import { omitKeys } from "bknd/utils";
import type { BaseModuleApiOptions } from "modules"; import type { BaseModuleApiOptions } from "modules";
export type TApiUser = SafeUser; export type TApiUser = SafeUser;
@@ -43,7 +43,7 @@ export type ApiOptions = {
} & ( } & (
| { | {
token?: string; token?: string;
user?: TApiUser; user?: TApiUser | null;
} }
| { | {
request: Request; request: Request;
+49 -4
View File
@@ -1,5 +1,5 @@
import type { CreateUserPayload } from "auth/AppAuth"; import type { CreateUserPayload } from "auth/AppAuth";
import { $console } from "core/utils"; import { $console, McpClient } from "bknd/utils";
import { Event } from "core/events"; import { Event } from "core/events";
import type { em as prototypeEm } from "data/prototype"; import type { em as prototypeEm } from "data/prototype";
import { Connection } from "data/connection/Connection"; import { Connection } from "data/connection/Connection";
@@ -23,13 +23,34 @@ import type { IEmailDriver, ICacheDriver } from "core/drivers";
import { Api, type ApiOptions } from "Api"; import { Api, type ApiOptions } from "Api";
export type AppPluginConfig = { export type AppPluginConfig = {
/**
* The name of the plugin.
*/
name: string; name: string;
/**
* The schema of the plugin.
*/
schema?: () => MaybePromise<ReturnType<typeof prototypeEm> | void>; schema?: () => MaybePromise<ReturnType<typeof prototypeEm> | void>;
/**
* Called before the app is built.
*/
beforeBuild?: () => MaybePromise<void>; beforeBuild?: () => MaybePromise<void>;
/**
* Called after the app is built.
*/
onBuilt?: () => MaybePromise<void>; onBuilt?: () => MaybePromise<void>;
/**
* Called when the server is initialized.
*/
onServerInit?: (server: Hono<ServerEnv>) => MaybePromise<void>; onServerInit?: (server: Hono<ServerEnv>) => MaybePromise<void>;
onFirstBoot?: () => MaybePromise<void>; /**
* Called when the app is booted.
*/
onBoot?: () => MaybePromise<void>; onBoot?: () => MaybePromise<void>;
/**
* Called when the app is first booted.
*/
onFirstBoot?: () => MaybePromise<void>;
}; };
export type AppPlugin = (app: App) => AppPluginConfig; export type AppPlugin = (app: App) => AppPluginConfig;
@@ -40,6 +61,9 @@ export class AppConfigUpdatedEvent extends AppEvent<{
}> { }> {
static override slug = "app-config-updated"; static override slug = "app-config-updated";
} }
/**
* @type {Event<{ app: App }>}
*/
export class AppBuiltEvent extends AppEvent { export class AppBuiltEvent extends AppEvent {
static override slug = "app-built"; static override slug = "app-built";
} }
@@ -71,6 +95,9 @@ export type AppOptions = {
}; };
}; };
export type CreateAppConfig = { export type CreateAppConfig = {
/**
* bla
*/
connection?: Connection | { url: string }; connection?: Connection | { url: string };
initialConfig?: InitialModuleConfigs; initialConfig?: InitialModuleConfigs;
options?: AppOptions; options?: AppOptions;
@@ -90,6 +117,7 @@ export class App<C extends Connection = Connection, Options extends AppOptions =
private trigger_first_boot = false; private trigger_first_boot = false;
private _building: boolean = false; private _building: boolean = false;
private _systemController: SystemController | null = null;
constructor( constructor(
public connection: C, public connection: C,
@@ -162,11 +190,12 @@ export class App<C extends Connection = Connection, Options extends AppOptions =
if (options?.sync) this.modules.ctx().flags.sync_required = true; if (options?.sync) this.modules.ctx().flags.sync_required = true;
await this.modules.build({ fetch: options?.fetch }); await this.modules.build({ fetch: options?.fetch });
const { guard, server } = this.modules.ctx(); const { guard } = this.modules.ctx();
// load system controller // load system controller
guard.registerPermissions(Object.values(SystemPermissions)); guard.registerPermissions(Object.values(SystemPermissions));
server.route("/api/system", new SystemController(this).getController()); this._systemController = new SystemController(this);
this._systemController.register(this);
// emit built event // emit built event
$console.log("App built"); $console.log("App built");
@@ -198,6 +227,10 @@ export class App<C extends Connection = Connection, Options extends AppOptions =
return this.modules.ctx().em; return this.modules.ctx().em;
} }
get mcp() {
return this._systemController?._mcpServer;
}
get fetch(): Hono["fetch"] { get fetch(): Hono["fetch"] {
return this.server.fetch as any; return this.server.fetch as any;
} }
@@ -256,6 +289,18 @@ export class App<C extends Connection = Connection, Options extends AppOptions =
return new Api({ host: "http://localhost", ...(options ?? {}), fetcher }); return new Api({ host: "http://localhost", ...(options ?? {}), fetcher });
} }
getMcpClient() {
if (!this.mcp) {
throw new Error("MCP is not enabled");
}
const mcpPath = this.modules.get("server").config.mcp.path;
return new McpClient({
url: "http://localhost" + mcpPath,
fetch: this.server.request,
});
}
async onUpdated<Module extends keyof Modules>(module: Module, config: ModuleConfigs[Module]) { async onUpdated<Module extends keyof Modules>(module: Module, config: ModuleConfigs[Module]) {
// if the EventManager was disabled, we assume we shouldn't // if the EventManager was disabled, we assume we shouldn't
// respond to events, such as "onUpdated". // respond to events, such as "onUpdated".
+2 -2
View File
@@ -53,7 +53,7 @@ export function adapterTestSuite<
url: overrides.dbUrl ?? ":memory:", url: overrides.dbUrl ?? ":memory:",
origin: "localhost", origin: "localhost",
} as any, } as any,
{ id }, { force: false, id },
); );
expect(app).toBeDefined(); expect(app).toBeDefined();
expect(app.toJSON().server.cors.origin).toEqual("localhost"); expect(app.toJSON().server.cors.origin).toEqual("localhost");
@@ -69,7 +69,7 @@ export function adapterTestSuite<
}; };
test("responds with the same app id", async () => { test("responds with the same app id", async () => {
const fetcher = makeHandler(undefined, undefined, { id }); const fetcher = makeHandler(undefined, undefined, { force: false, id });
const { res, data } = await getConfig(fetcher); const { res, data } = await getConfig(fetcher);
expect(res.ok).toBe(true); expect(res.ok).toBe(true);
+9 -4
View File
@@ -3,16 +3,15 @@
import path from "node:path"; import path from "node:path";
import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter"; import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter";
import { registerLocalMediaAdapter } from "."; import { registerLocalMediaAdapter } from ".";
import { config } from "bknd/core"; import { config, type App } from "bknd";
import type { ServeOptions } from "bun"; import type { ServeOptions } from "bun";
import { serveStatic } from "hono/bun"; import { serveStatic } from "hono/bun";
import type { App } from "App";
type BunEnv = Bun.Env; type BunEnv = Bun.Env;
export type BunBkndConfig<Env = BunEnv> = RuntimeBkndConfig<Env> & Omit<ServeOptions, "fetch">; export type BunBkndConfig<Env = BunEnv> = RuntimeBkndConfig<Env> & Omit<ServeOptions, "fetch">;
export async function createApp<Env = BunEnv>( export async function createApp<Env = BunEnv>(
{ distPath, ...config }: BunBkndConfig<Env> = {}, { distPath, serveStatic: _serveStatic, ...config }: BunBkndConfig<Env> = {},
args: Env = {} as Env, args: Env = {} as Env,
opts?: RuntimeOptions, opts?: RuntimeOptions,
) { ) {
@@ -21,8 +20,12 @@ export async function createApp<Env = BunEnv>(
return await createRuntimeApp( return await createRuntimeApp(
{ {
serveStatic:
_serveStatic ??
serveStatic({
root,
}),
...config, ...config,
serveStatic: serveStatic({ root }),
}, },
args ?? (process.env as Env), args ?? (process.env as Env),
opts, opts,
@@ -53,6 +56,7 @@ export function serve<Env = BunEnv>(
onBuilt, onBuilt,
buildConfig, buildConfig,
adminOptions, adminOptions,
serveStatic,
...serveOptions ...serveOptions
}: BunBkndConfig<Env> = {}, }: BunBkndConfig<Env> = {},
args: Env = {} as Env, args: Env = {} as Env,
@@ -70,6 +74,7 @@ export function serve<Env = BunEnv>(
buildConfig, buildConfig,
adminOptions, adminOptions,
distPath, distPath,
serveStatic,
}, },
args, args,
opts, opts,
@@ -1,5 +1,5 @@
import { Database } from "bun:sqlite"; import { Database } from "bun:sqlite";
import { genericSqlite, type GenericSqliteConnection } from "bknd/data"; import { genericSqlite, type GenericSqliteConnection } from "bknd";
export type BunSqliteConnection = GenericSqliteConnection<Database>; export type BunSqliteConnection = GenericSqliteConnection<Database>;
export type BunSqliteConnectionConfig = { export type BunSqliteConnectionConfig = {
+7 -1
View File
@@ -1,3 +1,5 @@
import { inspect } from "node:util";
export type BindingTypeMap = { export type BindingTypeMap = {
D1Database: D1Database; D1Database: D1Database;
KVNamespace: KVNamespace; KVNamespace: KVNamespace;
@@ -12,7 +14,11 @@ export function getBindings<T extends GetBindingType>(env: any, type: T): Bindin
const bindings: BindingMap<T>[] = []; const bindings: BindingMap<T>[] = [];
for (const key in env) { for (const key in env) {
try { try {
if (env[key] && (env[key] as any).constructor.name === type) { if (
(env[key] as any).constructor.name === type ||
String(env[key]) === `[object ${type}]` ||
inspect(env[key]).includes(type)
) {
bindings.push({ bindings.push({
key, key,
value: env[key] as BindingTypeMap[T], value: env[key] as BindingTypeMap[T],
@@ -1,10 +1,9 @@
import { afterAll, beforeAll, describe, expect, it } from "bun:test"; import { afterAll, beforeAll, describe, expect, it } from "bun:test";
import { makeApp } from "./modes/fresh"; import { makeConfig, type CloudflareContext } from "./config";
import { makeConfig, type CfMakeConfigArgs } from "./config";
import { disableConsoleLog, enableConsoleLog } from "core/utils"; import { disableConsoleLog, enableConsoleLog } from "core/utils";
import { adapterTestSuite } from "adapter/adapter-test-suite"; import { adapterTestSuite } from "adapter/adapter-test-suite";
import { bunTestRunner } from "adapter/bun/test"; import { bunTestRunner } from "adapter/bun/test";
import type { CloudflareBkndConfig } from "./cloudflare-workers.adapter"; import { type CloudflareBkndConfig, createApp } from "./cloudflare-workers.adapter";
beforeAll(disableConsoleLog); beforeAll(disableConsoleLog);
afterAll(enableConsoleLog); afterAll(enableConsoleLog);
@@ -18,7 +17,7 @@ describe("cf adapter", () => {
}); });
it("makes config", async () => { it("makes config", async () => {
const staticConfig = makeConfig( const staticConfig = await makeConfig(
{ {
connection: { url: DB_URL }, connection: { url: DB_URL },
initialConfig: { data: { basepath: DB_URL } }, initialConfig: { data: { basepath: DB_URL } },
@@ -28,7 +27,7 @@ describe("cf adapter", () => {
expect(staticConfig.initialConfig).toEqual({ data: { basepath: DB_URL } }); expect(staticConfig.initialConfig).toEqual({ data: { basepath: DB_URL } });
expect(staticConfig.connection).toBeDefined(); expect(staticConfig.connection).toBeDefined();
const dynamicConfig = makeConfig( const dynamicConfig = await makeConfig(
{ {
app: (env) => ({ app: (env) => ({
initialConfig: { data: { basepath: env.DB_URL } }, initialConfig: { data: { basepath: env.DB_URL } },
@@ -41,18 +40,19 @@ describe("cf adapter", () => {
expect(dynamicConfig.connection).toBeDefined(); expect(dynamicConfig.connection).toBeDefined();
}); });
adapterTestSuite<CloudflareBkndConfig, CfMakeConfigArgs<any>>(bunTestRunner, { adapterTestSuite<CloudflareBkndConfig, CloudflareContext<any>>(bunTestRunner, {
makeApp: async (c, a, o) => { makeApp: async (c, a, o) => {
return await makeApp(c, { env: a } as any, o); return await createApp(c, { env: a } as any, o);
}, },
makeHandler: (c, a, o) => { makeHandler: (c, a, o) => {
console.log("args", a);
return async (request: any) => { return async (request: any) => {
const app = await makeApp( const app = await createApp(
// needs a fallback, otherwise tries to launch D1 // needs a fallback, otherwise tries to launch D1
c ?? { c ?? {
connection: { url: DB_URL }, connection: { url: DB_URL },
}, },
a!, a as any,
o, o,
); );
return app.fetch(request); return app.fetch(request);
@@ -3,11 +3,10 @@
import type { RuntimeBkndConfig } from "bknd/adapter"; import type { RuntimeBkndConfig } from "bknd/adapter";
import { Hono } from "hono"; import { Hono } from "hono";
import { serveStatic } from "hono/cloudflare-workers"; import { serveStatic } from "hono/cloudflare-workers";
import { getFresh } from "./modes/fresh"; import type { MaybePromise } from "bknd";
import { getCached } from "./modes/cached"; import { $console } from "bknd/utils";
import { getDurable } from "./modes/durable"; import { createRuntimeApp, type RuntimeOptions } from "bknd/adapter";
import type { App } from "bknd"; import { registerAsyncsExecutionContext, makeConfig, type CloudflareContext } from "./config";
import { $console } from "core/utils";
declare global { declare global {
namespace Cloudflare { namespace Cloudflare {
@@ -17,12 +16,10 @@ declare global {
export type CloudflareEnv = Cloudflare.Env; export type CloudflareEnv = Cloudflare.Env;
export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> & { export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> & {
mode?: "warm" | "fresh" | "cache" | "durable"; bindings?: (args: Env) => MaybePromise<{
bindings?: (args: Env) => {
kv?: KVNamespace; kv?: KVNamespace;
dobj?: DurableObjectNamespace;
db?: D1Database; db?: D1Database;
}; }>;
d1?: { d1?: {
session?: boolean; session?: boolean;
transport?: "header" | "cookie"; transport?: "header" | "cookie";
@@ -36,11 +33,31 @@ export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> &
registerMedia?: boolean | ((env: Env) => void); registerMedia?: boolean | ((env: Env) => void);
}; };
export type Context<Env = CloudflareEnv> = { export async function createApp<Env extends CloudflareEnv = CloudflareEnv>(
request: Request; config: CloudflareBkndConfig<Env>,
env: Env; ctx: Partial<CloudflareContext<Env>> = {},
ctx: ExecutionContext; opts: RuntimeOptions = {
}; // by default, require the app to be rebuilt every time
force: true,
},
) {
const appConfig = await makeConfig(
{
...config,
onBuilt: async (app) => {
if (ctx.ctx) {
registerAsyncsExecutionContext(app, ctx?.ctx);
}
await config.onBuilt?.(app);
},
},
ctx,
);
return await createRuntimeApp<Env>(appConfig, ctx?.env, opts);
}
// compatiblity
export const getFresh = createApp;
export function serve<Env extends CloudflareEnv = CloudflareEnv>( export function serve<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env> = {}, config: CloudflareBkndConfig<Env> = {},
@@ -79,25 +96,8 @@ export function serve<Env extends CloudflareEnv = CloudflareEnv>(
} }
} }
const context = { request, env, ctx } as Context<Env>; const context = { request, env, ctx } as CloudflareContext<Env>;
const mode = config.mode ?? "warm"; const app = await createApp(config, context);
let app: App;
switch (mode) {
case "fresh":
app = await getFresh(config, context, { force: true });
break;
case "warm":
app = await getFresh(config, context);
break;
case "cache":
app = await getCached(config, context);
break;
case "durable":
return await getDurable(config, context);
default:
throw new Error(`Unknown mode ${mode}`);
}
return app.fetch(request, env, ctx); return app.fetch(request, env, ctx);
}, },
+14 -14
View File
@@ -1,16 +1,16 @@
/// <reference types="@cloudflare/workers-types" /> /// <reference types="@cloudflare/workers-types" />
import { Connection } from "bknd";
import { sqlite } from "bknd/adapter/sqlite";
import { makeConfig as makeAdapterConfig } from "bknd/adapter";
import { registerMedia } from "./storage/StorageR2Adapter"; import { registerMedia } from "./storage/StorageR2Adapter";
import { getBinding } from "./bindings"; import { getBinding } from "./bindings";
import { d1Sqlite } from "./connection/D1Connection"; import { d1Sqlite } from "./connection/D1Connection";
import { Connection } from "bknd/data";
import type { CloudflareBkndConfig, CloudflareEnv } from "."; import type { CloudflareBkndConfig, CloudflareEnv } from ".";
import { App } from "bknd"; import { App } from "bknd";
import { makeConfig as makeAdapterConfig } from "bknd/adapter"; import type { Context as HonoContext, ExecutionContext } from "hono";
import type { Context, ExecutionContext } from "hono"; import { $console } from "bknd/utils";
import { $console } from "core/utils";
import { setCookie } from "hono/cookie"; import { setCookie } from "hono/cookie";
import { sqlite } from "bknd/adapter/sqlite";
export const constants = { export const constants = {
exec_async_event_id: "cf_register_waituntil", exec_async_event_id: "cf_register_waituntil",
@@ -22,10 +22,10 @@ export const constants = {
}, },
}; };
export type CfMakeConfigArgs<Env extends CloudflareEnv = CloudflareEnv> = { export type CloudflareContext<Env extends CloudflareEnv = CloudflareEnv> = {
env: Env; env: Env;
ctx?: ExecutionContext; ctx: ExecutionContext;
request?: Request; request: Request;
}; };
function getCookieValue(cookies: string | null, name: string) { function getCookieValue(cookies: string | null, name: string) {
@@ -67,7 +67,7 @@ export function d1SessionHelper(config: CloudflareBkndConfig<any>) {
return undefined; return undefined;
}, },
set: (c: Context, d1?: D1DatabaseSession) => { set: (c: HonoContext, d1?: D1DatabaseSession) => {
if (!d1 || !config.d1?.session) return; if (!d1 || !config.d1?.session) return;
const session = d1.getBookmark(); const session = d1.getBookmark();
@@ -89,9 +89,9 @@ export function d1SessionHelper(config: CloudflareBkndConfig<any>) {
} }
let media_registered: boolean = false; let media_registered: boolean = false;
export function makeConfig<Env extends CloudflareEnv = CloudflareEnv>( export async function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>, config: CloudflareBkndConfig<Env>,
args?: CfMakeConfigArgs<Env>, args?: Partial<CloudflareContext<Env>>,
) { ) {
if (!media_registered && config.registerMedia !== false) { if (!media_registered && config.registerMedia !== false) {
if (typeof config.registerMedia === "function") { if (typeof config.registerMedia === "function") {
@@ -102,7 +102,7 @@ export function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
media_registered = true; media_registered = true;
} }
const appConfig = makeAdapterConfig(config, args?.env); const appConfig = await makeAdapterConfig(config, args?.env);
// if connection instance is given, don't do anything // if connection instance is given, don't do anything
// other than checking if D1 session is defined // other than checking if D1 session is defined
@@ -115,12 +115,12 @@ export function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
} }
// if connection is given, try to open with unified sqlite adapter // if connection is given, try to open with unified sqlite adapter
} else if (appConfig.connection) { } else if (appConfig.connection) {
appConfig.connection = sqlite(appConfig.connection); appConfig.connection = sqlite(appConfig.connection) as any;
// if connection is not given, but env is set // if connection is not given, but env is set
// try to make D1 from bindings // try to make D1 from bindings
} else if (args?.env) { } else if (args?.env) {
const bindings = config.bindings?.(args?.env); const bindings = await config.bindings?.(args?.env);
const sessionHelper = d1SessionHelper(config); const sessionHelper = d1SessionHelper(config);
const sessionId = sessionHelper.get(args.request); const sessionId = sessionHelper.get(args.request);
let session: D1DatabaseSession | undefined; let session: D1DatabaseSession | undefined;
@@ -1,6 +1,6 @@
/// <reference types="@cloudflare/workers-types" /> /// <reference types="@cloudflare/workers-types" />
import { genericSqlite, type GenericSqliteConnection } from "bknd/data"; import { genericSqlite, type GenericSqliteConnection } from "bknd";
import type { QueryResult } from "kysely"; import type { QueryResult } from "kysely";
export type D1SqliteConnection = GenericSqliteConnection<D1Database>; export type D1SqliteConnection = GenericSqliteConnection<D1Database>;
@@ -1,18 +1,18 @@
/// <reference types="@cloudflare/workers-types" /> /// <reference types="@cloudflare/workers-types" />
import { genericSqlite, type GenericSqliteConnection } from "bknd/data"; import { genericSqlite, type GenericSqliteConnection } from "bknd";
import type { QueryResult } from "kysely"; import type { QueryResult } from "kysely";
export type D1SqliteConnection = GenericSqliteConnection<D1Database>; export type DoSqliteConnection = GenericSqliteConnection<DurableObjectState["storage"]["sql"]>;
export type DurableObjecSql = DurableObjectState["storage"]["sql"]; export type DurableObjecSql = DurableObjectState["storage"]["sql"];
export type D1ConnectionConfig<DB extends DurableObjecSql> = export type DoConnectionConfig<DB extends DurableObjecSql> =
| DurableObjectState | DurableObjectState
| { | {
sql: DB; sql: DB;
}; };
export function doSqlite<DB extends DurableObjecSql>(config: D1ConnectionConfig<DB>) { export function doSqlite<DB extends DurableObjecSql>(config: DoConnectionConfig<DB>) {
const db = "sql" in config ? config.sql : config.storage.sql; const db = "sql" in config ? config.sql : config.storage.sql;
return genericSqlite( return genericSqlite(
@@ -21,7 +21,7 @@ export function doSqlite<DB extends DurableObjecSql>(config: D1ConnectionConfig<
(utils) => { (utils) => {
// must be async to work with the miniflare mock // must be async to work with the miniflare mock
const getStmt = async (sql: string, parameters?: any[] | readonly any[]) => const getStmt = async (sql: string, parameters?: any[] | readonly any[]) =>
await db.exec(sql, ...(parameters || [])); db.exec(sql, ...(parameters || []));
const mapResult = ( const mapResult = (
cursor: SqlStorageCursor<Record<string, SqlStorageValue>>, cursor: SqlStorageCursor<Record<string, SqlStorageValue>>,
+11 -6
View File
@@ -1,10 +1,14 @@
import { d1Sqlite, type D1ConnectionConfig } from "./connection/D1Connection"; import { d1Sqlite, type D1ConnectionConfig } from "./connection/D1Connection";
export * from "./cloudflare-workers.adapter"; export {
export { makeApp, getFresh } from "./modes/fresh"; getFresh,
export { getCached } from "./modes/cached"; createApp,
export { DurableBkndApp, getDurable } from "./modes/durable"; serve,
type CloudflareEnv,
type CloudflareBkndConfig,
} from "./cloudflare-workers.adapter";
export { d1Sqlite, type D1ConnectionConfig }; export { d1Sqlite, type D1ConnectionConfig };
export { doSqlite, type DoConnectionConfig } from "./connection/DoConnection";
export { export {
getBinding, getBinding,
getBindings, getBindings,
@@ -12,9 +16,10 @@ export {
type GetBindingType, type GetBindingType,
type BindingMap, type BindingMap,
} from "./bindings"; } from "./bindings";
export { constants } from "./config"; export { constants, type CloudflareContext } from "./config";
export { StorageR2Adapter } from "./storage/StorageR2Adapter"; export { StorageR2Adapter, registerMedia } from "./storage/StorageR2Adapter";
export { registries } from "bknd"; export { registries } from "bknd";
export { devFsVitePlugin, devFsWrite } from "./vite";
// for compatibility with old code // for compatibility with old code
export function d1<DB extends D1Database | D1DatabaseSession = D1Database>( export function d1<DB extends D1Database | D1DatabaseSession = D1Database>(
@@ -1,53 +0,0 @@
import { App } from "bknd";
import { createRuntimeApp } from "bknd/adapter";
import type { CloudflareBkndConfig, Context, CloudflareEnv } from "../index";
import { makeConfig, registerAsyncsExecutionContext, constants } from "../config";
export async function getCached<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>,
args: Context<Env>,
) {
const { env, ctx } = args;
const { kv } = config.bindings?.(env)!;
if (!kv) throw new Error("kv namespace is not defined in cloudflare.bindings");
const key = config.key ?? "app";
const cachedConfig = await kv.get(key);
const initialConfig = cachedConfig ? JSON.parse(cachedConfig) : undefined;
async function saveConfig(__config: any) {
ctx.waitUntil(kv!.put(key, JSON.stringify(__config)));
}
const app = await createRuntimeApp(
{
...makeConfig(config, args),
initialConfig,
onBuilt: async (app) => {
registerAsyncsExecutionContext(app, ctx);
app.module.server.client.get(constants.cache_endpoint, async (c) => {
await kv.delete(key);
return c.json({ message: "Cache cleared" });
});
await config.onBuilt?.(app);
},
beforeBuild: async (app) => {
app.emgr.onEvent(
App.Events.AppConfigUpdatedEvent,
async ({ params: { app } }) => {
saveConfig(app.toJSON(true));
},
"sync",
);
await config.beforeBuild?.(app);
},
},
args,
);
if (!cachedConfig) {
saveConfig(app.toJSON(true));
}
return app;
}
-134
View File
@@ -1,134 +0,0 @@
import { DurableObject } from "cloudflare:workers";
import type { App, CreateAppConfig } from "bknd";
import { createRuntimeApp, makeConfig } from "bknd/adapter";
import type { CloudflareBkndConfig, Context, CloudflareEnv } from "../index";
import { constants, registerAsyncsExecutionContext } from "../config";
import { $console } from "core/utils";
export async function getDurable<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>,
ctx: Context<Env>,
) {
const { dobj } = config.bindings?.(ctx.env)!;
if (!dobj) throw new Error("durable object is not defined in cloudflare.bindings");
const key = config.key ?? "app";
if ([config.onBuilt, config.beforeBuild].some((x) => x)) {
$console.warn("onBuilt and beforeBuild are not supported with DurableObject mode");
}
const start = performance.now();
const id = dobj.idFromName(key);
const stub = dobj.get(id) as unknown as DurableBkndApp;
const create_config = makeConfig(config, ctx.env);
const res = await stub.fire(ctx.request, {
config: create_config,
keepAliveSeconds: config.keepAliveSeconds,
});
const headers = new Headers(res.headers);
headers.set("X-TTDO", String(performance.now() - start));
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers,
});
}
export class DurableBkndApp extends DurableObject {
protected id = Math.random().toString(36).slice(2);
protected app?: App;
protected interval?: any;
async fire(
request: Request,
options: {
config: CreateAppConfig;
html?: string;
keepAliveSeconds?: number;
setAdminHtml?: boolean;
},
) {
let buildtime = 0;
if (!this.app) {
const start = performance.now();
const config = options.config;
// change protocol to websocket if libsql
if (
config?.connection &&
"type" in config.connection &&
config.connection.type === "libsql"
) {
//config.connection.config.protocol = "wss";
}
this.app = await createRuntimeApp({
...config,
onBuilt: async (app) => {
registerAsyncsExecutionContext(app, this.ctx);
app.modules.server.get(constants.do_endpoint, async (c) => {
// @ts-ignore
const context: any = c.req.raw.cf ? c.req.raw.cf : c.env.cf;
return c.json({
id: this.id,
keepAliveSeconds: options?.keepAliveSeconds ?? 0,
colo: context.colo,
});
});
await this.onBuilt(app);
},
adminOptions: { html: options.html },
beforeBuild: async (app) => {
await this.beforeBuild(app);
},
});
buildtime = performance.now() - start;
}
if (options?.keepAliveSeconds) {
this.keepAlive(options.keepAliveSeconds);
}
const res = await this.app!.fetch(request);
const headers = new Headers(res.headers);
headers.set("X-BuildTime", buildtime.toString());
headers.set("X-DO-ID", this.id);
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers,
});
}
async onBuilt(app: App) {}
async beforeBuild(app: App) {}
protected keepAlive(seconds: number) {
if (this.interval) {
clearInterval(this.interval);
}
let i = 0;
this.interval = setInterval(() => {
i += 1;
if (i === seconds) {
console.log("cleared");
clearInterval(this.interval);
// ping every 30 seconds
} else if (i % 30 === 0) {
console.log("ping");
this.app?.modules.ctx().connection.ping();
}
}, 1000);
}
}
-29
View File
@@ -1,29 +0,0 @@
import { createRuntimeApp, type RuntimeOptions } from "bknd/adapter";
import type { CloudflareBkndConfig, Context, CloudflareEnv } from "../index";
import { makeConfig, registerAsyncsExecutionContext, type CfMakeConfigArgs } from "../config";
export async function makeApp<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>,
args?: CfMakeConfigArgs<Env>,
opts?: RuntimeOptions,
) {
return await createRuntimeApp<Env>(makeConfig(config, args), args?.env, opts);
}
export async function getFresh<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>,
ctx: Context<Env>,
opts: RuntimeOptions = {},
) {
return await makeApp(
{
...config,
onBuilt: async (app) => {
registerAsyncsExecutionContext(app, ctx.ctx);
await config.onBuilt?.(app);
},
},
ctx,
opts,
);
}
+67
View File
@@ -0,0 +1,67 @@
import {
d1Sqlite,
getBinding,
registerMedia,
type CloudflareBkndConfig,
type CloudflareEnv,
} from "bknd/adapter/cloudflare";
import type { PlatformProxy } from "wrangler";
import process from "node:process";
export type WithPlatformProxyOptions = {
/**
* By default, proxy is used if the PROXY environment variable is set to 1.
* You can override/force this by setting this option.
*/
useProxy?: boolean;
};
export function withPlatformProxy<Env extends CloudflareEnv>(
config?: CloudflareBkndConfig<Env>,
opts?: WithPlatformProxyOptions,
) {
const use_proxy =
typeof opts?.useProxy === "boolean" ? opts.useProxy : process.env.PROXY === "1";
let proxy: PlatformProxy | undefined;
async function getEnv(env?: Env): Promise<Env> {
if (use_proxy) {
if (!proxy) {
const getPlatformProxy = await import("wrangler").then((mod) => mod.getPlatformProxy);
proxy = await getPlatformProxy();
setTimeout(proxy?.dispose, 1000);
}
return proxy.env as unknown as Env;
}
return env || ({} as Env);
}
return {
...config,
beforeBuild: async (app, registries) => {
if (!use_proxy) return;
const env = await getEnv();
registerMedia(env, registries as any);
await config?.beforeBuild?.(app, registries);
},
bindings: async (env) => {
return (await config?.bindings?.(await getEnv(env))) || {};
},
// @ts-ignore
app: async (_env) => {
const env = await getEnv(_env);
if (config?.app === undefined && use_proxy) {
const binding = getBinding(env, "D1Database");
return {
connection: d1Sqlite({
binding: binding.value,
}),
};
} else if (typeof config?.app === "function") {
return config?.app(env);
}
return config?.app || {};
},
} satisfies CloudflareBkndConfig<Env>;
}
@@ -1,22 +1,21 @@
import { registries } from "bknd"; import { registries as $registries, isDebug, guessMimeType } from "bknd";
import { isDebug } from "bknd/core";
// @ts-ignore
import { StringEnum } from "bknd/utils";
import { guessMimeType as guess, StorageAdapter, type FileBody } from "bknd/media";
import { getBindings } from "../bindings"; import { getBindings } from "../bindings";
import * as tb from "@sinclair/typebox"; import { s } from "bknd/utils";
const { Type } = tb; import { StorageAdapter, type FileBody } from "bknd";
export function makeSchema(bindings: string[] = []) { export function makeSchema(bindings: string[] = []) {
return Type.Object( return s.object(
{ {
binding: bindings.length > 0 ? StringEnum(bindings) : Type.Optional(Type.String()), binding: bindings.length > 0 ? s.string({ enum: bindings }) : s.string().optional(),
}, },
{ title: "R2", description: "Cloudflare R2 storage" }, { title: "R2", description: "Cloudflare R2 storage" },
); );
} }
export function registerMedia(env: Record<string, any>) { export function registerMedia(
env: Record<string, any>,
registries: typeof $registries = $registries,
) {
const r2_bindings = getBindings(env, "R2Bucket"); const r2_bindings = getBindings(env, "R2Bucket");
registries.media.register( registries.media.register(
@@ -93,7 +92,7 @@ export class StorageR2Adapter extends StorageAdapter {
const responseHeaders = new Headers({ const responseHeaders = new Headers({
"Accept-Ranges": "bytes", "Accept-Ranges": "bytes",
"Content-Type": guess(key), "Content-Type": guessMimeType(key),
}); });
const range = headers.has("range"); const range = headers.has("range");
@@ -145,7 +144,7 @@ export class StorageR2Adapter extends StorageAdapter {
if (!metadata || Object.keys(metadata).length === 0) { if (!metadata || Object.keys(metadata).length === 0) {
// guessing is especially required for dev environment (miniflare) // guessing is especially required for dev environment (miniflare)
metadata = { metadata = {
contentType: guess(object.key), contentType: guessMimeType(object.key),
}; };
} }
@@ -162,7 +161,7 @@ export class StorageR2Adapter extends StorageAdapter {
} }
return { return {
type: String(head.httpMetadata?.contentType ?? guess(key)), type: String(head.httpMetadata?.contentType ?? guessMimeType(key)),
size: head.size, size: head.size,
}; };
} }
+135
View File
@@ -0,0 +1,135 @@
import type { Plugin } from "vite";
import { writeFile as nodeWriteFile } from "node:fs/promises";
import { resolve } from "node:path";
/**
* Vite plugin that provides Node.js filesystem access during development
* by injecting a polyfill into the SSR environment
*/
export function devFsVitePlugin({
verbose = false,
configFile = "bknd.config.ts",
}: {
verbose?: boolean;
configFile?: string;
} = {}): any {
let isDev = false;
let projectRoot = "";
return {
name: "dev-fs-plugin",
enforce: "pre",
configResolved(config) {
isDev = config.command === "serve";
projectRoot = config.root;
},
configureServer(server) {
if (!isDev) return;
// Intercept stdout to watch for our write requests
const originalStdoutWrite = process.stdout.write;
process.stdout.write = function (chunk: any, encoding?: any, callback?: any) {
const output = chunk.toString();
// Check if this output contains our special write request
if (output.includes("{{DEV_FS_WRITE_REQUEST}}")) {
try {
// Extract the JSON from the log line
const match = output.match(/{{DEV_FS_WRITE_REQUEST}} ({.*})/);
if (match) {
const writeRequest = JSON.parse(match[1]);
if (writeRequest.type === "DEV_FS_WRITE_REQUEST") {
if (verbose) {
console.debug("[dev-fs-plugin] Intercepted write request via stdout");
}
// Process the write request immediately
(async () => {
try {
const fullPath = resolve(projectRoot, writeRequest.filename);
await nodeWriteFile(fullPath, writeRequest.data);
if (verbose) {
console.debug("[dev-fs-plugin] File written successfully!");
}
} catch (error) {
console.error("[dev-fs-plugin] Error writing file:", error);
}
})();
// Don't output the raw write request to console
return true;
}
}
} catch (error) {
// Not a valid write request, continue with normal output
}
}
// @ts-ignore
// biome-ignore lint:
return originalStdoutWrite.apply(process.stdout, arguments);
};
// Restore stdout when server closes
server.httpServer?.on("close", () => {
process.stdout.write = originalStdoutWrite;
});
},
// @ts-ignore
transform(code, id, options) {
// Only transform in SSR mode during development
if (!isDev || !options?.ssr) return;
// Check if this is the bknd config file
if (id.includes(configFile)) {
if (verbose) {
console.debug("[dev-fs-plugin] Transforming", configFile);
}
// Inject our filesystem polyfill at the top of the file
const polyfill = `
// Dev-fs polyfill injected by vite-plugin-dev-fs
if (typeof globalThis !== 'undefined') {
globalThis.__devFsPolyfill = {
writeFile: async (filename, data) => {
${verbose ? "console.debug('dev-fs polyfill: Intercepting write request for', filename);" : ""}
// Use console logging as a communication channel
// The main process will watch for this specific log pattern
const writeRequest = {
type: 'DEV_FS_WRITE_REQUEST',
filename: filename,
data: data,
timestamp: Date.now()
};
// Output as a specially formatted console message
console.log('{{DEV_FS_WRITE_REQUEST}}', JSON.stringify(writeRequest));
${verbose ? "console.debug('dev-fs polyfill: Write request sent via console');" : ""}
return Promise.resolve();
}
};
}
`;
return polyfill + code;
}
},
} satisfies Plugin;
}
// Write function that uses the dev-fs polyfill injected by our Vite plugin
export async function devFsWrite(filename: string, data: string): Promise<void> {
try {
// Check if the dev-fs polyfill is available (injected by our Vite plugin)
if (typeof globalThis !== "undefined" && (globalThis as any).__devFsPolyfill) {
return (globalThis as any).__devFsPolyfill.writeFile(filename, data);
}
// Fallback to Node.js fs for other environments (Node.js, Bun)
const { writeFile } = await import("node:fs/promises");
return writeFile(filename, data);
} catch (error) {
console.error("[dev-fs-write] Error writing file:", error);
}
}
+80 -18
View File
@@ -1,16 +1,21 @@
import { App, type CreateAppConfig } from "bknd"; import {
import { config as $config } from "bknd/core"; config as $config,
App,
type CreateAppConfig,
Connection,
guessMimeType,
type MaybePromise,
registries as $registries,
} from "bknd";
import { $console } from "bknd/utils"; import { $console } from "bknd/utils";
import type { MiddlewareHandler } from "hono"; import type { Context, MiddlewareHandler, Next } from "hono";
import type { AdminControllerOptions } from "modules/server/AdminController"; import type { AdminControllerOptions } from "modules/server/AdminController";
import { Connection } from "bknd/data"; import type { Manifest } from "vite";
export { Connection } from "bknd/data";
export type BkndConfig<Args = any> = CreateAppConfig & { export type BkndConfig<Args = any> = CreateAppConfig & {
app?: CreateAppConfig | ((args: Args) => CreateAppConfig); app?: CreateAppConfig | ((args: Args) => MaybePromise<CreateAppConfig>);
onBuilt?: (app: App) => Promise<void>; onBuilt?: (app: App) => Promise<void>;
beforeBuild?: (app: App) => Promise<void>; beforeBuild?: (app: App, registries?: typeof $registries) => Promise<void>;
buildConfig?: Parameters<App["build"]>[0]; buildConfig?: Parameters<App["build"]>[0];
}; };
@@ -33,10 +38,10 @@ export type DefaultArgs = {
[key: string]: any; [key: string]: any;
}; };
export function makeConfig<Args = DefaultArgs>( export async function makeConfig<Args = DefaultArgs>(
config: BkndConfig<Args>, config: BkndConfig<Args>,
args?: Args, args?: Args,
): CreateAppConfig { ): Promise<CreateAppConfig> {
let additionalConfig: CreateAppConfig = {}; let additionalConfig: CreateAppConfig = {};
const { app, ...rest } = config; const { app, ...rest } = config;
if (app) { if (app) {
@@ -44,7 +49,7 @@ export function makeConfig<Args = DefaultArgs>(
if (!args) { if (!args) {
throw new Error("args is required when config.app is a function"); throw new Error("args is required when config.app is a function");
} }
additionalConfig = app(args); additionalConfig = await app(args);
} else { } else {
additionalConfig = app; additionalConfig = app;
} }
@@ -63,23 +68,27 @@ export async function createAdapterApp<Config extends BkndConfig = BkndConfig, A
const id = opts?.id ?? "app"; const id = opts?.id ?? "app";
let app = apps.get(id); let app = apps.get(id);
if (!app || opts?.force) { if (!app || opts?.force) {
const appConfig = makeConfig(config, args); const appConfig = await makeConfig(config, args);
if (!appConfig.connection || !Connection.isConnection(appConfig.connection)) { if (!appConfig.connection || !Connection.isConnection(appConfig.connection)) {
let connection: Connection | undefined; let connection: Connection | undefined;
if (Connection.isConnection(config.connection)) { if (Connection.isConnection(config.connection)) {
connection = config.connection; connection = config.connection;
} else { } else {
const sqlite = (await import("bknd/adapter/sqlite")).sqlite; const sqlite = (await import("bknd/adapter/sqlite")).sqlite;
const conf = config.connection ?? { url: ":memory:" }; const conf = appConfig.connection ?? { url: ":memory:" };
connection = sqlite(conf); connection = sqlite(conf) as any;
$console.info(`Using ${connection.name} connection`, conf.url); $console.info(`Using ${connection!.name} connection`, conf.url);
} }
appConfig.connection = connection; appConfig.connection = connection;
} }
app = App.create(appConfig); app = App.create(appConfig);
apps.set(id, app);
if (!opts?.force) {
apps.set(id, app);
}
} }
return app; return app;
} }
@@ -101,7 +110,7 @@ export async function createFrameworkApp<Args = DefaultArgs>(
); );
} }
await config.beforeBuild?.(app); await config.beforeBuild?.(app, $registries);
await app.build(config.buildConfig); await app.build(config.buildConfig);
} }
@@ -134,9 +143,62 @@ export async function createRuntimeApp<Args = DefaultArgs>(
"sync", "sync",
); );
await config.beforeBuild?.(app); await config.beforeBuild?.(app, $registries);
await app.build(config.buildConfig); await app.build(config.buildConfig);
} }
return app; return app;
} }
/**
* Creates a middleware handler to serve static assets via dynamic imports.
* This is useful for environments where filesystem access is limited but bundled assets can be imported.
*
* @param manifest - Vite manifest object containing asset information
* @returns Hono middleware handler for serving static assets
*
* @example
* ```typescript
* import { serveStaticViaImport } from "bknd/adapter";
*
* serve({
* serveStatic: serveStaticViaImport(),
* });
* ```
*/
export function serveStaticViaImport(opts?: { manifest?: Manifest }) {
let files: string[] | undefined;
// @ts-ignore
return async (c: Context, next: Next) => {
if (!files) {
const manifest =
opts?.manifest ||
((await import("bknd/dist/manifest.json", { with: { type: "json" } }))
.default as Manifest);
files = Object.values(manifest).flatMap((asset) => [asset.file, ...(asset.css || [])]);
}
const path = c.req.path.substring(1);
if (files.includes(path)) {
try {
const content = await import(/* @vite-ignore */ `bknd/static/${path}?raw`, {
with: { type: "text" },
}).then((m) => m.default);
if (content) {
return c.body(content, {
headers: {
"Content-Type": guessMimeType(path),
"Cache-Control": "public, max-age=31536000, immutable",
},
});
}
} catch (e) {
console.error("Error serving static file:", e);
return c.text("File not found", 404);
}
}
await next();
};
}
@@ -1,4 +1,4 @@
import { genericSqlite } from "bknd/data"; import { genericSqlite } from "bknd";
import { DatabaseSync } from "node:sqlite"; import { DatabaseSync } from "node:sqlite";
export type NodeSqliteConnectionConfig = { export type NodeSqliteConnectionConfig = {
+3 -4
View File
@@ -3,9 +3,8 @@ import { serve as honoServe } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static"; import { serveStatic } from "@hono/node-server/serve-static";
import { registerLocalMediaAdapter } from "adapter/node/storage"; import { registerLocalMediaAdapter } from "adapter/node/storage";
import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter"; import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter";
import { config as $config } from "bknd/core"; import { config as $config, type App } from "bknd";
import { $console } from "core/utils"; import { $console } from "bknd/utils";
import type { App } from "App";
type NodeEnv = NodeJS.ProcessEnv; type NodeEnv = NodeJS.ProcessEnv;
export type NodeBkndConfig<Env = NodeEnv> = RuntimeBkndConfig<Env> & { export type NodeBkndConfig<Env = NodeEnv> = RuntimeBkndConfig<Env> & {
@@ -32,8 +31,8 @@ export async function createApp<Env = NodeEnv>(
registerLocalMediaAdapter(); registerLocalMediaAdapter();
return await createRuntimeApp( return await createRuntimeApp(
{ {
...config,
serveStatic: serveStatic({ root }), serveStatic: serveStatic({ root }),
...config,
}, },
// @ts-ignore // @ts-ignore
args ?? { env: process.env }, args ?? { env: process.env },
@@ -1,17 +1,15 @@
import { readFile, readdir, stat, unlink, writeFile } from "node:fs/promises"; import { readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
import { type Static, isFile, parse } from "bknd/utils"; import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "bknd";
import type { FileBody, FileListObject, FileMeta, FileUploadPayload } from "bknd/media"; import { StorageAdapter, guessMimeType } from "bknd";
import { StorageAdapter, guessMimeType as guess } from "bknd/media"; import { parse, s, isFile } from "bknd/utils";
import * as tb from "@sinclair/typebox";
const { Type } = tb;
export const localAdapterConfig = Type.Object( export const localAdapterConfig = s.object(
{ {
path: Type.String({ default: "./" }), path: s.string({ default: "./" }),
}, },
{ title: "Local", description: "Local file system storage", additionalProperties: false }, { title: "Local", description: "Local file system storage", additionalProperties: false },
); );
export type LocalAdapterConfig = Static<typeof localAdapterConfig>; export type LocalAdapterConfig = s.Static<typeof localAdapterConfig>;
export class StorageLocalAdapter extends StorageAdapter { export class StorageLocalAdapter extends StorageAdapter {
private config: LocalAdapterConfig; private config: LocalAdapterConfig;
@@ -62,8 +60,7 @@ export class StorageLocalAdapter extends StorageAdapter {
} }
const filePath = `${this.config.path}/${key}`; const filePath = `${this.config.path}/${key}`;
const is_file = isFile(body); await writeFile(filePath, isFile(body) ? body.stream() : body);
await writeFile(filePath, is_file ? body.stream() : body);
return await this.computeEtag(body); return await this.computeEtag(body);
} }
@@ -86,7 +83,7 @@ export class StorageLocalAdapter extends StorageAdapter {
async getObject(key: string, headers: Headers): Promise<Response> { async getObject(key: string, headers: Headers): Promise<Response> {
try { try {
const content = await readFile(`${this.config.path}/${key}`); const content = await readFile(`${this.config.path}/${key}`);
const mimeType = guess(key); const mimeType = guessMimeType(key);
return new Response(content, { return new Response(content, {
status: 200, status: 200,
@@ -108,7 +105,7 @@ export class StorageLocalAdapter extends StorageAdapter {
async getObjectMeta(key: string): Promise<FileMeta> { async getObjectMeta(key: string): Promise<FileMeta> {
const stats = await stat(`${this.config.path}/${key}`); const stats = await stat(`${this.config.path}/${key}`);
return { return {
type: guess(key) || "application/octet-stream", type: guessMimeType(key) || "application/octet-stream",
size: stats.size, size: stats.size,
}; };
} }
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Connection } from "bknd/data"; import type { Connection } from "bknd";
import { bunSqlite } from "../bun/connection/BunSqliteConnection"; import { bunSqlite } from "../bun/connection/BunSqliteConnection";
export function sqlite(config?: { url: string }): Connection { export function sqlite(config?: { url: string }): Connection {
+1 -1
View File
@@ -1,4 +1,4 @@
import { type Connection, libsql } from "bknd/data"; import { type Connection, libsql } from "bknd";
export function sqlite(config: { url: string }): Connection { export function sqlite(config: { url: string }): Connection {
return libsql(config); return libsql(config);
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Connection } from "bknd/data"; import type { Connection } from "bknd";
import { nodeSqlite } from "../node/connection/NodeSqliteConnection"; import { nodeSqlite } from "../node/connection/NodeSqliteConnection";
export function sqlite(config?: { url: string }): Connection { export function sqlite(config?: { url: string }): Connection {
+40 -9
View File
@@ -1,8 +1,9 @@
import { Authenticator, AuthPermissions, Role, type Strategy } from "auth"; import type { DB, PrimaryFieldType } from "bknd";
import type { PasswordStrategy } from "auth/authenticate/strategies"; import * as AuthPermissions from "auth/auth-permissions";
import type { DB } from "core"; import type { AuthStrategy } from "auth/authenticate/strategies/Strategy";
import { $console, secureRandomString, transformObject } from "core/utils"; import type { PasswordStrategy } from "auth/authenticate/strategies/PasswordStrategy";
import type { Entity, EntityManager } from "data"; import { $console, secureRandomString, transformObject } from "bknd/utils";
import type { Entity, EntityManager } from "data/entities";
import { em, entity, enumm, type FieldSchema } from "data/prototype"; import { em, entity, enumm, type FieldSchema } from "data/prototype";
import { Module } from "modules/Module"; import { Module } from "modules/Module";
import { AuthController } from "./api/AuthController"; import { AuthController } from "./api/AuthController";
@@ -10,9 +11,12 @@ import { type AppAuthSchema, authConfigSchema, STRATEGIES } from "./auth-schema"
import { AppUserPool } from "auth/AppUserPool"; import { AppUserPool } from "auth/AppUserPool";
import type { AppEntity } from "core/config"; import type { AppEntity } from "core/config";
import { usersFields } from "./auth-entities"; import { usersFields } from "./auth-entities";
import { Authenticator } from "./authenticate/Authenticator";
import { Role } from "./authorize/Role";
export type UsersFields = typeof AppAuth.usersFields;
export type UserFieldSchema = FieldSchema<typeof AppAuth.usersFields>; export type UserFieldSchema = FieldSchema<typeof AppAuth.usersFields>;
declare module "core" { declare module "bknd" {
interface Users extends AppEntity, UserFieldSchema {} interface Users extends AppEntity, UserFieldSchema {}
interface DB { interface DB {
users: Users; users: Users;
@@ -21,7 +25,7 @@ declare module "core" {
export type CreateUserPayload = { email: string; password: string; [key: string]: any }; export type CreateUserPayload = { email: string; password: string; [key: string]: any };
export class AppAuth extends Module<typeof authConfigSchema> { export class AppAuth extends Module<AppAuthSchema> {
private _authenticator?: Authenticator; private _authenticator?: Authenticator;
cache: Record<string, any> = {}; cache: Record<string, any> = {};
_controller!: AuthController; _controller!: AuthController;
@@ -84,11 +88,12 @@ export class AppAuth extends Module<typeof authConfigSchema> {
super.setBuilt(); super.setBuilt();
this._controller = new AuthController(this); this._controller = new AuthController(this);
this._controller.registerMcp();
this.ctx.server.route(this.config.basepath, this._controller.getController()); this.ctx.server.route(this.config.basepath, this._controller.getController());
this.ctx.guard.registerPermissions(AuthPermissions); this.ctx.guard.registerPermissions(AuthPermissions);
} }
isStrategyEnabled(strategy: Strategy | string) { isStrategyEnabled(strategy: AuthStrategy | string) {
const name = typeof strategy === "string" ? strategy : strategy.getName(); const name = typeof strategy === "string" ? strategy : strategy.getName();
// for now, password is always active // for now, password is always active
if (name === "password") return true; if (name === "password") return true;
@@ -173,6 +178,32 @@ export class AppAuth extends Module<typeof authConfigSchema> {
return created; return created;
} }
async changePassword(userId: PrimaryFieldType, newPassword: string) {
const users_entity = this.config.entity_name as "users";
const { data: user } = await this.em.repository(users_entity).findId(userId);
if (!user) {
throw new Error("User not found");
} else if (user.strategy !== "password") {
throw new Error("User is not using password strategy");
}
const togglePw = (visible: boolean) => {
const field = this.em.entity(users_entity).field("strategy_value")!;
field.config.hidden = !visible;
field.config.fillable = visible;
};
const pw = this.authenticator.strategy("password" as const) as PasswordStrategy;
togglePw(true);
await this.em.mutator(users_entity).updateOne(user.id, {
strategy_value: await pw.hash(newPassword),
});
togglePw(false);
return true;
}
override toJSON(secrets?: boolean): AppAuthSchema { override toJSON(secrets?: boolean): AppAuthSchema {
if (!this.config.enabled) { if (!this.config.enabled) {
return this.configDefault; return this.configDefault;
@@ -187,6 +218,6 @@ export class AppAuth extends Module<typeof authConfigSchema> {
enabled: this.isStrategyEnabled(strategy), enabled: this.isStrategyEnabled(strategy),
...strategy.toJSON(secrets), ...strategy.toJSON(secrets),
})), })),
}; } as AppAuthSchema;
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
import { AppAuth } from "auth/AppAuth"; import { AppAuth } from "auth/AppAuth";
import type { CreateUser, SafeUser, User, UserPool } from "auth/authenticate/Authenticator"; import type { CreateUser, SafeUser, User, UserPool } from "auth/authenticate/Authenticator";
import { $console } from "core/utils"; import { $console } from "bknd/utils";
import { pick } from "lodash-es"; import { pick } from "lodash-es";
import { import {
InvalidConditionsException, InvalidConditionsException,
+2 -2
View File
@@ -1,6 +1,6 @@
import type { AuthActionResponse } from "auth/api/AuthController"; import type { AuthActionResponse } from "auth/api/AuthController";
import type { AppAuthSchema } from "auth/auth-schema"; import type { AppAuthSchema } from "auth/auth-schema";
import type { AuthResponse, SafeUser, Strategy } from "auth/authenticate/Authenticator"; import type { AuthResponse, SafeUser, AuthStrategy } from "bknd";
import { type BaseModuleApiOptions, ModuleApi } from "modules/ModuleApi"; import { type BaseModuleApiOptions, ModuleApi } from "modules/ModuleApi";
export type AuthApiOptions = BaseModuleApiOptions & { export type AuthApiOptions = BaseModuleApiOptions & {
@@ -39,7 +39,7 @@ export class AuthApi extends ModuleApi<AuthApiOptions> {
} }
async actionSchema(strategy: string, action: string) { async actionSchema(strategy: string, action: string) {
return this.get<Strategy>([strategy, "actions", action, "schema.json"]); return this.get<AuthStrategy>([strategy, "actions", action, "schema.json"]);
} }
async action(strategy: string, action: string, input: any) { async action(strategy: string, action: string, input: any) {

Some files were not shown because too many files have changed in this diff Show More