@guren/core 1.4.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @guren/core
2
+
3
+ The framework entry point for [Guren](https://guren.dev/) — a Laravel-inspired fullstack TypeScript framework, built for Bun. Application code imports the whole framework API from this one package.
4
+
5
+ ```bash
6
+ bun add @guren/core
7
+ ```
8
+
9
+ Starting a new app? Scaffold one instead — it wires all of this up for you:
10
+
11
+ ```bash
12
+ bunx create-guren-app my-app --auth
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```typescript
18
+ import { Controller, Router, defineModel } from '@guren/core'
19
+ import { z } from 'zod'
20
+ import { posts } from '@/db/schema'
21
+
22
+ class Post extends defineModel(posts) {
23
+ static fillable = ['title', 'body']
24
+ }
25
+
26
+ class PostController extends Controller {
27
+ async store() {
28
+ const data = await this.validateBody(
29
+ z.object({ title: z.string().min(1), body: z.string().min(1) }),
30
+ )
31
+ const post = await Post.create(data)
32
+ return this.redirect(`/posts/${post.id}`)
33
+ }
34
+ }
35
+
36
+ export function registerWebRoutes(router: Router): void {
37
+ router.post('/posts', [PostController, 'store'])
38
+ }
39
+ ```
40
+
41
+ Boot the app with `createApp({ routes, providers })`, then `app.boot()` and `app.listen()`.
42
+
43
+ ## Entry points
44
+
45
+ | Import | Contents |
46
+ |--------|----------|
47
+ | `@guren/core` | The framework API: controllers, routing, middleware, auth, models, queues, mail, events, notifications, cache, validation |
48
+ | `@guren/core/runtime` | Bun server helpers used by the scaffolded `bin/serve.ts` |
49
+ | `@guren/core/vite` | The Vite plugin: Inertia + React integration, codegen watching, SSR builds |
50
+ | `@guren/core/lambda` | AWS Lambda adapters: `createLambdaHandler`, `createSqsHandler`, `createScheduleHandler`, `createConsoleHandler` |
51
+ | `@guren/core/redis` | Redis-backed session, cache, and queue stores |
52
+
53
+ ## CLI
54
+
55
+ The `guren` CLI ships with this package. `bunx guren` inside an app gives you scaffolding (`make:*`), codegen, migrations, and the integrity checks (`check`, `audit`, `doctor`).
56
+
57
+ ## Documentation
58
+
59
+ Guides, API reference, and deployment docs (Cloudflare Workers, AWS Lambda, Vercel, Docker) live at [guren.dev/docs](https://guren.dev/docs).
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ApiTokenStore, ApiToken, SessionStore, SessionData, OAuthStateStore, OAuthStatePayload } from '@guren/server';
2
2
  export * from '@guren/server';
3
- export { AccessorDefinitions, AccessorFn, AwsDataApiDatabase, AwsDataApiDatabaseOptions, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, Model, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PostgresDatabase, PostgresDatabaseOptions, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereOperator, WithRelations, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from '@guren/orm';
3
+ export { AccessorDefinitions, AccessorFn, AwsDataApiDatabase, AwsDataApiDatabaseOptions, AwsDataApiSeederContext, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, Model, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, MySqlSeederContext, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PostgresDatabase, PostgresDatabaseOptions, PostgresSeederContext, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, SqliteSeederContext, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereOperator, WithRelations, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from '@guren/orm';
4
4
 
5
5
  /**
6
6
  * Options for DatabaseApiTokenStore.
@@ -141,7 +141,7 @@ declare class DatabaseSessionStore implements SessionStore {
141
141
  *
142
142
  * Pass the Drizzle table for your `oauth_states` schema. Column property
143
143
  * names must match `stateHash` (text primary key), `provider`,
144
- * `redirectTo`, and `expiresAt`:
144
+ * `redirectTo`, `expiresAt`, and `binding`:
145
145
  *
146
146
  * ```ts
147
147
  * export const oauthStates = sqliteTable('oauth_states', {
@@ -149,9 +149,14 @@ declare class DatabaseSessionStore implements SessionStore {
149
149
  * provider: text('provider').notNull(),
150
150
  * redirectTo: text('redirect_to'),
151
151
  * expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
152
+ * binding: text('binding'),
152
153
  * })
153
154
  * ```
154
155
  *
156
+ * `binding` is required for `authorize({ bindTo })` to survive the round trip
157
+ * to the provider. Without the column the store cannot persist it, and every
158
+ * bound state comes back unbound.
159
+ *
155
160
  * @example
156
161
  * ```ts
157
162
  * import { createOAuthManager, DatabaseOAuthStateStore } from '@guren/core'
package/dist/index.js CHANGED
@@ -194,7 +194,9 @@ var DatabaseOAuthStateStore = class {
194
194
  stateHash,
195
195
  provider: payload.provider,
196
196
  redirectTo: payload.redirectTo ?? null,
197
- expiresAt: payload.expiresAt
197
+ expiresAt: payload.expiresAt,
198
+ // Persisted, not derived: an unbound state verifies for any browser.
199
+ binding: payload.binding ?? null
198
200
  });
199
201
  }
