@ismaelsoilet/synapsejs 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +206 -0
  3. package/bin/synapse.ts +919 -0
  4. package/package.json +70 -0
  5. package/src/client/components.tsx +508 -0
  6. package/src/client/context.tsx +62 -0
  7. package/src/client/hooks.ts +152 -0
  8. package/src/client/i18n.ts +40 -0
  9. package/src/client.ts +66 -0
  10. package/src/compiler/agent-diagnostic-json.ts +113 -0
  11. package/src/compiler/ast-daemon-compressor.ts +190 -0
  12. package/src/compiler/client-bundler.ts +356 -0
  13. package/src/compiler/context-bench.ts +191 -0
  14. package/src/compiler/contract.ts +260 -0
  15. package/src/compiler/db-schema-generator.ts +306 -0
  16. package/src/compiler/fields-parser.ts +267 -0
  17. package/src/compiler/impact-analyzer.ts +279 -0
  18. package/src/compiler/migration-runner.ts +555 -0
  19. package/src/compiler/oracle-runner.ts +293 -0
  20. package/src/compiler/scaffolder.ts +528 -0
  21. package/src/compiler/schema-dag.ts +137 -0
  22. package/src/compiler/schema-drift.ts +184 -0
  23. package/src/compiler/slice-discovery.ts +154 -0
  24. package/src/compiler/slice-splitter.ts +838 -0
  25. package/src/compiler/slice-templates.ts +1527 -0
  26. package/src/compiler/standalone-builder.ts +117 -0
  27. package/src/core/action-context.ts +152 -0
  28. package/src/core/config.ts +77 -0
  29. package/src/core/database-client.ts +246 -0
  30. package/src/core/database-factory.ts +46 -0
  31. package/src/core/image-optimizer.ts +83 -0
  32. package/src/core/index.ts +14 -0
  33. package/src/core/jobs.ts +53 -0
  34. package/src/core/machine-types.ts +75 -0
  35. package/src/core/oracle.ts +20 -0
  36. package/src/core/postgres-client.ts +164 -0
  37. package/src/core/postgres-queue.ts +288 -0
  38. package/src/core/query-builder.ts +343 -0
  39. package/src/core/rpc-client.ts +70 -0
  40. package/src/core/session-context.ts +87 -0
  41. package/src/core/session-cookie.ts +81 -0
  42. package/src/core/session-token.ts +170 -0
  43. package/src/core/sqlite-client.ts +201 -0
  44. package/src/core/storage.ts +317 -0
  45. package/src/index.ts +133 -0
  46. package/src/mcp/server.ts +553 -0
  47. package/src/runtime/client-entry.ts +65 -0
  48. package/src/runtime/discovery-rules.ts +63 -0
  49. package/src/runtime/event-hub.ts +97 -0
  50. package/src/runtime/postgres-event-hub.ts +148 -0
  51. package/src/runtime/queue-engine.ts +255 -0
  52. package/src/runtime/rate-limiter.ts +152 -0
  53. package/src/runtime/server.ts +1550 -0
  54. package/src/runtime/uploads.ts +192 -0
  55. package/templates/starter/.dockerignore +7 -0
  56. package/templates/starter/Dockerfile +40 -0
  57. package/templates/starter/README.md +40 -0
  58. package/templates/starter/gitignore +6 -0
  59. package/templates/starter/package.json +34 -0
  60. package/templates/starter/src/slices/welcome/hello-world.slice.tsx +172 -0
  61. package/templates/starter/tsconfig.json +21 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ismael Soilet
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,206 @@
1
+ # SynapseJS ⚡
2
+
3
+ > Bun-only fullstack framework where **a feature is a single contiguous file** (`*.slice.tsx`):
4
+ > input contract, database DDL, server action, React UI and test oracle together.
5
+
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
7
+ [![Bun](https://img.shields.io/badge/Bun-v1.2+-black)](https://bun.sh)
8
+
9
+ ## Requirements
10
+
11
+ - Bun **>= 1.2** — this package ships TypeScript source (`main: src/index.ts`), uses `bun:sqlite`,
12
+ `Bun.serve`, `Bun.CryptoHasher` and `Bun.spawn`. It does not run on Node.
13
+
14
+ ```bash
15
+ bun add synapsejs
16
+ ```
17
+
18
+ ## Status
19
+
20
+ Features are listed with the command that fails when they break. Nothing is documented as stable
21
+ without one — see the repository's `AGENTS.md` for the full contract.
22
+
23
+ **Stable:** vertical slices (N = 1) · `Result<T, E>` flows · TypeBox JIT contracts · declarative
24
+ `sliceSchema` migrations with DAG topological ordering · embedded SQLite (WAL, prepared-statement cache, CTE-safe) ·
25
+ isomorphic Query Builder with parameterized relational joins and sub-object nesting (`nestJoinedRow`) · centralized Schema Catalog (`.codebase/db-schema.d.ts`) ·
26
+ declarative UI primitives & hooks (`DataTable`, `DataForm`, `useAction`, `useLoaderData`, `useSubscription`, `SynapseProvider`) ·
27
+ realtime SSE gateway (`EventHub` + `ctx.broadcast`) · schema drift detector (`synapse db-drift`) · AST diff & cross-slice impact analysis (`synapse impact`) ·
28
+ unified Object Storage (Local + S3/R2/MinIO with SigV4 presigned URLs) · distributed PostgreSQL queue (`FOR UPDATE SKIP LOCKED`) ·
29
+ native Tagged SQL (`db.sql` / `db.sqlOne`) · background jobs engine (`defineJob` + `synapse worker`) · webhooks gateway
30
+ with rawBody preservation · B2B multi-tenancy & IDOR prevention (`requireTenant`) · hierarchical UI layouts (`_layout.tsx`)
31
+ and Turbo Morphing router · explicit RBAC via `requireAuth(session, roles)` · zero-wiring routing + SSR + RPC · slice discovery
32
+ that never reports PASS with zero slices · isomorphic splitter with compile and leak gates · typed AST skeleton map ·
33
+ scaffolder with `--fields` grammar and templates (create, list, update, delete, login, oauth-github, crud) · standalone production bundler (`synapse build --standalone`) ·
34
+ MCP stdio server with 10 tools · slice invariants under `bun:test` with per-invariant reporting · PostgreSQL parity · real concurrency & load stress benchmarks.
35
+
36
+ **Roadmap:** down-migrations / DDL rollbacks, multi-region distributed cache adapters (Redis/Dragonfly).
37
+
38
+ The repository README carries a measured context-surface benchmark of the same two features
39
+ implemented with and without the slice convention, including what the numbers do not show.
40
+
41
+ ## API stability
42
+
43
+ `fc` and `MockDatabaseClient` are deliberate parts of the contract, not accidents: slices declare their
44
+ invariants with `fc`, and the oracles use the mock. Both are asserted by
45
+ `packages/synapse/test/machine-types.test.ts` ("public contract"), together with every other export this
46
+ README lists. The same block is the list of what 1.0 will freeze. In 0.x a minor bump may still break;
47
+ every break is in [CHANGELOG.md](../CHANGELOG.md).
48
+
49
+ ## Quick start
50
+
51
+ ```bash
52
+ bunx synapsejs new my-app
53
+ cd my-app && bun install
54
+ bun run dev
55
+ bun run new-slice users register-user
56
+ ```
57
+
58
+ ## A slice
59
+
60
+ ```tsx
61
+ import { Type, Static, Value, Ok, Err, type Result, type DatabaseClient, createSession, requireAuth, type SessionContext } from 'synapsejs';
62
+
63
+ export const TicketInputSchema = Type.Object({
64
+ subject: Type.String({ minLength: 3 }),
65
+ priority: Type.Integer({ minimum: 1, maximum: 5 })
66
+ });
67
+ export type TicketInput = Static<typeof TicketInputSchema>;
68
+
69
+ export const sliceSchema = `
70
+ CREATE TABLE IF NOT EXISTS tickets (
71
+ id TEXT PRIMARY KEY,
72
+ subject TEXT NOT NULL,
73
+ priority INTEGER NOT NULL
74
+ );
75
+ `;
76
+
77
+ export type TicketOutput = Result<
78
+ { ticketId: string },
79
+ 'INVALID_SCHEMA' | 'NO_DATABASE' | 'UNAUTHORIZED' | 'FORBIDDEN'
80
+ >;
81
+
82
+ // `db` is optional so the same call site is valid on the server (connection injected)
83
+ // and on the client (where the call becomes an RPC stub).
84
+ export async function createTicketAction(
85
+ payload: unknown,
86
+ db?: DatabaseClient,
87
+ session?: SessionContext
88
+ ): Promise<TicketOutput> {
89
+ const auth = requireAuth(session, ['support']);
90
+ if (!auth.ok) return Err(auth.error);
91
+ if (!db) return Err('NO_DATABASE');
92
+ if (!Value.Check(TicketInputSchema, payload)) return Err('INVALID_SCHEMA');
93
+
94
+ const input = payload as TicketInput;
95
+ await db.query(`INSERT INTO tickets (id, subject, priority) VALUES ($1, $2, $3)`, [
96
+ crypto.randomUUID(), input.subject, input.priority
97
+ ]);
98
+ return Ok({ ticketId: 'ticket-1' });
99
+ }
100
+
101
+ export function CreateTicketTrigger() {
102
+ return <form>{/* UI lives in the same file */}</form>;
103
+ }
104
+
105
+ // Invariants run under Bun's real test runner via `synapse test`; the framework
106
+ // generates the wrapper, so slices never import a test library.
107
+ export const sliceTests = {
108
+ description: 'Ticket invariants',
109
+ cases: [
110
+ {
111
+ name: 'an anonymous caller is rejected before touching the database',
112
+ run: async () => {
113
+ const result = await createTicketAction({ subject: 'printer', priority: 2, requesterEmail: 'a@b.com' });
114
+ if (result.ok || result.error !== 'UNAUTHORIZED') throw new Error('expected UNAUTHORIZED');
115
+ }
116
+ }
117
+ ]
118
+ };
119
+ ```
120
+
121
+ ## MCP server
122
+
123
+ ```bash
124
+ bun run mcp # JSON-RPC 2.0 over stdio
125
+ ```
126
+
127
+ Tools: `synapse_get_repo_map`, `synapse_get_db_schema`, `synapse_check`, `synapse_split`,
128
+ `synapse_run_pbt`, `synapse_scaffold_slice`, `synapse_migrate`, `synapse_rollback`, `synapse_contract`,
129
+ `synapse_check_db_drift`, `synapse_diff_impact`. Slice-dependent tools fail with `NO_SLICES_DIR` (listing the paths they examined)
130
+ instead of reporting an empty success.
131
+
132
+ Client configuration for an agent host:
133
+
134
+ ```json
135
+ {
136
+ "mcpServers": {
137
+ "synapsejs": { "command": "bunx", "args": ["synapse", "mcp"], "cwd": "/path/to/your-app" }
138
+ }
139
+ }
140
+ ```
141
+
142
+ ## Client / server isolation
143
+
144
+ `synapse split` partitions each slice into `shared.tsx`, `server.ts` and `client.tsx` by
145
+ **reachability resolved through the type checker**, then enforces two gates: the emitted modules must
146
+ typecheck under your tsconfig, and the client module must not contain SQL, `db.query`, `sliceSchema`,
147
+ `process.env` or `Bun.`. A server action referenced by a component contributes only its wire
148
+ signature (payload + return type) to the client — never its body.
149
+
150
+ ## Package API
151
+
152
+ For comprehensive documentation, see [README.md](../../README.md) (English) or [README.pt-BR.md](../../README.pt-BR.md) (Português do Brasil).
153
+
154
+ ```typescript
155
+ import {
156
+ // Functional error handling
157
+ Result, Ok, Err, isOk, isErr, map, mapErr, unwrapOr, Option, Some, None,
158
+
159
+ // Runtime, Database & Action Context
160
+ SynapseServer, getDatabase, resetDatabaseInstance,
161
+ SqliteDatabaseClient, PostgresDatabaseClient, MockDatabaseClient,
162
+ type DatabaseClient, compileTaggedSql,
163
+ type ActionContext, createActionContext,
164
+ defineConfig, loadSynapseConfig,
165
+
166
+ // Object Storage & Optimization
167
+ type StorageClient, getStorage, LocalStorageAdapter, S3StorageAdapter,
168
+ optimizeImage,
169
+
170
+ // Background Jobs & Queue Engines
171
+ defineJob, QueueEngine, PostgresQueueEngine, type JobRecord, type JobDefinition,
172
+
173
+ // RPC boundary & Session
174
+ rpcCall, rpcTransportFailure, type RpcTransportError,
175
+ AnonymousSession, createSession, requireAuth, requireTenant,
176
+ hasRole, hasAnyRole, type SessionContext,
177
+ storeSession, clearSession, currentRoles, sessionCookie,
178
+ revokeSessionToken, isSessionTokenRevoked,
179
+
180
+ // JIT validation & PBT
181
+ Type, type Static, type TSchema, Value, fc,
182
+
183
+ // Declarative UI Primitives, Hooks & i18n
184
+ DataTable, DataForm, Button, Card, Badge, Pagination,
185
+ SynapseProvider, useAction, useLoaderData, useSubscription, useSession, useSynapseContext,
186
+ createTranslator,
187
+
188
+ // Realtime SSE Gateway
189
+ EventHub, getEventHub, resetEventHub,
190
+
191
+ // Compiler, Scaffolding, Schemas, Drift & Diagnostics
192
+ runSliceMigrations, rollbackSliceMigrations, runMachineVerifications,
193
+ orderSlicesByDag, parseTableDependencies, generateDatabaseSchemaCatalog,
194
+ checkSchemaDrift, analyzeImpact, nestJoinedRow,
195
+ resolveSlicesDir, findSliceFiles, SLICE_EXTENSION,
196
+ splitSlice, verifySplit, writeSplitArtifacts, artifactDirectory,
197
+ scaffoldSlice, scaffoldCrud, parseFields, compressRepositoryAST, buildStandalone,
198
+
199
+ // MCP
200
+ SynapseMcpServer
201
+ } from 'synapsejs';
202
+ ```
203
+
204
+ ## License
205
+
206
+ MIT © [Ismael Soilet](https://github.com/ismaelsoilet)