200
202
  async find(stateHash) {
@@ -267,7 +269,8 @@ function mapRecordToPayload(record) {
267
269
  provider: String(record.provider),
268
270
  redirectTo: record.redirectTo == null ? void 0 : String(record.redirectTo),
269
271
  // fetchLive's isExpired check guarantees this parses.
270
- expiresAt: toDate(record.expiresAt)
272
+ expiresAt: toDate(record.expiresAt),
273
+ binding: record.binding == null ? void 0 : String(record.binding)
271
274
  };
272
275
  }
273
276
  function deleteRemovedRow(result) {
@@ -22,10 +22,9 @@ declare function readManifest(...paths: string[]): {
22
22
  * Throw unless `out` is safe to delete: it must be neither the app root nor a
23
23
  * directory containing it.
24
24
  *
25
- * Both paths are resolved through their symlinks first, because the delete
26
- * that follows does too. Comparing lexically accepts `outputDir` values that
27
- * reach the app root the long way — on macOS `/tmp` is itself a symlink to
28
- * `/private/tmp`, so this is not a contrived case.
25
+ * Relates two paths, so it canonicalizes both: comparing lexically would
26
+ * accept `outputDir` values that reach the app root the long way, and the
27
+ * delete that follows resolves the links regardless.
29
28
  *
30
29
  * Containment is then decided with `relative` rather than a string prefix
31
30
  * because `out + sep` is `//` at the filesystem root, which no absolute path
@@ -56,6 +55,10 @@ declare function resetOutputDir(out: string, root: string, label: string): void;
56
55
  * Relative specifier for importing `target` from a module written into
57
56
  * `fromDir`, in POSIX form so the emitted source is platform-agnostic.
58
57
  *
58
+ * Relates two paths, so it canonicalizes both: the bundler resolves the
59
+ * emitted module from its real path, and a link that changes depth would
60
+ * otherwise leave the specifier short a `..` segment.
61
+ *
59
62
  * @param label Platform name for the error message, e.g. `'Lambda build'`.
60
63
  */
61
64
  declare function importSpecifier(fromDir: string, target: string, label: string): string;
@@ -51,7 +51,7 @@ function resetOutputDir(out, root, label) {
51
51
  }
52
52
  }
53
53
  function importSpecifier(fromDir, target, label) {
54
- const rel = relative(fromDir, target);
54
+ const rel = relative(realpathOfNearestExisting(fromDir), realpathOfNearestExisting(target));
55
55
  if (isAbsolute(rel)) {
56
56
  throw new Error(
57
57
  `${label}: ${target} cannot be imported relative to ${fromDir} (different drive or root?). Keep the app, SSR output, and outputDir on the same volume.`
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Zod 4 schema-reading primitives shared by `@guren/cli`'s TypeScript-type
3
+ * renderer (`src/schema-type-extractor.ts`) and the OpenAPI schema-object
4
+ * renderer (`@guren/openapi`).
5
+ *
6
+ * Internal by the rules in `contributing/api-stability.md`: reachable only
7
+ * through a deep import under `internal/`, never re-exported from
8
+ * `@guren/core`'s index.
9
+ *
10
+ * Zod 4 only. The zod 3 API (whether from the old `zod@3` package or the
11
+ * `zod/v3` subpath that zod 4 ships for migration) tags every node with
12
+ * `_def.typeName` and overloads `_def.type` to hold a nested schema — the
13
+ * ambiguity behind a bug this module's predecessors fixed twice. Rather than
14
+ * carrying both dialects forever, a v3 node is detected up front
15
+ * (`isZod3Schema`) and refused with `ZOD3_UNSUPPORTED_MESSAGE`; everything
16
+ * below it assumes the v4 layout, where `_def.type` is always the type name.
17
+ *
18
+ * What does NOT belong here: the two type switches that turn a node into an
19
+ * output (a TypeScript type string vs. an OpenAPI schema object). Their leaf
20
+ * vocabularies have legitimately diverged — the CLI renders `void`/`any`/
21
+ * `never`, which OpenAPI has no way to express — and that is a rendering
22
+ * decision, not schema-reading knowledge.
23
+ *
24
+ * Neither walker's `isOptional` belongs here either, but for a weaker reason
25
+ * than "they are both right": the CLI reads only the side of a `.pipe()` it
26
+ * renders, the OpenAPI walker requires both sides to permit omission, and
27
+ * *both* are approximations that a sufficiently odd pipeline can fool. Fixing
28
+ * them properly means simulating a parse, which is well beyond reading a
29
+ * `_def`. They stay with their callers until someone does that.
30
+ */
31
+ interface ZodSchemaLike {
32
+ _def?: Record<string, unknown>;
33
+ /** zod 4's internal container; `values` is its own computed set of accepted literals. */
34
+ _zod?: {
35
+ values?: Set<unknown>;
36
+ };
37
+ type?: string;
38
+ shape?: Record<string, ZodSchemaLike>;
39
+ }
40
+ /**
41
+ * Which side of a schema is being read.
42
+ *
43
+ * - `output` — the parsed value, i.e. what a controller receives after
44
+ * validation, or what a response body looks like.
45
+ * - `input` — the value a client has to send over the wire. Coercing and
46
+ * piped schemas can differ here from their output side.
47
+ */
48
+ type SchemaIo = 'input' | 'output';
49
+ /**
50
+ * Whether this node was authored with the zod 3 API. Only v3 sets
51
+ * `_def.typeName` (`"ZodString"`), so its presence is the discriminator —
52
+ * checked before any other read, because on a v3 node `_def.type` holds a
53
+ * nested *schema* and every v4-shaped read below would misfire on it.
54
+ */
55
+ declare function isZod3Schema(schema: ZodSchemaLike): boolean;
56
+ /**
57
+ * The one refusal message, stated once so the CLI's console warning and the
58
+ * OpenAPI document's warnings array cannot drift apart.
59
+ */
60
+ declare const ZOD3_UNSUPPORTED_MESSAGE = "this schema was authored with the zod v3 API (zod@3 or the zod/v3 subpath), which Guren does not support. Rewrite it with the zod 4 API (`import { z } from 'zod'`).";
61
+ /** The node's type name: `_def.type` (`"string"`, `"object"`, …) or the schema's own `.type`. */
62
+ declare function getTypeName(schema: ZodSchemaLike): string | undefined;
63
+ /** `getTypeName` with `'unknown'` for a node that has no readable name. */
64
+ declare function typeOf(schema: ZodSchemaLike): string;
65
+ /**
66
+ * The schema at `def[key]`, if it actually holds one. The object check is
67
+ * load-bearing: `_def` is untyped data from someone else's package, and a key
68
+ * holding a string or function must read as absent, not as a schema. (The
69
+ * v3-era version of this helper took a key *list* and returned the first
70
+ * match; with one dialect there is no precedence left to encode.)
71
+ */
72
+ declare function schemaAt(def: Record<string, unknown>, key: string): ZodSchemaLike | undefined;
73
+ /** The schema wrapped by a single-child wrapper (`.optional()`, `.readonly()`, `.catch()`, …) — always `_def.innerType` in zod 4. */
74
+ declare function innerSchema(def: Record<string, unknown>): ZodSchemaLike | undefined;
75
+ /** An array's element schema — `_def.element`, never `_def.type`, which holds the string `'array'`. */
76
+ declare function arrayElement(def: Record<string, unknown>): ZodSchemaLike | undefined;
77
+ /** A record's value schema — `_def.valueType`. */
78
+ declare function recordValueType(def: Record<string, unknown>): ZodSchemaLike | undefined;
79
+ /**
80
+ * Whether this node is a `.transform()`'s output half — a wrapped function
81
+ * with no type to read, as opposed to a schema that genuinely parses to
82
+ * `unknown`.
83
+ */
84
+ declare function isTransform(schema: ZodSchemaLike): boolean;
85
+ /**
86
+ * Both halves of a `.pipe()`. Zod 4 uses one `pipe` node for both `.pipe()`
87
+ * and `.transform()`: `_def.in` is what a caller sends, `_def.out` what a
88
+ * controller receives — except for a transform, whose out side is the
89
+ * transform function itself and so has no type to read. `to` is therefore
90
+ * absent for a transform, leaving `from` as the only readable answer.
91
+ */
92
+ declare function pipeSides(def: Record<string, unknown>): {
93
+ from: ZodSchemaLike | undefined;
94
+ to: ZodSchemaLike | undefined;
95
+ };
96
+ /** The one side of a `.pipe()` that describes the `io` direction being rendered. */
97
+ declare function pipeSide(def: Record<string, unknown>, io: SchemaIo): ZodSchemaLike | undefined;
98
+ /** An object's property map — `_def.shape`, or the schema's own `.shape`. */
99
+ declare function objectShape(schema: ZodSchemaLike): Record<string, ZodSchemaLike> | undefined;
100
+ /**
101
+ * An enum's accepted values, read from zod's own computed set at
102
+ * `_zod.values` rather than re-derived from `_def.entries`. The distinction
103
+ * matters because `z.nativeEnum` produces the same node and a real TypeScript
104
+ * numeric enum's runtime object carries reverse mappings (`{ A: 0, '0': 'A' }`)
105
+ * — and any hand-rolled filter for those has a false positive: in
106
+ * `{ A: 'B', B: 1 }`, the key `A` *looks* like a reverse entry (`entries['B']`
107
+ * is a number) but zod accepts `'B'`. Reading zod's set makes what we document
108
+ * what zod parses, by construction. The `entries` fallback (values unfiltered)
109
+ * only runs if a future zod 4.x stops exposing the set.
110
+ */
111
+ declare function enumValues(schema: ZodSchemaLike): Array<string | number>;
112
+ /** A literal's values — always the `_def.values` array in zod 4, which may hold more than one. */
113
+ declare function literalValues(def: Record<string, unknown>): unknown[];
114
+ /**
115
+ * Wrappers that neither add to a rendered type nor decide whether a field may
116
+ * be omitted — whatever they wrap answers both questions. (`lazy` is here for
117
+ * membership only: its child hides behind `_def.getter`, which no walker
118
+ * calls, so looking through it reads as "contents unavailable" rather than
119
+ * "unsupported type".)
120
+ */
121
+ declare const TRANSPARENT_WRAPPERS: ReadonlySet<string>;
122
+ /**
123
+ * Wrappers that pass their type through but *do* decide presence: each makes a
124
+ * field omissible, or (in `nonoptional`'s case) re-requires one.
125
+ */
126
+ declare const PRESENCE_WRAPPERS: ReadonlySet<string>;
127
+ /**
128
+ * Every type name that carries exactly one nested schema and no shape of its
129
+ * own — the union of the two sets above plus the two that render specially
130
+ * (`nullable` becomes a union with null; a pipe holds one schema per side).
131
+ *
132
+ * This is the vocabulary, not a policy: callers partition it however their
133
+ * rendering needs (the CLI splits transparent from presence-deciding because
134
+ * it walks types and presence separately; the OpenAPI walker looks through all
135
+ * of them uniformly). What none of them may do is disagree about *membership*
136
+ * — a name known to one walker and not the other silently changes an output,
137
+ * which is why the list lives here rather than once per package.
138
+ */
139
+ declare const SINGLE_CHILD_WRAPPERS: ReadonlySet<string>;
140
+
141
+ export { PRESENCE_WRAPPERS, SINGLE_CHILD_WRAPPERS, type SchemaIo, TRANSPARENT_WRAPPERS, ZOD3_UNSUPPORTED_MESSAGE, type ZodSchemaLike, arrayElement, enumValues, getTypeName, innerSchema, isTransform, isZod3Schema, literalValues, objectShape, pipeSide, pipeSides, recordValueType, schemaAt, typeOf };
@@ -0,0 +1,89 @@
1
+ // src/internal/zod-compat.ts
2
+ function isZod3Schema(schema) {
3
+ return typeof schema._def?.typeName === "string";
4
+ }
5
+ var ZOD3_UNSUPPORTED_MESSAGE = "this schema was authored with the zod v3 API (zod@3 or the zod/v3 subpath), which Guren does not support. Rewrite it with the zod 4 API (`import { z } from 'zod'`).";
6
+ function getTypeName(schema) {
7
+ const name = schema._def?.type ?? schema.type;
8
+ return typeof name === "string" ? name : void 0;
9
+ }
10
+ function typeOf(schema) {
11
+ return getTypeName(schema) ?? "unknown";
12
+ }
13
+ function schemaAt(def, key) {
14
+ const candidate = def[key];
15
+ return candidate && typeof candidate === "object" ? candidate : void 0;
16
+ }
17
+ function innerSchema(def) {
18
+ return schemaAt(def, "innerType");
19
+ }
20
+ function arrayElement(def) {
21
+ return schemaAt(def, "element");
22
+ }
23
+ function recordValueType(def) {
24
+ return schemaAt(def, "valueType");
25
+ }
26
+ function isTransform(schema) {
27
+ return typeOf(schema) === "transform";
28
+ }
29
+ function pipeSides(def) {
30
+ const to = schemaAt(def, "out");
31
+ return { from: schemaAt(def, "in"), to: to && !isTransform(to) ? to : void 0 };
32
+ }
33
+ function pipeSide(def, io) {
34
+ const { from, to } = pipeSides(def);
35
+ return io === "output" && to ? to : from;
36
+ }
37
+ function objectShape(schema) {
38
+ const def = schema._def ?? {};
39
+ return def.shape ?? schema.shape;
40
+ }
41
+ function enumValues(schema) {
42
+ const values = schema._zod?.values;
43
+ if (values) {
44
+ return [...values].filter(
45
+ (value) => typeof value === "string" || typeof value === "number"
46
+ );
47
+ }
48
+ const entries = schema._def?.entries;
49
+ return entries ? Object.values(entries) : [];
50
+ }
51
+ function literalValues(def) {
52
+ return Array.isArray(def.values) ? def.values : [];
53
+ }
54
+ var TRANSPARENT_WRAPPERS = /* @__PURE__ */ new Set([
55
+ "catch",
56
+ "readonly",
57
+ "lazy"
58
+ ]);
59
+ var PRESENCE_WRAPPERS = /* @__PURE__ */ new Set([
60
+ "optional",
61
+ "default",
62
+ "prefault",
63
+ "nonoptional"
64
+ ]);
65
+ var SINGLE_CHILD_WRAPPERS = /* @__PURE__ */ new Set([
66
+ ...TRANSPARENT_WRAPPERS,
67
+ ...PRESENCE_WRAPPERS,
68
+ "nullable",
69
+ "pipe"
70
+ ]);
71
+ export {
72
+ PRESENCE_WRAPPERS,
73
+ SINGLE_CHILD_WRAPPERS,
74
+ TRANSPARENT_WRAPPERS,
75
+ ZOD3_UNSUPPORTED_MESSAGE,
76
+ arrayElement,
77
+ enumValues,
78
+ getTypeName,
79
+ innerSchema,
80
+ isTransform,
81
+ isZod3Schema,
82
+ literalValues,
83
+ objectShape,
84
+ pipeSide,
85
+ pipeSides,
86
+ recordValueType,
87
+ schemaAt,
88
+ typeOf
89
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/core",
3
- "version": "1.4.0",
3
+ "version": "1.5.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -44,6 +44,10 @@
44
44
  "./internal/deploy-build": {
45
45
  "types": "./dist/internal/deploy-build.d.ts",
46
46
  "default": "./dist/internal/deploy-build.js"
47
+ },
48
+ "./internal/zod-compat": {
49
+ "types": "./dist/internal/zod-compat.d.ts",
50
+ "default": "./dist/internal/zod-compat.js"
47
51
  }
48
52
  },
49
53
  "bin": {
@@ -56,9 +60,9 @@
56
60
  "typecheck": "tsc --noEmit"
57
61
  },
58
62
  "dependencies": {
59
- "@guren/cli": "^1.6.0",
60
- "@guren/orm": "^1.3.0",
61
- "@guren/server": "^1.5.0"
63
+ "@guren/cli": "^2.2.0",
64
+ "@guren/orm": "^2.2.0",
65
+ "@guren/server": "^2.2.0"
62
66
  },
63
67
  "devDependencies": {
64
68
  "@types/node": "^20.14.10",