@nanokajs/core 1.8.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +3 -2
- package/dist/index.d.ts +8 -1
- package/dist/index.js +25 -41
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -11,11 +11,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
11
11
|
|
|
12
12
|
- Depth-1 relation eager loading via `findMany(adapter, { limit, with })` and `findOne(adapter, idOrWhere, { with })`.
|
|
13
13
|
- Typed `WithOptions`, `WithResult`, `RelationKeys`, and `FindOneOptions` exports for relation query results.
|
|
14
|
-
- Runtime `with` validation
|
|
14
|
+
- Runtime `with` validation for relation eager loading.
|
|
15
|
+
- Bidirectional relation graphs are supported for depth-1 eager loading.
|
|
15
16
|
|
|
16
17
|
### Notes
|
|
17
18
|
|
|
18
|
-
- Relation loading follows the documented parent query + relation query + JavaScript grouping strategy; nested eager loading
|
|
19
|
+
- Relation loading follows the documented parent query + relation query + JavaScript grouping strategy; nested eager loading and recursive relation graph traversal remain out of scope.
|
|
19
20
|
|
|
20
21
|
## [1.6.0] — 2026-05-05
|
|
21
22
|
|
package/dist/index.d.ts
CHANGED
|
@@ -20,6 +20,7 @@ import 'drizzle-orm/batch';
|
|
|
20
20
|
declare function d1Adapter<TSchema extends Record<string, unknown> = Record<string, never>>(d1: D1Database): Adapter<TSchema>;
|
|
21
21
|
|
|
22
22
|
type OpenAPISchemaObject = Record<string, unknown>;
|
|
23
|
+
type WithOpenAPIOption = Readonly<Record<string, true>>;
|
|
23
24
|
interface OpenAPIModelComponent {
|
|
24
25
|
create: OpenAPISchemaObject;
|
|
25
26
|
update: OpenAPISchemaObject;
|
|
@@ -467,6 +468,9 @@ interface Model<Fields extends Record<string, Field<any, any, any>>> {
|
|
|
467
468
|
*/
|
|
468
469
|
toResponseMany(rows: readonly RowType<Fields>[]): unknown[];
|
|
469
470
|
toOpenAPIComponent(): OpenAPIModelComponent;
|
|
471
|
+
toOpenAPISchema(usage: 'output', opts: {
|
|
472
|
+
readonly with: Partial<Record<RelationKeys<Fields> & string, true>>;
|
|
473
|
+
}): OpenAPISchemaObject;
|
|
470
474
|
toOpenAPISchema(usage: OpenAPIUsage): OpenAPISchemaObject;
|
|
471
475
|
/**
|
|
472
476
|
* Fetches multiple rows with pagination and optional ordering.
|
|
@@ -593,6 +597,9 @@ interface NanokaModel<Fields extends Record<string, Field<any, any, any>>> {
|
|
|
593
597
|
toResponse(row: RowType<Fields>): unknown;
|
|
594
598
|
toResponseMany(rows: readonly RowType<Fields>[]): unknown[];
|
|
595
599
|
toOpenAPIComponent(): OpenAPIModelComponent;
|
|
600
|
+
toOpenAPISchema(usage: 'output', opts: {
|
|
601
|
+
readonly with: Partial<Record<RelationKeys<Fields> & string, true>>;
|
|
602
|
+
}): OpenAPISchemaObject;
|
|
596
603
|
toOpenAPISchema(usage: OpenAPIUsage): OpenAPISchemaObject;
|
|
597
604
|
/**
|
|
598
605
|
* Fetches multiple rows with pagination and optional ordering.
|
|
@@ -702,4 +709,4 @@ interface Nanoka<E extends Env$1 = BlankEnv> extends Hono<E> {
|
|
|
702
709
|
*/
|
|
703
710
|
declare function nanoka<E extends Env$1 = BlankEnv>(adapter: Adapter): Nanoka<E>;
|
|
704
711
|
|
|
705
|
-
export { Adapter, type CreateInput, Field, FieldPolicy, type FindAllOptions, type FindManyOptions, type FindOneOptions, type HttpMethod, type IdOrWhere, InferFieldType, type Model, type Nanoka, type NanokaModel, type OpenAPIDocument, type OpenAPIModelComponent, type OpenAPIParamSpec, type OpenAPIRequestBodySpec, type OpenAPIResponseSpec, type OpenAPIRouteMetadata, type OpenAPISchemaObject, type OpenAPISpecOptions, type OpenAPIUsage, type OrderBy, RelationDef, type RelationKeys, type RouteOpenAPIMetadata, type RouteOpenAPIOption, type RowType, type SchemaOptions, type Where, type WithOptions, type WithResult, d1Adapter, defineModel, nanoka, swaggerUI };
|
|
712
|
+
export { Adapter, type CreateInput, Field, FieldPolicy, type FindAllOptions, type FindManyOptions, type FindOneOptions, type HttpMethod, type IdOrWhere, InferFieldType, type Model, type Nanoka, type NanokaModel, type OpenAPIDocument, type OpenAPIModelComponent, type OpenAPIParamSpec, type OpenAPIRequestBodySpec, type OpenAPIResponseSpec, type OpenAPIRouteMetadata, type OpenAPISchemaObject, type OpenAPISpecOptions, type OpenAPIUsage, type OrderBy, RelationDef, type RelationKeys, type RouteOpenAPIMetadata, type RouteOpenAPIOption, type RowType, type SchemaOptions, type Where, type WithOpenAPIOption, type WithOptions, type WithResult, d1Adapter, defineModel, nanoka, swaggerUI };
|
package/dist/index.js
CHANGED
|
@@ -154,6 +154,21 @@ function toOpenAPISchema(fields, usage, opts) {
|
|
|
154
154
|
required.push(key);
|
|
155
155
|
}
|
|
156
156
|
}
|
|
157
|
+
if (usage === "output" && opts?.with !== void 0) {
|
|
158
|
+
for (const [key, field] of Object.entries(fields)) {
|
|
159
|
+
if (field.kind !== "relation") continue;
|
|
160
|
+
if (opts.with[key] !== true) continue;
|
|
161
|
+
const relationField = field;
|
|
162
|
+
const rawTarget = relationField.target;
|
|
163
|
+
const targetModel = typeof rawTarget === "function" ? rawTarget() : rawTarget;
|
|
164
|
+
const targetSchema = toOpenAPISchema(targetModel.fields, "output");
|
|
165
|
+
if (relationField.relationKind === "hasMany") {
|
|
166
|
+
properties[key] = { type: "array", items: targetSchema };
|
|
167
|
+
} else {
|
|
168
|
+
properties[key] = { ...targetSchema, nullable: true };
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
157
172
|
return {
|
|
158
173
|
type: "object",
|
|
159
174
|
properties,
|
|
@@ -426,42 +441,6 @@ function validateWithOptions(fields, withOptions) {
|
|
|
426
441
|
}
|
|
427
442
|
}
|
|
428
443
|
}
|
|
429
|
-
var relationCycleCache = /* @__PURE__ */ new WeakMap();
|
|
430
|
-
function assertNoRelationCycle(fields, rootName = "root") {
|
|
431
|
-
const cached = relationCycleCache.get(fields);
|
|
432
|
-
if (cached !== void 0) {
|
|
433
|
-
if (cached !== null) throw cached;
|
|
434
|
-
return;
|
|
435
|
-
}
|
|
436
|
-
const visiting = /* @__PURE__ */ new Set();
|
|
437
|
-
const visited = /* @__PURE__ */ new Set();
|
|
438
|
-
const visit = (currentFields, path) => {
|
|
439
|
-
if (visiting.has(currentFields)) {
|
|
440
|
-
return new HTTPException(500, { message: "relation cycle detected" });
|
|
441
|
-
}
|
|
442
|
-
if (visited.has(currentFields)) {
|
|
443
|
-
return null;
|
|
444
|
-
}
|
|
445
|
-
visiting.add(currentFields);
|
|
446
|
-
for (const field of Object.values(currentFields)) {
|
|
447
|
-
if (field.kind !== "relation") continue;
|
|
448
|
-
const target = resolveRelationTarget(field);
|
|
449
|
-
const targetFields = target.fields;
|
|
450
|
-
const error2 = visit(targetFields, [...path, target.tableName]);
|
|
451
|
-
if (error2 !== null) {
|
|
452
|
-
return error2;
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
visiting.delete(currentFields);
|
|
456
|
-
visited.add(currentFields);
|
|
457
|
-
return null;
|
|
458
|
-
};
|
|
459
|
-
const error = visit(fields, [rootName]);
|
|
460
|
-
relationCycleCache.set(fields, error);
|
|
461
|
-
if (error !== null) {
|
|
462
|
-
throw error;
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
444
|
async function loadRelations(adapter, _parentTable, parentFields, parentRows, withOptions) {
|
|
466
445
|
if (parentRows.length === 0) {
|
|
467
446
|
return [];
|
|
@@ -584,7 +563,6 @@ async function findManyImpl(adapter, table, fields, options) {
|
|
|
584
563
|
const rows = await query;
|
|
585
564
|
if (options.with !== void 0) {
|
|
586
565
|
validateWithOptions(fields, options.with);
|
|
587
|
-
assertNoRelationCycle(fields);
|
|
588
566
|
return loadRelations(adapter, table, fields, rows, options.with);
|
|
589
567
|
}
|
|
590
568
|
return rows;
|
|
@@ -648,7 +626,6 @@ async function findOneImpl(adapter, table, fields, idOrWhere, options) {
|
|
|
648
626
|
}
|
|
649
627
|
if (options?.with !== void 0) {
|
|
650
628
|
validateWithOptions(fields, options.with);
|
|
651
|
-
assertNoRelationCycle(fields);
|
|
652
629
|
}
|
|
653
630
|
const rows = await adapter.drizzle.select().from(table).where(whereClause).limit(1);
|
|
654
631
|
if (rows.length === 0) {
|
|
@@ -748,8 +725,12 @@ function defineModel(tableName, fields) {
|
|
|
748
725
|
toOpenAPIComponent() {
|
|
749
726
|
return toOpenAPIComponent(fields);
|
|
750
727
|
},
|
|
751
|
-
toOpenAPISchema(usage) {
|
|
752
|
-
return toOpenAPISchema(
|
|
728
|
+
toOpenAPISchema(usage, opts) {
|
|
729
|
+
return toOpenAPISchema(
|
|
730
|
+
fields,
|
|
731
|
+
usage,
|
|
732
|
+
opts ? { with: opts.with } : void 0
|
|
733
|
+
);
|
|
753
734
|
},
|
|
754
735
|
findMany: ((adapter, options) => findManyImpl(adapter, table, fields, options)),
|
|
755
736
|
findAll(adapter, options) {
|
|
@@ -881,7 +862,10 @@ function nanoka(adapter) {
|
|
|
881
862
|
toResponse: (row) => inner.toResponse(row),
|
|
882
863
|
toResponseMany: (rows) => inner.toResponseMany(rows),
|
|
883
864
|
toOpenAPIComponent: () => inner.toOpenAPIComponent(),
|
|
884
|
-
toOpenAPISchema: (usage) =>
|
|
865
|
+
toOpenAPISchema: (usage, opts) => (
|
|
866
|
+
// biome-ignore lint/suspicious/noExplicitAny: NanokaModel interface overloads provide type safety
|
|
867
|
+
inner.toOpenAPISchema(usage, opts)
|
|
868
|
+
),
|
|
885
869
|
findMany: ((options) => inner.findMany(adapter, options)),
|
|
886
870
|
findAll: (options) => inner.findAll(adapter, options),
|
|
887
871
|
findOne: ((idOrWhere, options) => inner.findOne(adapter, idOrWhere, options)),
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapter/d1.ts","../src/model/types.ts","../src/model/schema.ts","../src/openapi/generate.ts","../src/model/table.ts","../src/model/crud.ts","../src/model/define.ts","../src/openapi/route.ts","../src/openapi/swagger-ui.ts","../src/router/nanoka.ts"],"names":["partial","combinedOmit","error"],"mappings":";;;;;;;;;AASO,SAAS,UACd,EAAA,EACkB;AAUlB,EAAA,MAAM,EAAA,GAAK,QAAQ,EAAE,CAAA;AAErB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,EAAA;AAAA,IACT,KAAA,EAAO,CAAC,OAAA,KAAY,EAAA,CAAG,MAAM,OAAO;AAAA,GACtC;AACF;;;AC+PO,SAAS,uBAAA,CACd,KACA,QAAA,EAC0B;AAC1B,EAAA,IAAI,GAAA,KAAQ,QAAW,OAAO,MAAA;AAC9B,EAAA,IAAI,OAAO,GAAA,KAAQ,UAAA,EAAY,OAAO,IAAI,QAAQ,CAAA;AAClD,EAAA,OAAO,GAAA;AACT;AASO,SAAS,mBACd,MAAA,EACgD;AAChD,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AAC/C,IAAA,IAAI,KAAA,CAAM,SAAS,UAAA,EAAY;AAC/B,IAAA,GAAA,CAAI,CAAC,CAAA,GAAI,CAAA;AAAA,EACX;AACA,EAAA,OAAO,MAAA,CAAO,OAAO,GAAG,CAAA;AAC1B;;;ACzSA,SAAS,kBAEP,MAAA,EACU;AACV,EAAA,MAAM,OAAiB,EAAC;AACxB,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AACjD,IAAA,IAAI,KAAA,CAAM,SAAA,CAAU,MAAA,KAAW,YAAA,EAAc;AAC3C,MAAA,IAAA,CAAK,KAAK,GAAG,CAAA;AAAA,IACf;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;AAMA,SAAS,oBAEP,MAAA,EACa;AACb,EAAA,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AAM,WAAW,GAAG,CAAA;AAAA,MAEzC,cAAA,EAAgB,CAAC,IAAA,KAAS,KAAA,CAAM,eAAe,IAAI,CAAA;AAAA,MAEnD,kBAAA,EAAoB,MAAM,KAAA,CAAM,kBAAA,EAAmB;AAAA,MAEnD,eAAA,EAAiB,CAAC,KAAA,KAAU,KAAA,CAAM,gBAAgB,KAAK,CAAA;AAAA,MAEvD,WAAW,CAAC,OAAA,KACV,KAAA,CAAM,QAAA,CAAS,SAAS,OAAc,CAAA,CAAA;AAAA,MAExC,SAAS,CAAC,OAAA,KAAY,KAAA,CAAM,OAAA,CAAQ,SAAS,OAAO,CAAA;AAAA,MAEpD,OAAA,GAAU,CACR,SAAA,EACA,OAAA,KACG,MAAM,OAAA,CAAQ,OAAA,EAAS,WAAW,OAAc,CAAA,CAAA;AAAA,MAErD,QAAQ,CAAC,IAAA,KAAS,KAAA,CAAM,MAAA,CAAO,SAAS,IAAI,CAAA;AAAA,MAE5C,MAAA,EAAQ,CAAC,SAAA,EAAW,IAAA,KAAS,MAAM,MAAA,CAAO,OAAA,EAAS,WAAW,IAAI,CAAA;AAAA,MAElE,QAAQ,CAAC,SAAA,KAAc,KAAA,CAAM,MAAA,CAAO,SAAS,SAAS;AAAA,KACxD;AAAA,EACF,CAAA;AAEA,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["import type { D1Database } from '@cloudflare/workers-types'\nimport { drizzle } from 'drizzle-orm/d1'\nimport type { Adapter } from './types'\n\n/**\n * D1-specific adapter factory. Wraps Cloudflare D1 binding in the generic\n * Adapter abstraction, enabling the core query path and router to remain\n * implementation-agnostic.\n */\nexport function d1Adapter<TSchema extends Record<string, unknown> = Record<string, never>>(\n d1: D1Database,\n): Adapter<TSchema> {\n // drizzle-orm/d1's drizzle() returns DrizzleD1Database which embeds D1-specific\n // result types. We cast to BaseSQLiteDatabase via the Adapter interface to keep\n // the D1 dependency local to this file (see CLAUDE.md rule #3). Consumers receive\n // the typed Adapter interface, so this `any` is intentionally local.\n //\n // Note: drizzle-orm/d1 internally stores the D1 binding in db.$client. When\n // handling multiple D1 bindings, call d1Adapter() fresh for each binding rather\n // than caching the return value across binding switches.\n // biome-ignore lint/suspicious/noExplicitAny: intentional - Drizzle returns complex union type\n const db = drizzle(d1) as any\n\n return {\n drizzle: db,\n batch: (queries) => db.batch(queries),\n }\n}\n","import type { Hook } from '@hono/zod-validator'\nimport type { SQL } from 'drizzle-orm'\nimport type { AnySQLiteColumn, SQLiteTableWithColumns } from 'drizzle-orm/sqlite-core'\nimport type { Env, MiddlewareHandler, ValidationTargets } from 'hono'\nimport type { z } from 'zod'\nimport type { Adapter } from '../adapter/types'\nimport type { Field, FieldPolicy, InferFieldType, RelationDef } from '../field/types'\nimport type { OpenAPIModelComponent, OpenAPISchemaObject, OpenAPIUsage } from '../openapi/types'\n\n/**\n * @internal\n * Extracts keys of non-relation fields from a Fields record.\n * Relation fields (kind: 'relation') are excluded from DB column types, RowType, etc.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\nexport type NonRelationKeys<Fields extends Record<string, Field<any, any, any>>> = {\n [K in keyof Fields]: Fields[K] extends { kind: 'relation' } ? never : K\n}[keyof Fields]\n\n/**\n * @internal\n * Extracts keys of relation fields from a Fields record.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\nexport type RelationKeys<Fields extends Record<string, Field<any, any, any>>> = {\n [K in keyof Fields]: Fields[K] extends { kind: 'relation' } ? K : never\n}[keyof Fields]\n\nexport type RelationTargetFields<Target> = Target extends () => infer Resolved\n ? RelationTargetFields<Resolved>\n : Target extends { fields: infer TargetFields }\n ? TargetFields\n : never\n\nexport type RelationResult<F> =\n F extends RelationDef<infer Target, string>\n ? RelationTargetFields<Target> extends Record<string, Field<any, any, any>>\n ? F['relationKind'] extends 'hasMany'\n ? RowType<RelationTargetFields<Target>>[]\n : RowType<RelationTargetFields<Target>> | null\n : never\n : never\n\nexport type WithOptions<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = {\n readonly [K in RelationKeys<Fields>]?: true\n}\n\nexport type WithResult<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n With,\n> = RowType<Fields> & { readonly [K in keyof With]: RelationResult<Fields[K & keyof Fields]> }\n\n/**\n * Options for findMany query.\n * `limit` is required (no default).\n * `offset` defaults to 0 if omitted.\n * `orderBy` is optional for column ordering.\n * `where` accepts either an equality object or a Drizzle SQL expression.\n */\nexport interface FindManyOptions<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n With extends WithOptions<Fields> | undefined = undefined,\n> {\n readonly limit: number\n readonly offset?: number\n readonly orderBy?: OrderBy<Fields>\n readonly where?: Where<Fields> | SQL\n readonly with?: With\n}\n\nexport interface FindOneOptions<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n With extends WithOptions<Fields> | undefined = undefined,\n> {\n readonly with?: With\n}\n\n/**\n * Options for findAll query.\n * No `limit` — issues no LIMIT clause. For batch processing / admin tooling.\n * Apply an app-level size guard when used in request handlers.\n */\nexport interface FindAllOptions<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> {\n readonly offset?: number\n readonly orderBy?: OrderBy<Fields>\n readonly where?: Where<Fields> | SQL\n}\n\n/**\n * Order-by specification: single field, or field with direction, or array of multiple.\n */\nexport type OrderBy<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> =\n | (NonRelationKeys<Fields> & string)\n | { readonly column: NonRelationKeys<Fields> & string; readonly direction?: 'asc' | 'desc' }\n | ReadonlyArray<\n | (NonRelationKeys<Fields> & string)\n | { readonly column: NonRelationKeys<Fields> & string; readonly direction?: 'asc' | 'desc' }\n >\n\n/**\n * Where clause object: each key is a field name, each value is the desired equality.\n */\nexport type Where<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = {\n readonly [K in NonRelationKeys<Fields>]?: InferFieldType<Fields[K]>\n}\n\n/**\n * Identifier or Where clause: can be a primary key value or a Where object.\n */\nexport type IdOrWhere<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = string | number | Where<Fields>\n\n/**\n * Row type: full record type from fields, excluding relation fields.\n */\nexport type RowType<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = {\n [K in NonRelationKeys<Fields>]: InferFieldType<Fields[K]>\n}\n\n/**\n * Drizzle table type with columns typed to match the model's Fields (excluding relation fields).\n * Allows type-safe column access via Model.table.fieldName.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\nexport type ModelTable<Fields extends Record<string, Field<any, any, any>>> =\n SQLiteTableWithColumns<{\n name: string\n schema: undefined\n columns: { [K in NonRelationKeys<Fields>]: AnySQLiteColumn }\n dialect: 'sqlite'\n }>\n\n/**\n * @internal\n * Extracts the policy from a Field's modifiers.\n *\n * Uses `Field<any, { policy: infer P }, any>` rather than a two-step\n * `infer M` + `M extends { policy: infer P }` pattern.\n * The two-step pattern is broken when TypeScript widens `M` to the constraint\n * `FieldModifiers` (which has `policy?: FieldPolicy` as optional), causing\n * `M extends { policy: infer P }` to be true for ALL fields regardless of their\n * actual policy value. Directly matching `{ policy: infer P }` avoids this.\n */\ntype PolicyOf<F> =\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n F extends Field<any, { policy: infer P extends FieldPolicy }, any> ? P : never\n\n/**\n * @internal\n * Computes which field keys should be omitted based on policy and usage.\n * Mirrors the runtime logic in derivePolicyOptions() in schema.ts.\n *\n * NOTE: `[PolicyOf<Fields[K]>] extends [never]` (non-distributive form) is used to\n * short-circuit fields with no policy to `never` (do not omit). Without this guard,\n * `never extends 'serverOnly'` evaluates to `true` (vacuously), causing every field\n * without a policy to be incorrectly included in the omit set.\n */\nexport type PolicyOmitKeys<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n Usage extends 'input-create' | 'input-update' | 'output',\n> = {\n [K in keyof Fields]: [PolicyOf<Fields[K]>] extends [never]\n ? never\n : PolicyOf<Fields[K]> extends 'serverOnly'\n ? K\n : Usage extends 'output'\n ? PolicyOf<Fields[K]> extends 'writeOnly'\n ? K\n : never\n : Usage extends 'input-create' | 'input-update'\n ? PolicyOf<Fields[K]> extends 'readOnly'\n ? K\n : never\n : never\n}[keyof Fields]\n\n/**\n * @internal\n * Computes which field keys have the serverOnly policy.\n * serverOnly fields are completely excluded from CreateInput\n * (cannot be passed even from library internals — they are server-side only).\n *\n * Uses `[PolicyOf<Fields[K]>] extends [never]` (non-distributive form) to short-circuit\n * fields with no policy to `never`. Without this guard, `never extends 'serverOnly'`\n * evaluates to `true` (vacuously), causing every field without a policy to be included.\n */\ntype ServerOnlyKeys<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = {\n [K in keyof Fields]: [PolicyOf<Fields[K]>] extends [never]\n ? never\n : PolicyOf<Fields[K]> extends 'serverOnly'\n ? K\n : never\n}[keyof Fields]\n\n/**\n * @internal\n * Determines if a field is required for create input.\n * A field is optional if it has a default, is optional, or is readOnly.\n *\n * Uses direct shape matching (`Field<any, { hasDefault: true }, any>`) to avoid\n * the TypeScript infer-widening issue where `infer M` resolves to `FieldModifiers`\n * (the constraint bound) instead of the concrete Mods type, causing `M extends\n * { policy: 'readOnly' }` to be false even for readOnly fields.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\ntype IsRequired<F extends Field<any, any, any>> =\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n F extends Field<any, { hasDefault: true }, any>\n ? false\n : // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n F extends Field<any, { optional: true }, any>\n ? false\n : // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n F extends Field<any, { policy: 'readOnly' }, any>\n ? false\n : true\n\n/**\n * Create input with precise types:\n * - `readOnly` fields are optional (library internals can pass them; API callers\n * are excluded via inputSchema — but CreateInput itself keeps them as optional\n * so handlers can supply generated values like `id` or `createdAt`)\n * - fields with `default` are optional\n * - fields marked `optional` are optional\n * - all other fields are required\n * - `serverOnly` fields are completely excluded (cannot be passed even internally)\n * - `writeOnly` fields are included as required (they are input fields by design)\n * - relation fields are completely excluded (no DB column)\n */\nexport type CreateInput<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = {\n [K in NonRelationKeys<Fields> as IsRequired<Fields[K]> extends true\n ? K extends ServerOnlyKeys<Fields>\n ? never\n : K\n : never]: InferFieldType<Fields[K]>\n} & {\n [K in NonRelationKeys<Fields> as IsRequired<Fields[K]> extends true\n ? never\n : K extends ServerOnlyKeys<Fields>\n ? never\n : K]?: InferFieldType<Fields[K]>\n}\n\nexport type FieldAccessor<K extends string> = { readonly [Key in K]: Key }\n\nexport interface SchemaOptions<K extends string = string> {\n readonly pick?: readonly K[] | ((f: FieldAccessor<K>) => readonly K[])\n readonly omit?: readonly K[] | ((f: FieldAccessor<K>) => readonly K[])\n readonly partial?: boolean\n}\n\n/**\n * @internal\n * Resolves pick/omit option to string array using the accessor when it's a function.\n */\nexport function resolveSchemaOptionKeys<K extends string>(\n opt: readonly K[] | ((f: FieldAccessor<K>) => readonly K[]) | undefined,\n accessor: FieldAccessor<K>,\n): readonly K[] | undefined {\n if (opt === undefined) return undefined\n if (typeof opt === 'function') return opt(accessor)\n return opt\n}\n\n/**\n * @internal\n * Builds a frozen field accessor object for use in schema/validator options.\n * Relation fields are excluded so that `omit: f => [f.posts]` is a type error.\n * Each non-relation key maps to itself, providing typo detection at type level.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\nexport function buildFieldAccessor<Fields extends Record<string, Field<any, any, any>>>(\n fields: Fields,\n): { readonly [K in NonRelationKeys<Fields>]: K } {\n const acc: Record<string, string> = {}\n for (const [k, field] of Object.entries(fields)) {\n if (field.kind === 'relation') continue\n acc[k] = k\n }\n return Object.freeze(acc) as { readonly [K in NonRelationKeys<Fields>]: K }\n}\n\n/**\n * @internal\n * Extracts a Zod shape from fields for the Apply type.\n * Only non-relation fields are included (relation fields have zodBase: ZodNever\n * and are skipped at runtime in buildBaseObject).\n * Indexed access ensures concrete Zod types are preserved (not `any`).\n */\nexport type FieldsToZodShape<\n Fields extends Record<\n string,\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Field<any, any, any>\n >,\n> = {\n [K in NonRelationKeys<Fields>]: Fields[K]['zodBase']\n}\n\n/**\n * @internal\n * Utility to narrow array literal types to union of strings.\n */\ntype ArrayKeys<A> = A extends readonly (infer U)[] ? U : never\n\n/**\n * @internal\n * Resolves pick/omit option type to the array type.\n * Handles both array form and accessor function form.\n */\ntype ResolveOptKeys<Opt> = Opt extends readonly string[]\n ? Opt\n : Opt extends (f: FieldAccessor<infer _K>) => readonly (infer R)[]\n ? readonly R[]\n : never\n\n/**\n * @internal\n * Apply pick transformation to a shape.\n */\ntype ApplyPickToShape<Shape extends z.ZodRawShape, PickOpt> =\n ResolveOptKeys<PickOpt> extends readonly string[]\n ? Pick<Shape, ArrayKeys<ResolveOptKeys<PickOpt>> & keyof Shape>\n : Shape\n\n/**\n * @internal\n * Apply omit transformation to a shape.\n */\ntype ApplyOmitToShape<Shape extends z.ZodRawShape, OmitOpt> =\n ResolveOptKeys<OmitOpt> extends readonly string[]\n ? Omit<Shape, ArrayKeys<ResolveOptKeys<OmitOpt>> & keyof Shape>\n : Shape\n\n/**\n * @internal\n * Apply partial transformation to a shape.\n */\ntype ApplyPartialToShape<Shape extends z.ZodRawShape> = {\n [K in keyof Shape]: z.ZodOptional<Shape[K]>\n}\n\n/**\n * @internal\n * Checks if an option value (array or function) is present (i.e. not undefined and not never).\n * Uses distributive conditional to handle union types like `T | undefined`.\n */\ntype HasOpt<Opt> = undefined extends Opt ? false : [Opt] extends [never] ? false : true\n\n/**\n * @internal\n * Apply pick/omit/partial transformations to a Zod raw shape.\n * Order: pick → omit → partial\n * Handles both array form and accessor function form for pick/omit.\n */\ntype ApplyShape<\n Shape extends z.ZodRawShape,\n Opts extends SchemaOptions | undefined,\n> = Opts extends SchemaOptions\n ? HasOpt<Opts['pick']> extends true\n ? HasOpt<Opts['omit']> extends true\n ? Opts extends { partial: true }\n ? ApplyPartialToShape<ApplyOmitToShape<ApplyPickToShape<Shape, Opts['pick']>, Opts['omit']>>\n : ApplyOmitToShape<ApplyPickToShape<Shape, Opts['pick']>, Opts['omit']>\n : Opts extends { partial: true }\n ? ApplyPartialToShape<ApplyPickToShape<Shape, Opts['pick']>>\n : ApplyPickToShape<Shape, Opts['pick']>\n : HasOpt<Opts['omit']> extends true\n ? Opts extends { partial: true }\n ? ApplyPartialToShape<ApplyOmitToShape<Shape, Opts['omit']>>\n : ApplyOmitToShape<Shape, Opts['omit']>\n : Opts extends { partial: true }\n ? ApplyPartialToShape<Shape>\n : Shape\n : Shape\n\n/**\n * @internal\n * Returns the correct Zod object type after applying pick/omit/partial transformations.\n */\nexport type Apply<\n Shape extends z.ZodRawShape,\n Opts extends SchemaOptions | undefined,\n> = z.ZodObject<ApplyShape<Shape, Opts>>\n\n/**\n * @internal\n * Apply pick transformation to a TS record type.\n */\ntype ApplyPickToRecord<R, PickOpt> =\n ResolveOptKeys<PickOpt> extends readonly string[]\n ? Pick<R, ArrayKeys<ResolveOptKeys<PickOpt>> & keyof R>\n : R\n\n/**\n * @internal\n * Apply omit transformation to a TS record type.\n */\ntype ApplyOmitToRecord<R, OmitOpt> =\n ResolveOptKeys<OmitOpt> extends readonly string[]\n ? Omit<R, ArrayKeys<ResolveOptKeys<OmitOpt>> & keyof R>\n : R\n\n/**\n * @internal\n * Apply pick/omit/partial transformations to a TypeScript record type.\n * Mirrors ApplyShape but operates on TS types directly, not Zod shapes.\n * Used for Zod v3/v4 compatible middleware input/output type computation.\n */\ntype ApplyToRecord<R, Opts extends SchemaOptions | undefined> = Opts extends SchemaOptions\n ? HasOpt<Opts['pick']> extends true\n ? HasOpt<Opts['omit']> extends true\n ? Opts extends { partial: true }\n ? Partial<ApplyOmitToRecord<ApplyPickToRecord<R, Opts['pick']>, Opts['omit']>>\n : ApplyOmitToRecord<ApplyPickToRecord<R, Opts['pick']>, Opts['omit']>\n : Opts extends { partial: true }\n ? Partial<ApplyPickToRecord<R, Opts['pick']>>\n : ApplyPickToRecord<R, Opts['pick']>\n : HasOpt<Opts['omit']> extends true\n ? Opts extends { partial: true }\n ? Partial<ApplyOmitToRecord<R, Opts['omit']>>\n : ApplyOmitToRecord<R, Opts['omit']>\n : Opts extends { partial: true }\n ? Partial<R>\n : R\n : R\n\n/**\n * @internal\n * Mirrors @hono/zod-validator's middleware Input type.\n * Aligned with @hono/zod-validator@0.4.x; revisit on version bump.\n */\ntype HasUndefined<T> = undefined extends T ? true : false\n\n/**\n * @internal\n * Hono middleware input/output type for validator middleware.\n * Aligned with @hono/zod-validator@0.4.x; revisit on version bump.\n *\n * WARNING (Zod 4): `z.input<ZodTypeAny>` resolves to `unknown` in Zod 4, making\n * `c.req.valid(target)` return `unknown` if `In`/`Out` are left as defaults.\n * When using this type directly (outside of `ModelValidatorReturn`), always pass\n * explicit `In` and `Out` type arguments — do NOT rely on the defaults.\n *\n * Internal usages in this file (ModelValidatorReturn and preset overloads) already\n * pass `In`/`Out` explicitly via `ApplyToRecord` or `Omit<RowType<Fields>, ...>`.\n */\nexport type ValidatorInput<\n Target extends keyof ValidationTargets,\n Schema extends z.ZodTypeAny,\n In = z.input<Schema>,\n Out = z.output<Schema>,\n> = {\n in: HasUndefined<In> extends true\n ? {\n [K in Target]?:\n | (In extends ValidationTargets[K]\n ? In\n : { [K2 in keyof In]?: ValidationTargets[K][K2] | undefined })\n | undefined\n }\n : {\n [K in Target]: In extends ValidationTargets[K]\n ? In\n : { [K2 in keyof In]: ValidationTargets[K][K2] }\n }\n out: { [K in Target]: Out }\n}\n\n/**\n * @internal\n * Type-safe Hono middleware handler return for Model.validator().\n * Provides proper type narrowing for c.req.valid(target).\n *\n * Uses RowType<Fields> directly for input/output type computation\n * to ensure Zod v3/v4 compatibility (z.input<ZodTypeAny> returns unknown in Zod v4).\n */\nexport type ModelValidatorReturn<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n Target extends keyof ValidationTargets,\n Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined,\n> = MiddlewareHandler<\n any,\n string,\n ValidatorInput<\n Target,\n Apply<FieldsToZodShape<Fields>, Opts>,\n ApplyToRecord<RowType<Fields>, Opts>,\n ApplyToRecord<RowType<Fields>, Opts>\n >\n>\n\n/**\n * Hook type for Model.validator() third argument.\n * Re-exported from @hono/zod-validator for convenience.\n */\nexport type { Hook }\n\n/**\n * Represents a database model with type-safe schema derivation and CRUD operations.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for the generic Field constraint\nexport interface Model<Fields extends Record<string, Field<any, any, any>>> {\n readonly fields: Fields\n readonly tableName: string\n readonly table: ModelTable<Fields>\n\n /**\n * Returns a Zod schema derived from this model's fields.\n * Supports pick, omit, and partial transformations.\n *\n * @example\n * const CreateSchema = User.schema({ omit: ['passwordHash'] })\n * const UpdateSchema = User.schema({ partial: true, pick: ['name', 'email'] })\n */\n schema<Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined>(\n opts?: Opts,\n ): Apply<FieldsToZodShape<Fields>, Opts>\n\n /**\n * Returns a Hono middleware validator derived from this model's schema.\n * Integrates with @hono/zod-validator to validate request inputs.\n * The optional `hook` argument is passed through to @hono/zod-validator.\n *\n * Accepts a preset ('create' | 'update') as second argument to use inputSchema.\n * When a preset is used, the return type is a MiddlewareHandler (loosely typed in Phase 2A).\n * Precise type narrowing for preset is deferred to Phase 2B M2.3.\n *\n * @example\n * app.post('/users', User.validator('json', 'create'), c => {\n * const body = c.req.valid('json')\n * })\n * app.post('/users', User.validator('json', { omit: ['passwordHash'] }), c => {\n * const body = c.req.valid('json')\n * })\n * // With hook:\n * app.post('/users', User.validator('json', opts, (result, c) => {\n * if (!result.success) return c.json({ error: 'Invalid request' }, 400)\n * }), handler)\n */\n validator<Target extends keyof ValidationTargets, E extends Env = Env, P extends string = string>(\n target: Target,\n preset: 'create',\n hook?: Hook<\n Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-create'> & string>,\n E,\n P,\n Target\n >,\n ): MiddlewareHandler<\n E,\n P,\n ValidatorInput<\n Target,\n z.ZodObject<z.ZodRawShape>,\n Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-create'> & string>,\n Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-create'> & string>\n >\n >\n validator<Target extends keyof ValidationTargets, E extends Env = Env, P extends string = string>(\n target: Target,\n preset: 'update',\n hook?: Hook<\n Partial<Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-update'> & string>>,\n E,\n P,\n Target\n >,\n ): MiddlewareHandler<\n E,\n P,\n ValidatorInput<\n Target,\n z.ZodObject<z.ZodRawShape>,\n Partial<Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-update'> & string>>,\n Partial<Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-update'> & string>>\n >\n >\n validator<\n Target extends keyof ValidationTargets,\n Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined,\n E extends Env = Env,\n P extends string = string,\n >(\n target: Target,\n opts?: Opts,\n hook?: Hook<z.output<Apply<FieldsToZodShape<Fields>, Opts>>, E, P, Target>,\n ): ModelValidatorReturn<Fields, Target, Opts>\n\n /**\n * Returns a Zod schema for API input, with policy-based field exclusions applied.\n * - 'create': serverOnly and readOnly fields are excluded\n * - 'update': same exclusions + all fields become optional (partial: true)\n *\n * The return type precisely reflects policy-derived omissions using PolicyOmitKeys.\n */\n inputSchema<Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined = undefined>(\n usage: 'create',\n opts?: Opts,\n ): z.ZodObject<\n ApplyShape<\n Omit<FieldsToZodShape<Fields>, PolicyOmitKeys<Fields, 'input-create'> & string>,\n Opts\n >\n >\n inputSchema<Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined = undefined>(\n usage: 'update',\n opts?: Opts,\n ): z.ZodObject<\n ApplyShape<\n Omit<FieldsToZodShape<Fields>, PolicyOmitKeys<Fields, 'input-update'> & string>,\n Opts extends undefined ? { partial: true } : Opts & { partial: true }\n >\n >\n inputSchema(\n usage: 'create' | 'update',\n opts?: SchemaOptions<NonRelationKeys<Fields> & string>,\n ): z.ZodObject<z.ZodRawShape>\n\n /**\n * Returns a Zod schema for API output, with policy-based field exclusions applied.\n * - serverOnly and writeOnly fields are excluded\n * - readOnly fields remain present\n *\n * The return type precisely reflects policy-derived omissions using PolicyOmitKeys.\n */\n outputSchema<\n Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined = undefined,\n >(\n opts?: Opts,\n ): z.ZodObject<\n ApplyShape<Omit<FieldsToZodShape<Fields>, PolicyOmitKeys<Fields, 'output'> & string>, Opts>\n >\n\n /**\n * Parses a DB row through outputSchema and returns the safe response object.\n * Equivalent to `User.outputSchema().parse(row)`.\n */\n toResponse(row: RowType<Fields>): unknown\n\n /**\n * Parses an array of DB rows through outputSchema and returns safe response objects.\n * The outputSchema is built once and reused for all rows.\n * Equivalent to mapping `toResponse` over the array but more efficient.\n *\n * @example\n * const rows = await app.db.select().from(User.table).where(...)\n * return c.json(User.toResponseMany(rows))\n */\n toResponseMany(rows: readonly RowType<Fields>[]): unknown[]\n\n toOpenAPIComponent(): OpenAPIModelComponent\n\n toOpenAPISchema(usage: OpenAPIUsage): OpenAPISchemaObject\n\n /**\n * Fetches multiple rows with pagination and optional ordering.\n * `limit` is required (no default) to prevent accidental unbounded queries.\n * Offset defaults to 0 if omitted.\n *\n * @example\n * const users = await User.findMany(adapter, { limit: 20 })\n * const page2 = await User.findMany(adapter, { limit: 20, offset: 20 })\n * const sorted = await User.findMany(adapter, { limit: 10, orderBy: 'name' })\n */\n findMany<With extends WithOptions<Fields>>(\n adapter: Adapter,\n options: FindManyOptions<Fields, With> & { readonly with: With },\n ): Promise<WithResult<Fields, With>[]>\n findMany(adapter: Adapter, options: FindManyOptions<Fields>): Promise<RowType<Fields>[]>\n\n /**\n * Fetches all rows without a LIMIT clause.\n * For batch processing / admin tooling. Apply an app-level size guard when used in request handlers.\n *\n * @example\n * const users = await User.findAll(adapter)\n * const admins = await User.findAll(adapter, { orderBy: 'name', where: { role: 'admin' } })\n */\n findAll(adapter: Adapter, options?: FindAllOptions<Fields>): Promise<RowType<Fields>[]>\n\n /**\n * Fetches a single row by primary key or where clause.\n * Returns null if not found.\n *\n * @example\n * const user = await User.findOne(adapter, id)\n * const byEmail = await User.findOne(adapter, { email: 'john@example.com' })\n */\n findOne<With extends WithOptions<Fields>>(\n adapter: Adapter,\n idOrWhere: IdOrWhere<Fields>,\n options: FindOneOptions<Fields, With> & { readonly with: With },\n ): Promise<WithResult<Fields, With> | null>\n findOne(adapter: Adapter, idOrWhere: IdOrWhere<Fields>): Promise<RowType<Fields> | null>\n\n /**\n * Creates a new row and returns the created record.\n *\n * @example\n * const user = await User.create(adapter, { name: 'John', email: 'john@example.com' })\n */\n create(adapter: Adapter, data: CreateInput<Fields>): Promise<RowType<Fields>>\n\n /**\n * Updates rows matching the given id or where clause.\n * Returns the updated row(s), or null if no rows matched.\n *\n * @example\n * const updated = await User.update(adapter, id, { name: 'Jane' })\n * const byEmail = await User.update(adapter, { email: '...' }, { name: 'Jane' })\n */\n update(\n adapter: Adapter,\n idOrWhere: IdOrWhere<Fields>,\n data: Partial<RowType<Fields>>,\n ): Promise<RowType<Fields> | null>\n\n /**\n * Deletes rows matching the given id or where clause.\n * Returns the number of deleted rows.\n *\n * @example\n * const result = await User.delete(adapter, id)\n * console.log(result.deleted) // number\n */\n delete(adapter: Adapter, idOrWhere: IdOrWhere<Fields>): Promise<{ readonly deleted: number }>\n}\n","import { z } from 'zod'\nimport type { Field } from '../field/types'\nimport { type FieldAccessor, resolveSchemaOptionKeys, type SchemaOptions } from './types'\n\ntype PolicyUsage = 'input-create' | 'input-update' | 'output'\n\n/**\n * Returns field names that are security-critical and must always be omitted from API schemas.\n * Currently only serverOnly fields. These cannot be overridden by user pick/omit.\n */\nfunction computeForcedOmit(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field handling\n fields: Record<string, Field<any, any, any>>,\n): string[] {\n const omit: string[] = []\n for (const [key, field] of Object.entries(fields)) {\n if (field.modifiers.policy === 'serverOnly') {\n omit.push(key)\n }\n }\n return omit\n}\n\n/**\n * Returns field names for relation fields that must always be omitted from API schemas.\n * Relation fields have no DB column and no Zod schema representation.\n */\nfunction computeRelationOmit(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field handling\n fields: Record<string, Field<any, any, any>>,\n): Set<string> {\n const keys = new Set<string>()\n for (const [key, field] of Object.entries(fields)) {\n if (field.kind === 'relation') keys.add(key)\n }\n return keys\n}\n\n/**\n * Returns field names to omit based on UX-oriented policy (writeOnly / readOnly).\n * These can be overridden when user explicitly provides pick.\n *\n * Policy mapping:\n * - `writeOnly`: omitted from output only. For input targets (input-create, input-update),\n * writeOnly fields are NOT omitted — they are intentionally part of the input (e.g. password).\n * - `readOnly`: omitted from input targets (input-create, input-update) only. Remains in output.\n *\n * The asymmetry is by design: writeOnly means \"accepted on write, hidden on read\";\n * readOnly means \"visible on read, rejected on write\".\n */\nfunction computeOptionalOmit(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field handling\n fields: Record<string, Field<any, any, any>>,\n target: PolicyUsage,\n): string[] {\n const omit: string[] = []\n for (const [key, field] of Object.entries(fields)) {\n const policy = field.modifiers.policy\n if (!policy) continue\n if (policy === 'writeOnly' && target === 'output') {\n omit.push(key)\n } else if (policy === 'readOnly' && (target === 'input-create' || target === 'input-update')) {\n omit.push(key)\n }\n }\n return omit\n}\n\n/**\n * Merges policy-derived omit with user-provided SchemaOptions.\n *\n * serverOnly fields are always omitted regardless of user pick/omit (security invariant).\n * writeOnly / readOnly are UX-oriented and can be overridden when user provides pick.\n * For 'input-update', partial defaults to true unless user specifies otherwise.\n */\nexport function derivePolicyOptions(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field handling\n fields: Record<string, Field<any, any, any>>,\n usage: PolicyUsage,\n userOpts?: SchemaOptions,\n // biome-ignore lint/suspicious/noExplicitAny: accessor is a plain object with string keys\n accessor?: FieldAccessor<any>,\n): SchemaOptions {\n const forcedBase = computeForcedOmit(fields)\n const relationOmit = computeRelationOmit(fields)\n const forced = [...new Set([...forcedBase, ...relationOmit])]\n const optional = computeOptionalOmit(fields, usage)\n\n const acc = accessor ?? ({} as FieldAccessor<string>)\n const resolvedPick = resolveSchemaOptionKeys(userOpts?.pick, acc)\n const resolvedOmit = resolveSchemaOptionKeys(userOpts?.omit, acc)\n\n if (resolvedPick !== undefined) {\n const partial = usage === 'input-update' ? (userOpts?.partial ?? true) : userOpts?.partial\n // serverOnly fields are stripped from pick even if user explicitly listed them\n const sanitizedPick = Array.from(resolvedPick).filter((k) => !forced.includes(k))\n // Combine forced omit with user-provided omit to preserve both constraints\n const combinedOmit = [...new Set([...forced, ...(resolvedOmit ?? [])])]\n return {\n ...userOpts,\n pick: sanitizedPick,\n ...(combinedOmit.length > 0 ? { omit: combinedOmit } : {}),\n partial,\n }\n }\n\n const combinedOmit = [...new Set([...forced, ...optional, ...(resolvedOmit ?? [])])]\n const partial =\n usage === 'input-update' ? (userOpts?.partial ?? true) : (userOpts?.partial ?? undefined)\n\n return {\n ...(userOpts ?? {}),\n pick: undefined,\n ...(combinedOmit.length > 0 ? { omit: combinedOmit } : {}),\n ...(partial !== undefined ? { partial } : {}),\n }\n}\n\n/**\n * Builds a Zod object schema from a fields definition.\n * Returns a ZodObject with all fields required and present.\n * Relation fields are excluded as they have no Zod schema representation.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field handling and Zod shape\nexport function buildBaseObject(fields: Record<string, Field<any, any, any>>): z.ZodObject<any> {\n // biome-ignore lint/suspicious/noExplicitAny: Record key-value pairs have any type for shape\n const shape: Record<string, any> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (field.kind === 'relation') continue\n shape[key] = field.zodBase\n }\n return z.object(shape)\n}\n\n/**\n * Applies pick, omit, and partial transformations to a Zod object schema.\n * Order: pick → omit → partial\n *\n * Returns the transformed schema, cast to Apply<Shape, Opts> at the call site.\n */\nexport function applySchemaOptions(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Zod shape operations\n baseSchema: z.ZodObject<any>,\n opts: SchemaOptions | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: accessor is a plain object with string keys\n accessor?: FieldAccessor<any>,\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for return type\n): z.ZodObject<any> {\n if (!opts) {\n return baseSchema\n }\n\n const acc = accessor ?? ({} as FieldAccessor<string>)\n const resolvedPick = resolveSchemaOptionKeys(opts.pick, acc)\n const resolvedOmit = resolveSchemaOptionKeys(opts.omit, acc)\n\n let schema = baseSchema\n\n // Apply pick\n if (resolvedPick !== undefined) {\n const pickArray = Array.from(resolvedPick)\n schema = schema.pick(\n // biome-ignore lint/suspicious/noExplicitAny: Zod API\n Object.fromEntries(pickArray.map((k) => [k, true])) as any,\n )\n }\n\n // Apply omit\n if (resolvedOmit !== undefined) {\n const omitArray = Array.from(resolvedOmit)\n schema = schema.omit(\n // biome-ignore lint/suspicious/noExplicitAny: Zod API\n Object.fromEntries(omitArray.map((k) => [k, true])) as any,\n )\n }\n\n // Apply partial\n // `partial: false` を渡してもこの条件で何もしない。スキーマは required のまま。\n if (opts.partial === true) {\n schema = schema.partial()\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Cast to Apply type at call site\n return schema as any\n}\n","import type { Field } from '../field/types'\nimport { applySchemaOptions, buildBaseObject, derivePolicyOptions } from '../model/schema'\nimport type { SchemaOptions } from '../model/types'\nimport type { OpenAPIModelComponent, OpenAPISchemaObject, OpenAPIUsage } from './types'\n\n// biome-ignore lint/suspicious/noExplicitAny: OpenAPI generation accepts any concrete field builder.\ntype AnyField = Field<any, any, any>\ntype FieldsRecord = Record<string, AnyField>\n\ninterface OpenAPIOptions {\n readonly opts?: SchemaOptions\n readonly strict?: boolean\n}\n\nexport function toOpenAPIComponent(\n fields: FieldsRecord,\n opts?: OpenAPIOptions,\n): OpenAPIModelComponent {\n return {\n create: toOpenAPISchema(fields, 'create', opts),\n update: toOpenAPISchema(fields, 'update', opts),\n output: toOpenAPISchema(fields, 'output', opts),\n }\n}\n\nexport function toOpenAPISchema(\n fields: FieldsRecord,\n usage: OpenAPIUsage,\n opts?: OpenAPIOptions,\n): OpenAPISchemaObject {\n const policyUsage =\n usage === 'create' ? 'input-create' : usage === 'update' ? 'input-update' : 'output'\n const merged = derivePolicyOptions(fields, policyUsage, opts?.opts)\n const schema = applySchemaOptions(buildBaseObject(fields), merged)\n const shape = getZodObjectShape(schema)\n const properties: Record<string, OpenAPISchemaObject> = {}\n const required: string[] = []\n\n for (const [key, zodSchema] of Object.entries(shape)) {\n const field = fields[key]\n if (field === undefined) continue\n if (field.kind === 'relation') continue\n\n properties[key] = fieldToOpenAPISchema(field, opts?.strict)\n if (field.modifiers.policy === 'writeOnly' && (usage === 'create' || usage === 'update')) {\n properties[key].writeOnly = true\n }\n if (field.modifiers.policy === 'readOnly' && usage === 'output') {\n properties[key].readOnly = true\n }\n if (usage !== 'update' && isRequiredZodSchema(zodSchema)) {\n required.push(key)\n }\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n }\n}\n\nfunction fieldToOpenAPISchema(field: AnyField, strict = false): OpenAPISchemaObject {\n const schema: OpenAPISchemaObject =\n field.kind === 'json'\n ? zodToOpenAPISchema(field.zodBase, strict)\n : field.kind === 'string'\n ? { type: 'string' }\n : field.kind === 'uuid'\n ? { type: 'string', format: 'uuid' }\n : field.kind === 'number'\n ? { type: 'number' }\n : field.kind === 'integer'\n ? { type: 'integer' }\n : field.kind === 'boolean'\n ? { type: 'boolean' }\n : field.kind === 'timestamp'\n ? { type: 'string', format: 'date-time' }\n : {}\n\n if (field.modifiers.format === 'email') {\n schema.format = 'email'\n }\n if (field.modifiers.min !== undefined) {\n if (field.kind === 'string' || field.kind === 'uuid') {\n schema.minLength = field.modifiers.min\n } else {\n schema.minimum = field.modifiers.min\n }\n }\n if (field.modifiers.max !== undefined) {\n if (field.kind === 'string' || field.kind === 'uuid') {\n schema.maxLength = field.modifiers.max\n } else {\n schema.maximum = field.modifiers.max\n }\n }\n\n if (field.modifiers.optional) {\n schema.nullable = true\n }\n\n return schema\n}\n\nfunction zodToOpenAPISchema(schema: unknown, strict = false): OpenAPISchemaObject {\n const def = getZodDef(schema)\n if (def === undefined) return {}\n\n const typeName = getZodTypeName(def)\n\n if (typeName === 'ZodOptional' || typeName === 'optional') {\n return zodToOpenAPISchema(def.innerType, strict)\n }\n if (typeName === 'ZodDefault' || typeName === 'default') {\n return zodToOpenAPISchema(def.innerType, strict)\n }\n if (typeName === 'ZodNullable' || typeName === 'nullable') {\n return { ...zodToOpenAPISchema(def.innerType, strict), nullable: true }\n }\n\n if (typeName === 'ZodObject' || typeName === 'object') {\n const shape = getZodObjectShape(schema)\n const properties: Record<string, OpenAPISchemaObject> = {}\n const required: string[] = []\n\n for (const [key, childSchema] of Object.entries(shape)) {\n properties[key] = zodToOpenAPISchema(childSchema, strict)\n if (isRequiredZodSchema(childSchema)) {\n required.push(key)\n }\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n }\n }\n\n if (typeName === 'ZodString' || typeName === 'string') {\n return applyStringChecks({ type: 'string' }, def)\n }\n\n if (typeName === 'ZodNumber' || typeName === 'number') {\n return applyNumberChecks({ type: hasIntegerCheck(def) ? 'integer' : 'number' }, def)\n }\n\n if (typeName === 'ZodBoolean' || typeName === 'boolean') {\n return { type: 'boolean' }\n }\n\n if (typeName === 'ZodArray' || typeName === 'array') {\n const itemSchema = def.element ?? def.type\n return {\n type: 'array',\n items: zodToOpenAPISchema(itemSchema, strict),\n }\n }\n\n if (typeName === 'ZodRecord' || typeName === 'record') {\n return {\n type: 'object',\n additionalProperties: zodToOpenAPISchema(def.valueType, strict),\n }\n }\n\n if (typeName === 'ZodUnknown' || typeName === 'unknown') {\n return {}\n }\n\n if (strict) {\n throw new Error(`Unsupported Zod type for strict OpenAPI generation: ${typeName ?? 'unknown'}`)\n }\n return {\n 'x-nanoka-zod-unsupported': true,\n ...(typeName ? { 'x-nanoka-zod-type': typeName } : {}),\n }\n}\n\nfunction getZodObjectShape(schema: unknown): Record<string, unknown> {\n if (\n typeof schema === 'object' &&\n schema !== null &&\n 'shape' in schema &&\n typeof schema.shape === 'object' &&\n schema.shape !== null\n ) {\n return schema.shape as Record<string, unknown>\n }\n\n if (\n typeof schema === 'object' &&\n schema !== null &&\n '_def' in schema &&\n typeof schema._def === 'object' &&\n schema._def !== null &&\n 'shape' in schema._def\n ) {\n const shape = schema._def.shape\n return (typeof shape === 'function' ? shape() : shape) as Record<string, unknown>\n }\n\n return {}\n}\n\nfunction isRequiredZodSchema(schema: unknown): boolean {\n const def = getZodDef(schema)\n if (def === undefined) {\n return true\n }\n\n const typeName = getZodTypeName(def)\n return (\n typeName !== 'ZodOptional' &&\n typeName !== 'optional' &&\n typeName !== 'ZodDefault' &&\n typeName !== 'default'\n )\n}\n\nfunction getZodDef(schema: unknown): Record<string, unknown> | undefined {\n if (\n typeof schema === 'object' &&\n schema !== null &&\n '_def' in schema &&\n typeof schema._def === 'object' &&\n schema._def !== null\n ) {\n return schema._def as Record<string, unknown>\n }\n\n return undefined\n}\n\nfunction getZodTypeName(def: Record<string, unknown>): string | undefined {\n return typeof def.typeName === 'string'\n ? def.typeName\n : typeof def.type === 'string'\n ? def.type\n : undefined\n}\n\nfunction applyStringChecks(\n schema: OpenAPISchemaObject,\n def: Record<string, unknown>,\n): OpenAPISchemaObject {\n for (const check of getZodChecks(def)) {\n const checkDef = getZodCheckDef(check)\n if (checkDef.kind === 'email' || checkDef.format === 'email') {\n schema.format = 'email'\n }\n if (checkDef.kind === 'min' && typeof checkDef.value === 'number') {\n schema.minLength = checkDef.value\n }\n if (checkDef.kind === 'max' && typeof checkDef.value === 'number') {\n schema.maxLength = checkDef.value\n }\n if (checkDef.check === 'min_length' && typeof checkDef.minimum === 'number') {\n schema.minLength = checkDef.minimum\n }\n if (checkDef.check === 'max_length' && typeof checkDef.maximum === 'number') {\n schema.maxLength = checkDef.maximum\n }\n }\n\n return schema\n}\n\nfunction applyNumberChecks(\n schema: OpenAPISchemaObject,\n def: Record<string, unknown>,\n): OpenAPISchemaObject {\n for (const check of getZodChecks(def)) {\n const checkDef = getZodCheckDef(check)\n if (checkDef.kind === 'min' && typeof checkDef.value === 'number') {\n schema.minimum = checkDef.value\n }\n if (checkDef.kind === 'max' && typeof checkDef.value === 'number') {\n schema.maximum = checkDef.value\n }\n if (\n (checkDef.check === 'greater_than' || checkDef.check === 'number_format') &&\n typeof checkDef.minimum === 'number'\n ) {\n schema.minimum = checkDef.minimum\n }\n if (\n (checkDef.check === 'less_than' || checkDef.check === 'number_format') &&\n typeof checkDef.maximum === 'number'\n ) {\n schema.maximum = checkDef.maximum\n }\n }\n\n return schema\n}\n\nfunction hasIntegerCheck(def: Record<string, unknown>): boolean {\n return getZodChecks(def).some((check) => {\n const checkDef = getZodCheckDef(check)\n return (\n checkDef.kind === 'int' ||\n checkDef.format === 'safeint' ||\n checkDef.format === 'int32' ||\n checkDef.format === 'int64'\n )\n })\n}\n\nfunction getZodChecks(def: Record<string, unknown>): readonly unknown[] {\n return Array.isArray(def.checks) ? def.checks : []\n}\n\nfunction getZodCheckDef(check: unknown): Record<string, unknown> {\n if (typeof check !== 'object' || check === null) {\n return {}\n }\n if (\n '_zod' in check &&\n typeof check._zod === 'object' &&\n check._zod !== null &&\n 'def' in check._zod &&\n typeof check._zod.def === 'object' &&\n check._zod.def !== null\n ) {\n return check._zod.def as Record<string, unknown>\n }\n\n return check as Record<string, unknown>\n}\n","import {\n type AnySQLiteColumn,\n type SQLiteTableWithColumns,\n sqliteTable,\n} from 'drizzle-orm/sqlite-core'\nimport type { Field } from '../field/types'\nimport type { NonRelationKeys } from './types'\n\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\ntype ModelTable<Fields extends Record<string, Field<any, any, any>>> = SQLiteTableWithColumns<{\n name: string\n schema: undefined\n columns: { [K in NonRelationKeys<Fields>]: AnySQLiteColumn }\n dialect: 'sqlite'\n}>\n\n/**\n * Constructs a Drizzle SQLiteTable from a tableName and fields.\n * Each field is converted to a Drizzle column via field.drizzleColumn(key).\n * @internal\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\nexport function buildTable<Fields extends Record<string, Field<any, any, any>>>(\n tableName: string,\n fields: Fields,\n): ModelTable<Fields> {\n const columns: Record<string, any> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (field.kind === 'relation') continue\n columns[key] = field.drizzleColumn(key)\n }\n return sqliteTable(tableName, columns) as unknown as ModelTable<Fields>\n}\n","import { and, asc, desc, eq, inArray, SQL } from 'drizzle-orm'\nimport type { SQLiteTableWithColumns } from 'drizzle-orm/sqlite-core'\nimport { HTTPException } from 'hono/http-exception'\nimport type { Adapter } from '../adapter/types'\nimport type { Field, RelationDef, RelationTargetLike } from '../field/types'\nimport { buildTable } from './table'\nimport type {\n CreateInput,\n FindAllOptions,\n FindOneOptions,\n IdOrWhere,\n OrderBy,\n RowType,\n Where,\n WithOptions,\n WithResult,\n} from './types'\n\n/**\n * Validates and guards limit/offset parameters.\n * @internal\n */\nfunction guardLimit(limit: unknown): number {\n if (!Number.isInteger(limit)) {\n throw new HTTPException(400, { message: 'limit must be an integer' })\n }\n const n = limit as number\n if (n < 0) {\n throw new HTTPException(400, { message: 'limit must be >= 0' })\n }\n return n\n}\n\nfunction guardOffset(offset: unknown): number {\n if (!Number.isInteger(offset)) {\n throw new HTTPException(400, { message: 'offset must be an integer' })\n }\n const n = offset as number\n if (n < 0) {\n throw new HTTPException(400, { message: 'offset must be >= 0' })\n }\n return n\n}\n\n/**\n * Finds the primary key field from fields record.\n * @internal\n */\nfunction findPrimaryKey(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n fields: Record<string, Field<any, any, any>>,\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n): [string, Field<any, any, any>] | null {\n let pkKey: string | undefined\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n let pkField: Field<any, any, any> | undefined\n let pkCount = 0\n\n for (const [key, field] of Object.entries(fields)) {\n if (field.modifiers.primary === true) {\n pkCount++\n if (pkCount === 1) {\n pkKey = key\n pkField = field\n }\n }\n }\n\n if (pkCount === 0) {\n return null\n }\n if (pkCount > 1) {\n throw new HTTPException(500, { message: 'model has multiple primary keys' })\n }\n if (pkKey === undefined || pkField === undefined) {\n return null\n }\n\n return [pkKey, pkField]\n}\n\n/**\n * Constructs a Drizzle where clause from an object.\n * All entries are combined with AND.\n * @internal\n */\nfunction buildWhereClause(\n table: SQLiteTableWithColumns<any>,\n fields: Record<string, Field<any, any, any>>,\n where: Where<Record<string, any>>,\n): ReturnType<typeof and> | null {\n const conditions: ReturnType<typeof eq>[] = []\n\n for (const [key, value] of Object.entries(where)) {\n // Multi-layered guard against identifier injection\n if (!Object.hasOwn(fields, key)) {\n throw new HTTPException(400, { message: 'invalid field in where clause' })\n }\n if (!Object.hasOwn(table, key)) {\n throw new HTTPException(400, { message: 'invalid column in table' })\n }\n // biome-ignore lint/suspicious/noExplicitAny: table column access is runtime-guarded by hasOwn\n const col = (table as unknown as Record<string, any>)[key]\n conditions.push(eq(col, value))\n }\n\n if (conditions.length === 0) {\n return null\n }\n if (conditions.length === 1) {\n return conditions[0]\n }\n return and(...conditions)\n}\n\nfunction resolveRelationTarget(field: RelationDef): RelationTargetLike {\n return typeof field.target === 'function' ? field.target() : field.target\n}\n\nfunction getTargetTable(target: RelationTargetLike): SQLiteTableWithColumns<any> {\n if (Object.hasOwn(target, 'table')) {\n return (target as unknown as { table: SQLiteTableWithColumns<any> }).table\n }\n return buildTable(target.tableName, target.fields as Record<string, Field<any, any, any>>)\n}\n\nfunction validateWithOptions(\n fields: Record<string, Field<any, any, any>>,\n withOptions: Record<string, unknown>,\n): void {\n if (withOptions === null || typeof withOptions !== 'object' || Array.isArray(withOptions)) {\n throw new HTTPException(400, { message: 'invalid with option' })\n }\n\n for (const [key, value] of Object.entries(withOptions)) {\n if (value !== true) {\n throw new HTTPException(400, { message: 'nested with is not supported' })\n }\n if (!Object.hasOwn(fields, key) || fields[key]?.kind !== 'relation') {\n throw new HTTPException(400, { message: 'invalid relation in with option' })\n }\n }\n}\n\nconst relationCycleCache = new WeakMap<object, Error | null>()\n\nfunction assertNoRelationCycle(\n fields: Record<string, Field<any, any, any>>,\n rootName = 'root',\n): void {\n const cached = relationCycleCache.get(fields)\n if (cached !== undefined) {\n if (cached !== null) throw cached\n return\n }\n\n const visiting = new Set<object>()\n const visited = new Set<object>()\n\n const visit = (\n currentFields: Record<string, Field<any, any, any>>,\n path: readonly string[],\n ): Error | null => {\n if (visiting.has(currentFields)) {\n return new HTTPException(500, { message: 'relation cycle detected' })\n }\n if (visited.has(currentFields)) {\n return null\n }\n\n visiting.add(currentFields)\n for (const field of Object.values(currentFields)) {\n if (field.kind !== 'relation') continue\n\n const target = resolveRelationTarget(field as RelationDef)\n const targetFields = target.fields as Record<string, Field<any, any, any>>\n const error = visit(targetFields, [...path, target.tableName])\n if (error !== null) {\n return error\n }\n }\n visiting.delete(currentFields)\n visited.add(currentFields)\n return null\n }\n\n const error = visit(fields, [rootName])\n relationCycleCache.set(fields, error)\n if (error !== null) {\n throw error\n }\n}\n\nasync function loadRelations<\n Fields extends Record<string, Field<any, any, any>>,\n With extends WithOptions<Fields>,\n>(\n adapter: Adapter,\n _parentTable: SQLiteTableWithColumns<any>,\n parentFields: Fields,\n parentRows: RowType<Fields>[],\n withOptions: With,\n): Promise<WithResult<Fields, With>[]> {\n if (parentRows.length === 0) {\n return []\n }\n\n const rows = parentRows.map((row) => ({ ...row })) as WithResult<Fields, With>[]\n\n for (const relationKey of Object.keys(withOptions)) {\n const field = parentFields[relationKey]\n if (field?.kind !== 'relation') {\n throw new HTTPException(400, { message: 'invalid relation in with option' })\n }\n\n const relation = field as RelationDef\n const target = resolveRelationTarget(relation)\n const targetFields = target.fields as Record<string, Field<any, any, any>>\n const targetTable = getTargetTable(target)\n\n if (relation.relationKind === 'hasMany') {\n const parentPk = findPrimaryKey(parentFields)\n if (!parentPk) {\n throw new HTTPException(500, { message: 'model has no primary key' })\n }\n const parentPkKey = parentPk[0]\n const foreignKey = relation.foreignKey\n if (!Object.hasOwn(targetFields, foreignKey) || !Object.hasOwn(targetTable, foreignKey)) {\n throw new HTTPException(500, { message: 'invalid relation foreign key' })\n }\n\n const parentIds = Array.from(\n new Set(parentRows.map((row) => (row as Record<string, unknown>)[parentPkKey])),\n )\n const targetRows =\n parentIds.length === 0\n ? []\n : await adapter.drizzle\n .select()\n .from(targetTable)\n .where(\n inArray(\n (targetTable as unknown as Record<string, any>)[foreignKey],\n parentIds as any[],\n ),\n )\n\n const grouped = new Map<unknown, unknown[]>()\n for (const targetRow of targetRows as Record<string, unknown>[]) {\n const value = targetRow[foreignKey]\n const group = grouped.get(value)\n if (group === undefined) {\n grouped.set(value, [targetRow])\n } else {\n group.push(targetRow)\n }\n }\n\n for (const row of rows as Record<string, unknown>[]) {\n row[relationKey] = grouped.get(row[parentPkKey]) ?? []\n }\n } else {\n const foreignKey = relation.foreignKey\n if (!Object.hasOwn(parentFields, foreignKey) || !Object.hasOwn(_parentTable, foreignKey)) {\n throw new HTTPException(500, { message: 'invalid relation foreign key' })\n }\n\n const targetPk = findPrimaryKey(targetFields)\n if (!targetPk) {\n throw new HTTPException(500, { message: 'model has no primary key' })\n }\n const targetPkKey = targetPk[0]\n if (!Object.hasOwn(targetTable, targetPkKey)) {\n throw new HTTPException(500, { message: 'invalid relation primary key' })\n }\n\n const parentFkValues = Array.from(\n new Set(parentRows.map((row) => (row as Record<string, unknown>)[foreignKey])),\n )\n const targetRows =\n parentFkValues.length === 0\n ? []\n : await adapter.drizzle\n .select()\n .from(targetTable)\n .where(\n inArray(\n (targetTable as unknown as Record<string, any>)[targetPkKey],\n parentFkValues as any[],\n ),\n )\n\n const byPk = new Map<unknown, unknown>()\n for (const targetRow of targetRows as Record<string, unknown>[]) {\n byPk.set(targetRow[targetPkKey], targetRow)\n }\n\n for (const row of rows as Record<string, unknown>[]) {\n row[relationKey] = byPk.get(row[foreignKey]) ?? null\n }\n }\n }\n\n return rows\n}\n\n/**\n * Fetches multiple rows with limit, offset, optional ordering, and optional where clause.\n * @internal\n */\nexport async function findManyImpl<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n With extends WithOptions<Fields> | undefined = undefined,\n>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n fields: Fields,\n options: {\n limit: unknown\n offset?: unknown\n orderBy?: OrderBy<Fields>\n where?: Where<Fields> | SQL\n with?: With\n },\n): Promise<RowType<Fields>[] | WithResult<Fields, NonNullable<With>>[]> {\n const limit = guardLimit(options.limit)\n const offset = options.offset !== undefined ? guardOffset(options.offset) : 0\n\n // biome-ignore lint/suspicious/noExplicitAny: drizzle query builder type narrowing\n let query: any = adapter.drizzle.select().from(table).limit(limit).offset(offset)\n\n // Apply where clause\n if (options.where !== undefined) {\n if (options.where instanceof SQL) {\n query = query.where(options.where)\n } else {\n const whereClause = buildWhereClause(\n table,\n fields,\n options.where as Where<Record<string, any>>,\n )\n if (whereClause !== null) {\n query = query.where(whereClause)\n }\n }\n }\n\n // Apply ordering\n if (options.orderBy !== undefined) {\n const orderByList = Array.isArray(options.orderBy) ? options.orderBy : [options.orderBy]\n\n for (const orderByItem of orderByList) {\n let column: string\n let direction: 'asc' | 'desc' = 'asc'\n\n if (typeof orderByItem === 'string') {\n column = orderByItem\n } else if (\n typeof orderByItem === 'object' &&\n orderByItem !== null &&\n 'column' in orderByItem\n ) {\n column = orderByItem.column\n if (orderByItem.direction) {\n direction = orderByItem.direction\n }\n } else {\n throw new HTTPException(400, { message: 'invalid orderBy format' })\n }\n\n // Runtime guard against identifier injection (both fields and table to match where-clause guard)\n if (!Object.hasOwn(fields, column) || !Object.hasOwn(table, column)) {\n throw new HTTPException(400, { message: 'invalid field in orderBy' })\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: table column access is runtime-guarded by hasOwn\n const col = (table as unknown as Record<string, any>)[column]\n query = query.orderBy(direction === 'asc' ? asc(col) : desc(col))\n }\n }\n\n const rows = await query\n if (options.with !== undefined) {\n validateWithOptions(fields, options.with as Record<string, unknown>)\n assertNoRelationCycle(fields)\n return loadRelations(adapter, table, fields, rows, options.with as NonNullable<With>)\n }\n return rows\n}\n\n/**\n * Fetches all rows without a LIMIT clause.\n * For batch processing / admin tooling. Apply an app-level size guard when used in request handlers.\n * @internal\n */\nexport async function findAllImpl<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n fields: Fields,\n options?: FindAllOptions<Fields>,\n): Promise<RowType<Fields>[]> {\n const offset = options?.offset !== undefined ? guardOffset(options.offset) : undefined\n\n // SQLite requires LIMIT when OFFSET is used.\n // Number.MAX_SAFE_INTEGER is used as a sentinel \"no practical limit\" value when offset is specified.\n // biome-ignore lint/suspicious/noExplicitAny: drizzle query builder type narrowing\n let query: any =\n offset !== undefined\n ? adapter.drizzle.select().from(table).limit(Number.MAX_SAFE_INTEGER).offset(offset)\n : adapter.drizzle.select().from(table)\n\n // Apply where clause\n if (options?.where !== undefined) {\n if (options.where instanceof SQL) {\n query = query.where(options.where)\n } else {\n const whereClause = buildWhereClause(\n table,\n fields,\n options.where as Where<Record<string, any>>,\n )\n if (whereClause !== null) {\n query = query.where(whereClause)\n }\n }\n }\n\n // Apply ordering\n if (options?.orderBy !== undefined) {\n const orderByList = Array.isArray(options.orderBy) ? options.orderBy : [options.orderBy]\n\n for (const orderByItem of orderByList) {\n let column: string\n let direction: 'asc' | 'desc' = 'asc'\n\n if (typeof orderByItem === 'string') {\n column = orderByItem\n } else if (\n typeof orderByItem === 'object' &&\n orderByItem !== null &&\n 'column' in orderByItem\n ) {\n column = orderByItem.column\n if (orderByItem.direction) {\n direction = orderByItem.direction\n }\n } else {\n throw new HTTPException(400, { message: 'invalid orderBy format' })\n }\n\n // Runtime guard against identifier injection (both fields and table to match where-clause guard)\n if (!Object.hasOwn(fields, column) || !Object.hasOwn(table, column)) {\n throw new HTTPException(400, { message: 'invalid field in orderBy' })\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: table column access is runtime-guarded by hasOwn\n const col = (table as unknown as Record<string, any>)[column]\n query = query.orderBy(direction === 'asc' ? asc(col) : desc(col))\n }\n }\n\n const rows = await query\n return rows\n}\n\n/**\n * Fetches a single row by primary key or where clause.\n * @internal\n */\nexport async function findOneImpl<Fields extends Record<string, Field<any, any, any>>>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n fields: Fields,\n idOrWhere: IdOrWhere<Fields>,\n options?: FindOneOptions<Fields>,\n): Promise<RowType<Fields> | null> {\n let where: Where<Fields> | null = null\n\n if (typeof idOrWhere === 'string' || typeof idOrWhere === 'number') {\n // PK mode\n const pk = findPrimaryKey(fields)\n if (!pk) {\n throw new HTTPException(500, { message: 'model has no primary key' })\n }\n where = { [pk[0]]: idOrWhere } as Where<Fields>\n } else {\n where = idOrWhere as Where<Fields>\n }\n\n const whereClause = buildWhereClause(table, fields, where)\n if (!whereClause) {\n throw new HTTPException(400, { message: 'where clause must not be empty' })\n }\n\n if (options?.with !== undefined) {\n validateWithOptions(fields, options.with as Record<string, unknown>)\n assertNoRelationCycle(fields)\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: drizzle query type\n const rows = await (adapter.drizzle.select().from(table).where(whereClause).limit(1) as any)\n if (rows.length === 0) {\n return null\n }\n if (options?.with !== undefined) {\n const withRows = await loadRelations(adapter, table, fields, [rows[0]], options.with)\n return withRows[0] ?? null\n }\n return rows[0]\n}\n\n/**\n * Creates a new row and returns the created record.\n * @internal\n */\nexport async function createImpl<Fields extends Record<string, Field<any, any, any>>>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n data: CreateInput<Fields>,\n): Promise<RowType<Fields>> {\n const rows = await (adapter.drizzle\n .insert(table)\n .values(data as any)\n .returning() as any)\n return rows[0]\n}\n\n/**\n * Updates rows matching the given id or where clause.\n * @internal\n */\nexport async function updateImpl<Fields extends Record<string, Field<any, any, any>>>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n fields: Fields,\n idOrWhere: IdOrWhere<Fields>,\n data: Partial<RowType<Fields>>,\n): Promise<RowType<Fields> | null> {\n let where: Where<Fields> | null = null\n\n if (typeof idOrWhere === 'string' || typeof idOrWhere === 'number') {\n // PK mode\n const pk = findPrimaryKey(fields)\n if (!pk) {\n throw new HTTPException(500, { message: 'model has no primary key' })\n }\n where = { [pk[0]]: idOrWhere } as Where<Fields>\n } else {\n where = idOrWhere as Where<Fields>\n }\n\n const whereClause = buildWhereClause(table, fields, where)\n if (!whereClause) {\n throw new HTTPException(400, { message: 'where clause must not be empty' })\n }\n\n const rows = await (adapter.drizzle\n .update(table)\n .set(data as any)\n .where(whereClause)\n .returning() as any)\n return rows.length > 0 ? rows[0] : null\n}\n\n/**\n * Deletes rows matching the given id or where clause.\n * @internal\n */\nexport async function deleteImpl<Fields extends Record<string, Field<any, any, any>>>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n fields: Fields,\n idOrWhere: IdOrWhere<Fields>,\n): Promise<{ readonly deleted: number }> {\n let where: Where<Fields> | null = null\n\n if (typeof idOrWhere === 'string' || typeof idOrWhere === 'number') {\n // PK mode\n const pk = findPrimaryKey(fields)\n if (!pk) {\n throw new HTTPException(500, { message: 'model has no primary key' })\n }\n where = { [pk[0]]: idOrWhere } as Where<Fields>\n } else {\n where = idOrWhere as Where<Fields>\n }\n\n const whereClause = buildWhereClause(table, fields, where)\n if (!whereClause) {\n throw new HTTPException(400, { message: 'where clause must not be empty' })\n }\n\n const result = await adapter.drizzle.delete(table).where(whereClause).returning()\n return { deleted: result.length }\n}\n","import { type Hook, zValidator } from '@hono/zod-validator'\nimport type { Env, ValidationTargets } from 'hono'\nimport type { z } from 'zod'\nimport type { Adapter } from '../adapter/types'\nimport type { Field } from '../field/types'\nimport { toOpenAPIComponent, toOpenAPISchema } from '../openapi/generate'\nimport type { OpenAPIUsage } from '../openapi/types'\nimport { createImpl, deleteImpl, findAllImpl, findManyImpl, findOneImpl, updateImpl } from './crud'\nimport { applySchemaOptions, buildBaseObject, derivePolicyOptions } from './schema'\nimport { buildTable } from './table'\nimport type {\n Apply,\n CreateInput,\n FieldsToZodShape,\n FindAllOptions,\n FindManyOptions,\n FindOneOptions,\n IdOrWhere,\n Model,\n NonRelationKeys,\n RowType,\n SchemaOptions,\n} from './types'\nimport { buildFieldAccessor } from './types'\n\n/**\n * Creates a Model instance from a tableName and fields definition.\n * The model supports deriving Zod schemas, Hono validators, and CRUD operations.\n *\n * @example\n * const User = defineModel('users', {\n * id: t.uuid().primary(),\n * name: t.string(),\n * email: t.string().email(),\n * passwordHash: t.string(),\n * })\n *\n * const CreateSchema = User.schema({ omit: ['passwordHash'] })\n * const users = await User.findMany(adapter, { limit: 20 })\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field constraint\nexport function defineModel<Fields extends Record<string, Field<any, any, any>>>(\n tableName: string,\n fields: Fields,\n): Model<Fields> {\n const table = buildTable(tableName, fields)\n const accessor = buildFieldAccessor(fields)\n\n return {\n fields,\n tableName,\n table,\n\n schema<Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined>(\n opts?: Opts,\n ): Apply<FieldsToZodShape<Fields>, Opts> {\n const baseSchema = buildBaseObject(fields)\n const schema = applySchemaOptions(baseSchema, opts, accessor)\n // biome-ignore lint/suspicious/noExplicitAny: Zod .pick()/.omit() return type narrowing requires cast at boundary\n return schema as any\n },\n\n validator(\n target: keyof ValidationTargets,\n optsOrPreset?: 'create' | 'update' | SchemaOptions<NonRelationKeys<Fields> & string>,\n // biome-ignore lint/suspicious/noExplicitAny: Hook<T> is contravariant in T; any is required to bridge overload implementations\n hook?: Hook<any, Env, string, keyof ValidationTargets>,\n ) {\n let schema: z.ZodTypeAny\n if (optsOrPreset === 'create' || optsOrPreset === 'update') {\n schema = this.inputSchema(optsOrPreset)\n } else {\n schema = this.schema(optsOrPreset as SchemaOptions<NonRelationKeys<Fields> & string>)\n }\n // biome-ignore lint/suspicious/noExplicitAny: zValidator return type cast required at overload boundary\n return zValidator(target, schema, hook) as any\n },\n\n inputSchema(\n usage: 'create' | 'update',\n opts?: SchemaOptions<NonRelationKeys<Fields> & string>,\n // biome-ignore lint/suspicious/noExplicitAny: precise return type is enforced by Model<Fields> overload signatures\n ): any {\n const merged = derivePolicyOptions(\n fields,\n usage === 'create' ? 'input-create' : 'input-update',\n opts,\n accessor,\n )\n const baseSchema = buildBaseObject(fields)\n return applySchemaOptions(baseSchema, merged)\n },\n\n outputSchema(\n opts?: SchemaOptions<NonRelationKeys<Fields> & string>,\n // biome-ignore lint/suspicious/noExplicitAny: precise return type is enforced by Model<Fields> overload signatures\n ): any {\n const merged = derivePolicyOptions(fields, 'output', opts, accessor)\n const baseSchema = buildBaseObject(fields)\n return applySchemaOptions(baseSchema, merged)\n },\n\n toResponse(row: RowType<Fields>): unknown {\n return this.outputSchema().parse(row)\n },\n\n toResponseMany(rows: readonly RowType<Fields>[]): unknown[] {\n const schema = this.outputSchema()\n return rows.map((row) => schema.parse(row))\n },\n\n toOpenAPIComponent() {\n return toOpenAPIComponent(fields)\n },\n\n toOpenAPISchema(usage: OpenAPIUsage) {\n return toOpenAPISchema(fields, usage)\n },\n\n findMany: ((adapter: Adapter, options: FindManyOptions<Fields>) =>\n findManyImpl(adapter, table, fields, options)) as Model<Fields>['findMany'],\n\n findAll(adapter: Adapter, options?: FindAllOptions<Fields>): Promise<RowType<Fields>[]> {\n return findAllImpl(adapter, table, fields, options)\n },\n\n findOne: ((adapter: Adapter, idOrWhere: IdOrWhere<Fields>, options?: FindOneOptions<Fields>) =>\n findOneImpl(adapter, table, fields, idOrWhere, options)) as Model<Fields>['findOne'],\n\n create(adapter: Adapter, data: CreateInput<Fields>): Promise<RowType<Fields>> {\n return createImpl(adapter, table, data)\n },\n\n update(\n adapter: Adapter,\n idOrWhere: IdOrWhere<Fields>,\n data: Partial<RowType<Fields>>,\n ): Promise<RowType<Fields> | null> {\n return updateImpl(adapter, table, fields, idOrWhere, data)\n },\n\n delete(adapter: Adapter, idOrWhere: IdOrWhere<Fields>): Promise<{ readonly deleted: number }> {\n return deleteImpl(adapter, table, fields, idOrWhere)\n },\n }\n}\n","import type { OpenAPIDocument, OpenAPIRouteMetadata, OpenAPISpecOptions } from './types'\n\nfunction honoPathToOpenAPI(path: string): string {\n return path.replace(/:([^/]+)/g, '{$1}')\n}\n\nexport function buildOpenAPIDocument(\n routes: readonly OpenAPIRouteMetadata[],\n options: OpenAPISpecOptions,\n): OpenAPIDocument {\n const paths: Record<string, Record<string, unknown>> = {}\n\n for (const route of routes) {\n const openAPIPath = honoPathToOpenAPI(route.path)\n if (!paths[openAPIPath]) {\n paths[openAPIPath] = {}\n }\n\n const operation: Record<string, unknown> = {}\n if (route.operationId) operation.operationId = route.operationId\n if (route.summary) operation.summary = route.summary\n if (route.description) operation.description = route.description\n if (route.tags) operation.tags = route.tags\n\n const parameters: unknown[] = []\n const pathParams = [...route.path.matchAll(/:([^/]+)/g)].map((m) => m[1])\n for (const param of pathParams) {\n const alreadyDefined = route.params?.some((p) => p.name === param && p.in === 'path')\n if (!alreadyDefined) {\n parameters.push({ name: param, in: 'path', required: true, schema: { type: 'string' } })\n }\n }\n if (route.params) {\n parameters.push(...route.params)\n }\n if (parameters.length > 0) operation.parameters = parameters\n\n if (route.requestBody) operation.requestBody = route.requestBody\n operation.responses = route.responses\n\n paths[openAPIPath][route.method] = operation\n }\n\n const doc: OpenAPIDocument = {\n openapi: '3.1.0',\n info: options.info,\n ...(options.servers ? { servers: options.servers } : {}),\n paths,\n }\n\n return doc\n}\n","import type { MiddlewareHandler } from 'hono'\n\nexport interface SwaggerUIOptions {\n readonly url: string\n readonly title?: string\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n}\n\nexport function swaggerUI(options: SwaggerUIOptions): MiddlewareHandler {\n const title = escapeHtml(options.title ?? 'API Documentation')\n const html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <title>${title}</title>\n <link rel=\"stylesheet\" href=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui.css\" />\n</head>\n<body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js\"></script>\n <script>\n SwaggerUIBundle({\n url: ${JSON.stringify(options.url)},\n dom_id: '#swagger-ui',\n presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],\n layout: 'BaseLayout',\n })\n </script>\n</body>\n</html>`\n\n return async (c) => {\n return c.html(html)\n }\n}\n","import { Hono } from 'hono'\nimport type { BlankEnv, Env, H } from 'hono/types'\nimport type { Adapter } from '../adapter/types'\nimport type { Field } from '../field/types'\nimport { defineModel } from '../model/define'\nimport type { IdOrWhere } from '../model/types'\nimport { buildOpenAPIDocument } from '../openapi/route'\nimport type { HttpMethod, OpenAPIRouteMetadata } from '../openapi/types'\nimport type { Nanoka, NanokaModel, RouteOpenAPIOption } from './types'\n\n/**\n * Creates a Nanoka application instance with the given database adapter.\n *\n * @param adapter - The database adapter (e.g., d1Adapter(env.DB))\n * @returns A Nanoka application (Hono extended with model(), db, and batch)\n *\n * @example\n * export default {\n * fetch(req: Request, env: Env, ctx: ExecutionContext) {\n * const app = nanoka(d1Adapter(env.DB))\n * const User = app.model('users', { id, name, email, passwordHash })\n * app.get('/users', async (c) => {\n * const users = await User.findMany({ limit: 20 })\n * return c.json(users)\n * })\n * return app.fetch(req, env, ctx)\n * }\n * }\n */\nexport function nanoka<E extends Env = BlankEnv>(adapter: Adapter): Nanoka<E> {\n const app = new Hono<E>() as Nanoka<E>\n const openapiRoutes: OpenAPIRouteMetadata[] = []\n\n Object.defineProperty(app, 'db', {\n get: () => adapter.drizzle,\n enumerable: true,\n })\n\n app.batch = ((queries: Parameters<Adapter['batch']>[0]) =>\n adapter.batch(queries)) as unknown as Adapter['batch']\n\n app.openapi = (metadata: OpenAPIRouteMetadata) => {\n openapiRoutes.push(metadata)\n return app\n }\n\n app.generateOpenAPISpec = (options) => buildOpenAPIDocument(openapiRoutes, options)\n\n function wrapWithOpenAPI(method: HttpMethod) {\n // biome-ignore lint/suspicious/noExplicitAny: original Hono method is typed as HandlerInterface which needs any at call site\n const original = (app as any)[method].bind(app)\n // biome-ignore lint/suspicious/noExplicitAny: overload bridge — type safety is provided by the Nanoka interface overload\n ;(app as any)[method] = (path: string, second: RouteOpenAPIOption | H, ...rest: H[]) => {\n if (\n second !== null &&\n typeof second === 'object' &&\n !Array.isArray(second) &&\n typeof (second as RouteOpenAPIOption).openapi === 'object'\n ) {\n const { openapi } = second as RouteOpenAPIOption\n openapiRoutes.push({ ...openapi, path, method })\n return original(path, ...rest)\n }\n return original(path, second, ...rest)\n }\n }\n\n for (const method of ['get', 'post', 'put', 'patch', 'delete'] as const) {\n wrapWithOpenAPI(method)\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field generic constraint\n app.model = function model<Fields extends Record<string, Field<any, any, any>>>(\n name: string,\n fields: Fields,\n ): NanokaModel<Fields> {\n const inner = defineModel(name, fields)\n\n return {\n fields: inner.fields,\n tableName: inner.tableName,\n table: inner.table,\n\n schema: (opts) => inner.schema(opts),\n\n validator: (\n ...args: [\n keyof import('hono').ValidationTargets,\n (\n | 'create'\n | 'update'\n | import('../model/types').SchemaOptions<\n import('../model/types').NonRelationKeys<Fields> & string\n >\n )?,\n import('@hono/zod-validator').Hook<\n // biome-ignore lint/suspicious/noExplicitAny: Hook<T> is contravariant in T; any is required to bridge overload implementations\n any,\n import('hono').Env,\n string,\n keyof import('hono').ValidationTargets\n >?,\n ]\n ) => {\n // `NanokaModel` interface の overload 定義 (router/types.ts) で type safety は担保する。\n // 実装は inner.validator に委譲するだけで、型は interface 側の overload に従う。\n // biome-ignore lint/suspicious/noExplicitAny: NanokaModel interface overloads provide type safety\n return (inner.validator as (...a: typeof args) => any)(...args)\n },\n\n inputSchema: (usage, opts) => inner.inputSchema(usage, opts),\n\n outputSchema: (opts) => inner.outputSchema(opts),\n\n toResponse: (row) => inner.toResponse(row),\n\n toResponseMany: (rows) => inner.toResponseMany(rows),\n\n toOpenAPIComponent: () => inner.toOpenAPIComponent(),\n\n toOpenAPISchema: (usage) => inner.toOpenAPISchema(usage),\n\n findMany: ((options: Parameters<NanokaModel<Fields>['findMany']>[0]) =>\n inner.findMany(adapter, options as any)) as NanokaModel<Fields>['findMany'],\n\n findAll: (options) => inner.findAll(adapter, options),\n\n findOne: ((\n idOrWhere: IdOrWhere<Fields>,\n options?: import('../model/types').FindOneOptions<Fields>,\n ) => inner.findOne(adapter, idOrWhere, options as any)) as NanokaModel<Fields>['findOne'],\n\n create: (data) => inner.create(adapter, data),\n\n update: (idOrWhere, data) => inner.update(adapter, idOrWhere, data),\n\n delete: (idOrWhere) => inner.delete(adapter, idOrWhere),\n }\n }\n\n return app\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapter/d1.ts","../src/model/types.ts","../src/model/schema.ts","../src/openapi/generate.ts","../src/model/table.ts","../src/model/crud.ts","../src/model/define.ts","../src/openapi/route.ts","../src/openapi/swagger-ui.ts","../src/router/nanoka.ts"],"names":["partial","combinedOmit"],"mappings":";;;;;;;;;AASO,SAAS,UACd,EAAA,EACkB;AAUlB,EAAA,MAAM,EAAA,GAAK,QAAQ,EAAE,CAAA;AAErB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,EAAA;AAAA,IACT,KAAA,EAAO,CAAC,OAAA,KAAY,EAAA,CAAG,MAAM,OAAO;AAAA,GACtC;AACF;;;AC+PO,SAAS,uBAAA,CACd,KACA,QAAA,EAC0B;AAC1B,EAAA,IAAI,GAAA,KAAQ,QAAW,OAAO,MAAA;AAC9B,EAAA,IAAI,OAAO,GAAA,KAAQ,UAAA,EAAY,OAAO,IAAI,QAAQ,CAAA;AAClD,EAAA,OAAO,GAAA;AACT;AASO,SAAS,mBACd,MAAA,EACgD;AAChD,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AAC/C,IAAA,IAAI,KAAA,CAAM,SAAS,UAAA,EAAY;AAC/B,IAAA,GAAA,CAAI,CAAC,CAAA,GAAI,CAAA;AAAA,EACX;AACA,EAAA,OAAO,MAAA,CAAO,OAAO,GAAG,CAAA;AAC1B;;;ACzSA,SAAS,kBAEP,MAAA,EACU;AACV,EAAA,MAAM,OAAiB,EAAC;AACxB,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AACjD,IAAA,IAAI,KAAA,CAAM,SAAA,CAAU,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A,EACA,OAAA,KACG,MAAM,OAAA,CAAQ,OAAA,EAAS,WAAW,OAAc,CAAA,CAAA;AAAA,MAErD,QAAQ,CAAC,IAAA,KAAS,KAAA,CAAM,MAAA,CAAO,SAAS,IAAI,CAAA;AAAA,MAE5C,MAAA,EAAQ,CAAC,SAAA,EAAW,IAAA,KAAS,MAAM,MAAA,CAAO,OAAA,EAAS,WAAW,IAAI,CAAA;AAAA,MAElE,QAAQ,CAAC,SAAA,KAAc,KAAA,CAAM,MAAA,CAAO,SAAS,SAAS;AAAA,KACxD;AAAA,EACF,CAAA;AAEA,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["import type { D1Database } from '@cloudflare/workers-types'\nimport { drizzle } from 'drizzle-orm/d1'\nimport type { Adapter } from './types'\n\n/**\n * D1-specific adapter factory. Wraps Cloudflare D1 binding in the generic\n * Adapter abstraction, enabling the core query path and router to remain\n * implementation-agnostic.\n */\nexport function d1Adapter<TSchema extends Record<string, unknown> = Record<string, never>>(\n d1: D1Database,\n): Adapter<TSchema> {\n // drizzle-orm/d1's drizzle() returns DrizzleD1Database which embeds D1-specific\n // result types. We cast to BaseSQLiteDatabase via the Adapter interface to keep\n // the D1 dependency local to this file (see CLAUDE.md rule #3). Consumers receive\n // the typed Adapter interface, so this `any` is intentionally local.\n //\n // Note: drizzle-orm/d1 internally stores the D1 binding in db.$client. When\n // handling multiple D1 bindings, call d1Adapter() fresh for each binding rather\n // than caching the return value across binding switches.\n // biome-ignore lint/suspicious/noExplicitAny: intentional - Drizzle returns complex union type\n const db = drizzle(d1) as any\n\n return {\n drizzle: db,\n batch: (queries) => db.batch(queries),\n }\n}\n","import type { Hook } from '@hono/zod-validator'\nimport type { SQL } from 'drizzle-orm'\nimport type { AnySQLiteColumn, SQLiteTableWithColumns } from 'drizzle-orm/sqlite-core'\nimport type { Env, MiddlewareHandler, ValidationTargets } from 'hono'\nimport type { z } from 'zod'\nimport type { Adapter } from '../adapter/types'\nimport type { Field, FieldPolicy, InferFieldType, RelationDef } from '../field/types'\nimport type { OpenAPIModelComponent, OpenAPISchemaObject, OpenAPIUsage } from '../openapi/types'\n\n/**\n * @internal\n * Extracts keys of non-relation fields from a Fields record.\n * Relation fields (kind: 'relation') are excluded from DB column types, RowType, etc.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\nexport type NonRelationKeys<Fields extends Record<string, Field<any, any, any>>> = {\n [K in keyof Fields]: Fields[K] extends { kind: 'relation' } ? never : K\n}[keyof Fields]\n\n/**\n * @internal\n * Extracts keys of relation fields from a Fields record.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\nexport type RelationKeys<Fields extends Record<string, Field<any, any, any>>> = {\n [K in keyof Fields]: Fields[K] extends { kind: 'relation' } ? K : never\n}[keyof Fields]\n\nexport type RelationTargetFields<Target> = Target extends () => infer Resolved\n ? RelationTargetFields<Resolved>\n : Target extends { fields: infer TargetFields }\n ? TargetFields\n : never\n\nexport type RelationResult<F> =\n F extends RelationDef<infer Target, string>\n ? RelationTargetFields<Target> extends Record<string, Field<any, any, any>>\n ? F['relationKind'] extends 'hasMany'\n ? RowType<RelationTargetFields<Target>>[]\n : RowType<RelationTargetFields<Target>> | null\n : never\n : never\n\nexport type WithOptions<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = {\n readonly [K in RelationKeys<Fields>]?: true\n}\n\nexport type WithResult<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n With,\n> = RowType<Fields> & { readonly [K in keyof With]: RelationResult<Fields[K & keyof Fields]> }\n\n/**\n * Options for findMany query.\n * `limit` is required (no default).\n * `offset` defaults to 0 if omitted.\n * `orderBy` is optional for column ordering.\n * `where` accepts either an equality object or a Drizzle SQL expression.\n */\nexport interface FindManyOptions<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n With extends WithOptions<Fields> | undefined = undefined,\n> {\n readonly limit: number\n readonly offset?: number\n readonly orderBy?: OrderBy<Fields>\n readonly where?: Where<Fields> | SQL\n readonly with?: With\n}\n\nexport interface FindOneOptions<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n With extends WithOptions<Fields> | undefined = undefined,\n> {\n readonly with?: With\n}\n\n/**\n * Options for findAll query.\n * No `limit` — issues no LIMIT clause. For batch processing / admin tooling.\n * Apply an app-level size guard when used in request handlers.\n */\nexport interface FindAllOptions<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> {\n readonly offset?: number\n readonly orderBy?: OrderBy<Fields>\n readonly where?: Where<Fields> | SQL\n}\n\n/**\n * Order-by specification: single field, or field with direction, or array of multiple.\n */\nexport type OrderBy<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> =\n | (NonRelationKeys<Fields> & string)\n | { readonly column: NonRelationKeys<Fields> & string; readonly direction?: 'asc' | 'desc' }\n | ReadonlyArray<\n | (NonRelationKeys<Fields> & string)\n | { readonly column: NonRelationKeys<Fields> & string; readonly direction?: 'asc' | 'desc' }\n >\n\n/**\n * Where clause object: each key is a field name, each value is the desired equality.\n */\nexport type Where<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = {\n readonly [K in NonRelationKeys<Fields>]?: InferFieldType<Fields[K]>\n}\n\n/**\n * Identifier or Where clause: can be a primary key value or a Where object.\n */\nexport type IdOrWhere<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = string | number | Where<Fields>\n\n/**\n * Row type: full record type from fields, excluding relation fields.\n */\nexport type RowType<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = {\n [K in NonRelationKeys<Fields>]: InferFieldType<Fields[K]>\n}\n\n/**\n * Drizzle table type with columns typed to match the model's Fields (excluding relation fields).\n * Allows type-safe column access via Model.table.fieldName.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\nexport type ModelTable<Fields extends Record<string, Field<any, any, any>>> =\n SQLiteTableWithColumns<{\n name: string\n schema: undefined\n columns: { [K in NonRelationKeys<Fields>]: AnySQLiteColumn }\n dialect: 'sqlite'\n }>\n\n/**\n * @internal\n * Extracts the policy from a Field's modifiers.\n *\n * Uses `Field<any, { policy: infer P }, any>` rather than a two-step\n * `infer M` + `M extends { policy: infer P }` pattern.\n * The two-step pattern is broken when TypeScript widens `M` to the constraint\n * `FieldModifiers` (which has `policy?: FieldPolicy` as optional), causing\n * `M extends { policy: infer P }` to be true for ALL fields regardless of their\n * actual policy value. Directly matching `{ policy: infer P }` avoids this.\n */\ntype PolicyOf<F> =\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n F extends Field<any, { policy: infer P extends FieldPolicy }, any> ? P : never\n\n/**\n * @internal\n * Computes which field keys should be omitted based on policy and usage.\n * Mirrors the runtime logic in derivePolicyOptions() in schema.ts.\n *\n * NOTE: `[PolicyOf<Fields[K]>] extends [never]` (non-distributive form) is used to\n * short-circuit fields with no policy to `never` (do not omit). Without this guard,\n * `never extends 'serverOnly'` evaluates to `true` (vacuously), causing every field\n * without a policy to be incorrectly included in the omit set.\n */\nexport type PolicyOmitKeys<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n Usage extends 'input-create' | 'input-update' | 'output',\n> = {\n [K in keyof Fields]: [PolicyOf<Fields[K]>] extends [never]\n ? never\n : PolicyOf<Fields[K]> extends 'serverOnly'\n ? K\n : Usage extends 'output'\n ? PolicyOf<Fields[K]> extends 'writeOnly'\n ? K\n : never\n : Usage extends 'input-create' | 'input-update'\n ? PolicyOf<Fields[K]> extends 'readOnly'\n ? K\n : never\n : never\n}[keyof Fields]\n\n/**\n * @internal\n * Computes which field keys have the serverOnly policy.\n * serverOnly fields are completely excluded from CreateInput\n * (cannot be passed even from library internals — they are server-side only).\n *\n * Uses `[PolicyOf<Fields[K]>] extends [never]` (non-distributive form) to short-circuit\n * fields with no policy to `never`. Without this guard, `never extends 'serverOnly'`\n * evaluates to `true` (vacuously), causing every field without a policy to be included.\n */\ntype ServerOnlyKeys<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = {\n [K in keyof Fields]: [PolicyOf<Fields[K]>] extends [never]\n ? never\n : PolicyOf<Fields[K]> extends 'serverOnly'\n ? K\n : never\n}[keyof Fields]\n\n/**\n * @internal\n * Determines if a field is required for create input.\n * A field is optional if it has a default, is optional, or is readOnly.\n *\n * Uses direct shape matching (`Field<any, { hasDefault: true }, any>`) to avoid\n * the TypeScript infer-widening issue where `infer M` resolves to `FieldModifiers`\n * (the constraint bound) instead of the concrete Mods type, causing `M extends\n * { policy: 'readOnly' }` to be false even for readOnly fields.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\ntype IsRequired<F extends Field<any, any, any>> =\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n F extends Field<any, { hasDefault: true }, any>\n ? false\n : // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n F extends Field<any, { optional: true }, any>\n ? false\n : // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n F extends Field<any, { policy: 'readOnly' }, any>\n ? false\n : true\n\n/**\n * Create input with precise types:\n * - `readOnly` fields are optional (library internals can pass them; API callers\n * are excluded via inputSchema — but CreateInput itself keeps them as optional\n * so handlers can supply generated values like `id` or `createdAt`)\n * - fields with `default` are optional\n * - fields marked `optional` are optional\n * - all other fields are required\n * - `serverOnly` fields are completely excluded (cannot be passed even internally)\n * - `writeOnly` fields are included as required (they are input fields by design)\n * - relation fields are completely excluded (no DB column)\n */\nexport type CreateInput<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n> = {\n [K in NonRelationKeys<Fields> as IsRequired<Fields[K]> extends true\n ? K extends ServerOnlyKeys<Fields>\n ? never\n : K\n : never]: InferFieldType<Fields[K]>\n} & {\n [K in NonRelationKeys<Fields> as IsRequired<Fields[K]> extends true\n ? never\n : K extends ServerOnlyKeys<Fields>\n ? never\n : K]?: InferFieldType<Fields[K]>\n}\n\nexport type FieldAccessor<K extends string> = { readonly [Key in K]: Key }\n\nexport interface SchemaOptions<K extends string = string> {\n readonly pick?: readonly K[] | ((f: FieldAccessor<K>) => readonly K[])\n readonly omit?: readonly K[] | ((f: FieldAccessor<K>) => readonly K[])\n readonly partial?: boolean\n}\n\n/**\n * @internal\n * Resolves pick/omit option to string array using the accessor when it's a function.\n */\nexport function resolveSchemaOptionKeys<K extends string>(\n opt: readonly K[] | ((f: FieldAccessor<K>) => readonly K[]) | undefined,\n accessor: FieldAccessor<K>,\n): readonly K[] | undefined {\n if (opt === undefined) return undefined\n if (typeof opt === 'function') return opt(accessor)\n return opt\n}\n\n/**\n * @internal\n * Builds a frozen field accessor object for use in schema/validator options.\n * Relation fields are excluded so that `omit: f => [f.posts]` is a type error.\n * Each non-relation key maps to itself, providing typo detection at type level.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\nexport function buildFieldAccessor<Fields extends Record<string, Field<any, any, any>>>(\n fields: Fields,\n): { readonly [K in NonRelationKeys<Fields>]: K } {\n const acc: Record<string, string> = {}\n for (const [k, field] of Object.entries(fields)) {\n if (field.kind === 'relation') continue\n acc[k] = k\n }\n return Object.freeze(acc) as { readonly [K in NonRelationKeys<Fields>]: K }\n}\n\n/**\n * @internal\n * Extracts a Zod shape from fields for the Apply type.\n * Only non-relation fields are included (relation fields have zodBase: ZodNever\n * and are skipped at runtime in buildBaseObject).\n * Indexed access ensures concrete Zod types are preserved (not `any`).\n */\nexport type FieldsToZodShape<\n Fields extends Record<\n string,\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Field<any, any, any>\n >,\n> = {\n [K in NonRelationKeys<Fields>]: Fields[K]['zodBase']\n}\n\n/**\n * @internal\n * Utility to narrow array literal types to union of strings.\n */\ntype ArrayKeys<A> = A extends readonly (infer U)[] ? U : never\n\n/**\n * @internal\n * Resolves pick/omit option type to the array type.\n * Handles both array form and accessor function form.\n */\ntype ResolveOptKeys<Opt> = Opt extends readonly string[]\n ? Opt\n : Opt extends (f: FieldAccessor<infer _K>) => readonly (infer R)[]\n ? readonly R[]\n : never\n\n/**\n * @internal\n * Apply pick transformation to a shape.\n */\ntype ApplyPickToShape<Shape extends z.ZodRawShape, PickOpt> =\n ResolveOptKeys<PickOpt> extends readonly string[]\n ? Pick<Shape, ArrayKeys<ResolveOptKeys<PickOpt>> & keyof Shape>\n : Shape\n\n/**\n * @internal\n * Apply omit transformation to a shape.\n */\ntype ApplyOmitToShape<Shape extends z.ZodRawShape, OmitOpt> =\n ResolveOptKeys<OmitOpt> extends readonly string[]\n ? Omit<Shape, ArrayKeys<ResolveOptKeys<OmitOpt>> & keyof Shape>\n : Shape\n\n/**\n * @internal\n * Apply partial transformation to a shape.\n */\ntype ApplyPartialToShape<Shape extends z.ZodRawShape> = {\n [K in keyof Shape]: z.ZodOptional<Shape[K]>\n}\n\n/**\n * @internal\n * Checks if an option value (array or function) is present (i.e. not undefined and not never).\n * Uses distributive conditional to handle union types like `T | undefined`.\n */\ntype HasOpt<Opt> = undefined extends Opt ? false : [Opt] extends [never] ? false : true\n\n/**\n * @internal\n * Apply pick/omit/partial transformations to a Zod raw shape.\n * Order: pick → omit → partial\n * Handles both array form and accessor function form for pick/omit.\n */\ntype ApplyShape<\n Shape extends z.ZodRawShape,\n Opts extends SchemaOptions | undefined,\n> = Opts extends SchemaOptions\n ? HasOpt<Opts['pick']> extends true\n ? HasOpt<Opts['omit']> extends true\n ? Opts extends { partial: true }\n ? ApplyPartialToShape<ApplyOmitToShape<ApplyPickToShape<Shape, Opts['pick']>, Opts['omit']>>\n : ApplyOmitToShape<ApplyPickToShape<Shape, Opts['pick']>, Opts['omit']>\n : Opts extends { partial: true }\n ? ApplyPartialToShape<ApplyPickToShape<Shape, Opts['pick']>>\n : ApplyPickToShape<Shape, Opts['pick']>\n : HasOpt<Opts['omit']> extends true\n ? Opts extends { partial: true }\n ? ApplyPartialToShape<ApplyOmitToShape<Shape, Opts['omit']>>\n : ApplyOmitToShape<Shape, Opts['omit']>\n : Opts extends { partial: true }\n ? ApplyPartialToShape<Shape>\n : Shape\n : Shape\n\n/**\n * @internal\n * Returns the correct Zod object type after applying pick/omit/partial transformations.\n */\nexport type Apply<\n Shape extends z.ZodRawShape,\n Opts extends SchemaOptions | undefined,\n> = z.ZodObject<ApplyShape<Shape, Opts>>\n\n/**\n * @internal\n * Apply pick transformation to a TS record type.\n */\ntype ApplyPickToRecord<R, PickOpt> =\n ResolveOptKeys<PickOpt> extends readonly string[]\n ? Pick<R, ArrayKeys<ResolveOptKeys<PickOpt>> & keyof R>\n : R\n\n/**\n * @internal\n * Apply omit transformation to a TS record type.\n */\ntype ApplyOmitToRecord<R, OmitOpt> =\n ResolveOptKeys<OmitOpt> extends readonly string[]\n ? Omit<R, ArrayKeys<ResolveOptKeys<OmitOpt>> & keyof R>\n : R\n\n/**\n * @internal\n * Apply pick/omit/partial transformations to a TypeScript record type.\n * Mirrors ApplyShape but operates on TS types directly, not Zod shapes.\n * Used for Zod v3/v4 compatible middleware input/output type computation.\n */\ntype ApplyToRecord<R, Opts extends SchemaOptions | undefined> = Opts extends SchemaOptions\n ? HasOpt<Opts['pick']> extends true\n ? HasOpt<Opts['omit']> extends true\n ? Opts extends { partial: true }\n ? Partial<ApplyOmitToRecord<ApplyPickToRecord<R, Opts['pick']>, Opts['omit']>>\n : ApplyOmitToRecord<ApplyPickToRecord<R, Opts['pick']>, Opts['omit']>\n : Opts extends { partial: true }\n ? Partial<ApplyPickToRecord<R, Opts['pick']>>\n : ApplyPickToRecord<R, Opts['pick']>\n : HasOpt<Opts['omit']> extends true\n ? Opts extends { partial: true }\n ? Partial<ApplyOmitToRecord<R, Opts['omit']>>\n : ApplyOmitToRecord<R, Opts['omit']>\n : Opts extends { partial: true }\n ? Partial<R>\n : R\n : R\n\n/**\n * @internal\n * Mirrors @hono/zod-validator's middleware Input type.\n * Aligned with @hono/zod-validator@0.4.x; revisit on version bump.\n */\ntype HasUndefined<T> = undefined extends T ? true : false\n\n/**\n * @internal\n * Hono middleware input/output type for validator middleware.\n * Aligned with @hono/zod-validator@0.4.x; revisit on version bump.\n *\n * WARNING (Zod 4): `z.input<ZodTypeAny>` resolves to `unknown` in Zod 4, making\n * `c.req.valid(target)` return `unknown` if `In`/`Out` are left as defaults.\n * When using this type directly (outside of `ModelValidatorReturn`), always pass\n * explicit `In` and `Out` type arguments — do NOT rely on the defaults.\n *\n * Internal usages in this file (ModelValidatorReturn and preset overloads) already\n * pass `In`/`Out` explicitly via `ApplyToRecord` or `Omit<RowType<Fields>, ...>`.\n */\nexport type ValidatorInput<\n Target extends keyof ValidationTargets,\n Schema extends z.ZodTypeAny,\n In = z.input<Schema>,\n Out = z.output<Schema>,\n> = {\n in: HasUndefined<In> extends true\n ? {\n [K in Target]?:\n | (In extends ValidationTargets[K]\n ? In\n : { [K2 in keyof In]?: ValidationTargets[K][K2] | undefined })\n | undefined\n }\n : {\n [K in Target]: In extends ValidationTargets[K]\n ? In\n : { [K2 in keyof In]: ValidationTargets[K][K2] }\n }\n out: { [K in Target]: Out }\n}\n\n/**\n * @internal\n * Type-safe Hono middleware handler return for Model.validator().\n * Provides proper type narrowing for c.req.valid(target).\n *\n * Uses RowType<Fields> directly for input/output type computation\n * to ensure Zod v3/v4 compatibility (z.input<ZodTypeAny> returns unknown in Zod v4).\n */\nexport type ModelValidatorReturn<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n Target extends keyof ValidationTargets,\n Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined,\n> = MiddlewareHandler<\n any,\n string,\n ValidatorInput<\n Target,\n Apply<FieldsToZodShape<Fields>, Opts>,\n ApplyToRecord<RowType<Fields>, Opts>,\n ApplyToRecord<RowType<Fields>, Opts>\n >\n>\n\n/**\n * Hook type for Model.validator() third argument.\n * Re-exported from @hono/zod-validator for convenience.\n */\nexport type { Hook }\n\n/**\n * Represents a database model with type-safe schema derivation and CRUD operations.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for the generic Field constraint\nexport interface Model<Fields extends Record<string, Field<any, any, any>>> {\n readonly fields: Fields\n readonly tableName: string\n readonly table: ModelTable<Fields>\n\n /**\n * Returns a Zod schema derived from this model's fields.\n * Supports pick, omit, and partial transformations.\n *\n * @example\n * const CreateSchema = User.schema({ omit: ['passwordHash'] })\n * const UpdateSchema = User.schema({ partial: true, pick: ['name', 'email'] })\n */\n schema<Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined>(\n opts?: Opts,\n ): Apply<FieldsToZodShape<Fields>, Opts>\n\n /**\n * Returns a Hono middleware validator derived from this model's schema.\n * Integrates with @hono/zod-validator to validate request inputs.\n * The optional `hook` argument is passed through to @hono/zod-validator.\n *\n * Accepts a preset ('create' | 'update') as second argument to use inputSchema.\n * When a preset is used, the return type is a MiddlewareHandler (loosely typed in Phase 2A).\n * Precise type narrowing for preset is deferred to Phase 2B M2.3.\n *\n * @example\n * app.post('/users', User.validator('json', 'create'), c => {\n * const body = c.req.valid('json')\n * })\n * app.post('/users', User.validator('json', { omit: ['passwordHash'] }), c => {\n * const body = c.req.valid('json')\n * })\n * // With hook:\n * app.post('/users', User.validator('json', opts, (result, c) => {\n * if (!result.success) return c.json({ error: 'Invalid request' }, 400)\n * }), handler)\n */\n validator<Target extends keyof ValidationTargets, E extends Env = Env, P extends string = string>(\n target: Target,\n preset: 'create',\n hook?: Hook<\n Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-create'> & string>,\n E,\n P,\n Target\n >,\n ): MiddlewareHandler<\n E,\n P,\n ValidatorInput<\n Target,\n z.ZodObject<z.ZodRawShape>,\n Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-create'> & string>,\n Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-create'> & string>\n >\n >\n validator<Target extends keyof ValidationTargets, E extends Env = Env, P extends string = string>(\n target: Target,\n preset: 'update',\n hook?: Hook<\n Partial<Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-update'> & string>>,\n E,\n P,\n Target\n >,\n ): MiddlewareHandler<\n E,\n P,\n ValidatorInput<\n Target,\n z.ZodObject<z.ZodRawShape>,\n Partial<Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-update'> & string>>,\n Partial<Omit<RowType<Fields>, PolicyOmitKeys<Fields, 'input-update'> & string>>\n >\n >\n validator<\n Target extends keyof ValidationTargets,\n Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined,\n E extends Env = Env,\n P extends string = string,\n >(\n target: Target,\n opts?: Opts,\n hook?: Hook<z.output<Apply<FieldsToZodShape<Fields>, Opts>>, E, P, Target>,\n ): ModelValidatorReturn<Fields, Target, Opts>\n\n /**\n * Returns a Zod schema for API input, with policy-based field exclusions applied.\n * - 'create': serverOnly and readOnly fields are excluded\n * - 'update': same exclusions + all fields become optional (partial: true)\n *\n * The return type precisely reflects policy-derived omissions using PolicyOmitKeys.\n */\n inputSchema<Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined = undefined>(\n usage: 'create',\n opts?: Opts,\n ): z.ZodObject<\n ApplyShape<\n Omit<FieldsToZodShape<Fields>, PolicyOmitKeys<Fields, 'input-create'> & string>,\n Opts\n >\n >\n inputSchema<Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined = undefined>(\n usage: 'update',\n opts?: Opts,\n ): z.ZodObject<\n ApplyShape<\n Omit<FieldsToZodShape<Fields>, PolicyOmitKeys<Fields, 'input-update'> & string>,\n Opts extends undefined ? { partial: true } : Opts & { partial: true }\n >\n >\n inputSchema(\n usage: 'create' | 'update',\n opts?: SchemaOptions<NonRelationKeys<Fields> & string>,\n ): z.ZodObject<z.ZodRawShape>\n\n /**\n * Returns a Zod schema for API output, with policy-based field exclusions applied.\n * - serverOnly and writeOnly fields are excluded\n * - readOnly fields remain present\n *\n * The return type precisely reflects policy-derived omissions using PolicyOmitKeys.\n */\n outputSchema<\n Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined = undefined,\n >(\n opts?: Opts,\n ): z.ZodObject<\n ApplyShape<Omit<FieldsToZodShape<Fields>, PolicyOmitKeys<Fields, 'output'> & string>, Opts>\n >\n\n /**\n * Parses a DB row through outputSchema and returns the safe response object.\n * Equivalent to `User.outputSchema().parse(row)`.\n */\n toResponse(row: RowType<Fields>): unknown\n\n /**\n * Parses an array of DB rows through outputSchema and returns safe response objects.\n * The outputSchema is built once and reused for all rows.\n * Equivalent to mapping `toResponse` over the array but more efficient.\n *\n * @example\n * const rows = await app.db.select().from(User.table).where(...)\n * return c.json(User.toResponseMany(rows))\n */\n toResponseMany(rows: readonly RowType<Fields>[]): unknown[]\n\n toOpenAPIComponent(): OpenAPIModelComponent\n\n toOpenAPISchema(\n usage: 'output',\n opts: { readonly with: Partial<Record<RelationKeys<Fields> & string, true>> },\n ): OpenAPISchemaObject\n toOpenAPISchema(usage: OpenAPIUsage): OpenAPISchemaObject\n\n /**\n * Fetches multiple rows with pagination and optional ordering.\n * `limit` is required (no default) to prevent accidental unbounded queries.\n * Offset defaults to 0 if omitted.\n *\n * @example\n * const users = await User.findMany(adapter, { limit: 20 })\n * const page2 = await User.findMany(adapter, { limit: 20, offset: 20 })\n * const sorted = await User.findMany(adapter, { limit: 10, orderBy: 'name' })\n */\n findMany<With extends WithOptions<Fields>>(\n adapter: Adapter,\n options: FindManyOptions<Fields, With> & { readonly with: With },\n ): Promise<WithResult<Fields, With>[]>\n findMany(adapter: Adapter, options: FindManyOptions<Fields>): Promise<RowType<Fields>[]>\n\n /**\n * Fetches all rows without a LIMIT clause.\n * For batch processing / admin tooling. Apply an app-level size guard when used in request handlers.\n *\n * @example\n * const users = await User.findAll(adapter)\n * const admins = await User.findAll(adapter, { orderBy: 'name', where: { role: 'admin' } })\n */\n findAll(adapter: Adapter, options?: FindAllOptions<Fields>): Promise<RowType<Fields>[]>\n\n /**\n * Fetches a single row by primary key or where clause.\n * Returns null if not found.\n *\n * @example\n * const user = await User.findOne(adapter, id)\n * const byEmail = await User.findOne(adapter, { email: 'john@example.com' })\n */\n findOne<With extends WithOptions<Fields>>(\n adapter: Adapter,\n idOrWhere: IdOrWhere<Fields>,\n options: FindOneOptions<Fields, With> & { readonly with: With },\n ): Promise<WithResult<Fields, With> | null>\n findOne(adapter: Adapter, idOrWhere: IdOrWhere<Fields>): Promise<RowType<Fields> | null>\n\n /**\n * Creates a new row and returns the created record.\n *\n * @example\n * const user = await User.create(adapter, { name: 'John', email: 'john@example.com' })\n */\n create(adapter: Adapter, data: CreateInput<Fields>): Promise<RowType<Fields>>\n\n /**\n * Updates rows matching the given id or where clause.\n * Returns the updated row(s), or null if no rows matched.\n *\n * @example\n * const updated = await User.update(adapter, id, { name: 'Jane' })\n * const byEmail = await User.update(adapter, { email: '...' }, { name: 'Jane' })\n */\n update(\n adapter: Adapter,\n idOrWhere: IdOrWhere<Fields>,\n data: Partial<RowType<Fields>>,\n ): Promise<RowType<Fields> | null>\n\n /**\n * Deletes rows matching the given id or where clause.\n * Returns the number of deleted rows.\n *\n * @example\n * const result = await User.delete(adapter, id)\n * console.log(result.deleted) // number\n */\n delete(adapter: Adapter, idOrWhere: IdOrWhere<Fields>): Promise<{ readonly deleted: number }>\n}\n","import { z } from 'zod'\nimport type { Field } from '../field/types'\nimport { type FieldAccessor, resolveSchemaOptionKeys, type SchemaOptions } from './types'\n\ntype PolicyUsage = 'input-create' | 'input-update' | 'output'\n\n/**\n * Returns field names that are security-critical and must always be omitted from API schemas.\n * Currently only serverOnly fields. These cannot be overridden by user pick/omit.\n */\nfunction computeForcedOmit(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field handling\n fields: Record<string, Field<any, any, any>>,\n): string[] {\n const omit: string[] = []\n for (const [key, field] of Object.entries(fields)) {\n if (field.modifiers.policy === 'serverOnly') {\n omit.push(key)\n }\n }\n return omit\n}\n\n/**\n * Returns field names for relation fields that must always be omitted from API schemas.\n * Relation fields have no DB column and no Zod schema representation.\n */\nfunction computeRelationOmit(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field handling\n fields: Record<string, Field<any, any, any>>,\n): Set<string> {\n const keys = new Set<string>()\n for (const [key, field] of Object.entries(fields)) {\n if (field.kind === 'relation') keys.add(key)\n }\n return keys\n}\n\n/**\n * Returns field names to omit based on UX-oriented policy (writeOnly / readOnly).\n * These can be overridden when user explicitly provides pick.\n *\n * Policy mapping:\n * - `writeOnly`: omitted from output only. For input targets (input-create, input-update),\n * writeOnly fields are NOT omitted — they are intentionally part of the input (e.g. password).\n * - `readOnly`: omitted from input targets (input-create, input-update) only. Remains in output.\n *\n * The asymmetry is by design: writeOnly means \"accepted on write, hidden on read\";\n * readOnly means \"visible on read, rejected on write\".\n */\nfunction computeOptionalOmit(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field handling\n fields: Record<string, Field<any, any, any>>,\n target: PolicyUsage,\n): string[] {\n const omit: string[] = []\n for (const [key, field] of Object.entries(fields)) {\n const policy = field.modifiers.policy\n if (!policy) continue\n if (policy === 'writeOnly' && target === 'output') {\n omit.push(key)\n } else if (policy === 'readOnly' && (target === 'input-create' || target === 'input-update')) {\n omit.push(key)\n }\n }\n return omit\n}\n\n/**\n * Merges policy-derived omit with user-provided SchemaOptions.\n *\n * serverOnly fields are always omitted regardless of user pick/omit (security invariant).\n * writeOnly / readOnly are UX-oriented and can be overridden when user provides pick.\n * For 'input-update', partial defaults to true unless user specifies otherwise.\n */\nexport function derivePolicyOptions(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field handling\n fields: Record<string, Field<any, any, any>>,\n usage: PolicyUsage,\n userOpts?: SchemaOptions,\n // biome-ignore lint/suspicious/noExplicitAny: accessor is a plain object with string keys\n accessor?: FieldAccessor<any>,\n): SchemaOptions {\n const forcedBase = computeForcedOmit(fields)\n const relationOmit = computeRelationOmit(fields)\n const forced = [...new Set([...forcedBase, ...relationOmit])]\n const optional = computeOptionalOmit(fields, usage)\n\n const acc = accessor ?? ({} as FieldAccessor<string>)\n const resolvedPick = resolveSchemaOptionKeys(userOpts?.pick, acc)\n const resolvedOmit = resolveSchemaOptionKeys(userOpts?.omit, acc)\n\n if (resolvedPick !== undefined) {\n const partial = usage === 'input-update' ? (userOpts?.partial ?? true) : userOpts?.partial\n // serverOnly fields are stripped from pick even if user explicitly listed them\n const sanitizedPick = Array.from(resolvedPick).filter((k) => !forced.includes(k))\n // Combine forced omit with user-provided omit to preserve both constraints\n const combinedOmit = [...new Set([...forced, ...(resolvedOmit ?? [])])]\n return {\n ...userOpts,\n pick: sanitizedPick,\n ...(combinedOmit.length > 0 ? { omit: combinedOmit } : {}),\n partial,\n }\n }\n\n const combinedOmit = [...new Set([...forced, ...optional, ...(resolvedOmit ?? [])])]\n const partial =\n usage === 'input-update' ? (userOpts?.partial ?? true) : (userOpts?.partial ?? undefined)\n\n return {\n ...(userOpts ?? {}),\n pick: undefined,\n ...(combinedOmit.length > 0 ? { omit: combinedOmit } : {}),\n ...(partial !== undefined ? { partial } : {}),\n }\n}\n\n/**\n * Builds a Zod object schema from a fields definition.\n * Returns a ZodObject with all fields required and present.\n * Relation fields are excluded as they have no Zod schema representation.\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field handling and Zod shape\nexport function buildBaseObject(fields: Record<string, Field<any, any, any>>): z.ZodObject<any> {\n // biome-ignore lint/suspicious/noExplicitAny: Record key-value pairs have any type for shape\n const shape: Record<string, any> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (field.kind === 'relation') continue\n shape[key] = field.zodBase\n }\n return z.object(shape)\n}\n\n/**\n * Applies pick, omit, and partial transformations to a Zod object schema.\n * Order: pick → omit → partial\n *\n * Returns the transformed schema, cast to Apply<Shape, Opts> at the call site.\n */\nexport function applySchemaOptions(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Zod shape operations\n baseSchema: z.ZodObject<any>,\n opts: SchemaOptions | undefined,\n // biome-ignore lint/suspicious/noExplicitAny: accessor is a plain object with string keys\n accessor?: FieldAccessor<any>,\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for return type\n): z.ZodObject<any> {\n if (!opts) {\n return baseSchema\n }\n\n const acc = accessor ?? ({} as FieldAccessor<string>)\n const resolvedPick = resolveSchemaOptionKeys(opts.pick, acc)\n const resolvedOmit = resolveSchemaOptionKeys(opts.omit, acc)\n\n let schema = baseSchema\n\n // Apply pick\n if (resolvedPick !== undefined) {\n const pickArray = Array.from(resolvedPick)\n schema = schema.pick(\n // biome-ignore lint/suspicious/noExplicitAny: Zod API\n Object.fromEntries(pickArray.map((k) => [k, true])) as any,\n )\n }\n\n // Apply omit\n if (resolvedOmit !== undefined) {\n const omitArray = Array.from(resolvedOmit)\n schema = schema.omit(\n // biome-ignore lint/suspicious/noExplicitAny: Zod API\n Object.fromEntries(omitArray.map((k) => [k, true])) as any,\n )\n }\n\n // Apply partial\n // `partial: false` を渡してもこの条件で何もしない。スキーマは required のまま。\n if (opts.partial === true) {\n schema = schema.partial()\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Cast to Apply type at call site\n return schema as any\n}\n","import type { Field, RelationDef } from '../field/types'\nimport { applySchemaOptions, buildBaseObject, derivePolicyOptions } from '../model/schema'\nimport type { SchemaOptions } from '../model/types'\nimport type {\n OpenAPIModelComponent,\n OpenAPISchemaObject,\n OpenAPIUsage,\n WithOpenAPIOption,\n} from './types'\n\n// biome-ignore lint/suspicious/noExplicitAny: OpenAPI generation accepts any concrete field builder.\ntype AnyField = Field<any, any, any>\ntype FieldsRecord = Record<string, AnyField>\n\ninterface OpenAPIOptions {\n readonly opts?: SchemaOptions\n readonly strict?: boolean\n readonly with?: WithOpenAPIOption\n}\n\nexport function toOpenAPIComponent(\n fields: FieldsRecord,\n opts?: OpenAPIOptions,\n): OpenAPIModelComponent {\n return {\n create: toOpenAPISchema(fields, 'create', opts),\n update: toOpenAPISchema(fields, 'update', opts),\n output: toOpenAPISchema(fields, 'output', opts),\n }\n}\n\nexport function toOpenAPISchema(\n fields: FieldsRecord,\n usage: OpenAPIUsage,\n opts?: OpenAPIOptions,\n): OpenAPISchemaObject {\n const policyUsage =\n usage === 'create' ? 'input-create' : usage === 'update' ? 'input-update' : 'output'\n const merged = derivePolicyOptions(fields, policyUsage, opts?.opts)\n const schema = applySchemaOptions(buildBaseObject(fields), merged)\n const shape = getZodObjectShape(schema)\n const properties: Record<string, OpenAPISchemaObject> = {}\n const required: string[] = []\n\n for (const [key, zodSchema] of Object.entries(shape)) {\n const field = fields[key]\n if (field === undefined) continue\n if (field.kind === 'relation') continue\n\n properties[key] = fieldToOpenAPISchema(field, opts?.strict)\n if (field.modifiers.policy === 'writeOnly' && (usage === 'create' || usage === 'update')) {\n properties[key].writeOnly = true\n }\n if (field.modifiers.policy === 'readOnly' && usage === 'output') {\n properties[key].readOnly = true\n }\n if (usage !== 'update' && isRequiredZodSchema(zodSchema)) {\n required.push(key)\n }\n }\n\n if (usage === 'output' && opts?.with !== undefined) {\n for (const [key, field] of Object.entries(fields)) {\n if (field.kind !== 'relation') continue\n if (opts.with[key] !== true) continue\n const relationField = field as unknown as RelationDef\n const rawTarget = relationField.target\n const targetModel = typeof rawTarget === 'function' ? rawTarget() : rawTarget\n const targetSchema = toOpenAPISchema(targetModel.fields as FieldsRecord, 'output')\n if (relationField.relationKind === 'hasMany') {\n properties[key] = { type: 'array', items: targetSchema }\n } else {\n properties[key] = { ...targetSchema, nullable: true }\n }\n }\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n }\n}\n\nfunction fieldToOpenAPISchema(field: AnyField, strict = false): OpenAPISchemaObject {\n const schema: OpenAPISchemaObject =\n field.kind === 'json'\n ? zodToOpenAPISchema(field.zodBase, strict)\n : field.kind === 'string'\n ? { type: 'string' }\n : field.kind === 'uuid'\n ? { type: 'string', format: 'uuid' }\n : field.kind === 'number'\n ? { type: 'number' }\n : field.kind === 'integer'\n ? { type: 'integer' }\n : field.kind === 'boolean'\n ? { type: 'boolean' }\n : field.kind === 'timestamp'\n ? { type: 'string', format: 'date-time' }\n : {}\n\n if (field.modifiers.format === 'email') {\n schema.format = 'email'\n }\n if (field.modifiers.min !== undefined) {\n if (field.kind === 'string' || field.kind === 'uuid') {\n schema.minLength = field.modifiers.min\n } else {\n schema.minimum = field.modifiers.min\n }\n }\n if (field.modifiers.max !== undefined) {\n if (field.kind === 'string' || field.kind === 'uuid') {\n schema.maxLength = field.modifiers.max\n } else {\n schema.maximum = field.modifiers.max\n }\n }\n\n if (field.modifiers.optional) {\n schema.nullable = true\n }\n\n return schema\n}\n\nfunction zodToOpenAPISchema(schema: unknown, strict = false): OpenAPISchemaObject {\n const def = getZodDef(schema)\n if (def === undefined) return {}\n\n const typeName = getZodTypeName(def)\n\n if (typeName === 'ZodOptional' || typeName === 'optional') {\n return zodToOpenAPISchema(def.innerType, strict)\n }\n if (typeName === 'ZodDefault' || typeName === 'default') {\n return zodToOpenAPISchema(def.innerType, strict)\n }\n if (typeName === 'ZodNullable' || typeName === 'nullable') {\n return { ...zodToOpenAPISchema(def.innerType, strict), nullable: true }\n }\n\n if (typeName === 'ZodObject' || typeName === 'object') {\n const shape = getZodObjectShape(schema)\n const properties: Record<string, OpenAPISchemaObject> = {}\n const required: string[] = []\n\n for (const [key, childSchema] of Object.entries(shape)) {\n properties[key] = zodToOpenAPISchema(childSchema, strict)\n if (isRequiredZodSchema(childSchema)) {\n required.push(key)\n }\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n }\n }\n\n if (typeName === 'ZodString' || typeName === 'string') {\n return applyStringChecks({ type: 'string' }, def)\n }\n\n if (typeName === 'ZodNumber' || typeName === 'number') {\n return applyNumberChecks({ type: hasIntegerCheck(def) ? 'integer' : 'number' }, def)\n }\n\n if (typeName === 'ZodBoolean' || typeName === 'boolean') {\n return { type: 'boolean' }\n }\n\n if (typeName === 'ZodArray' || typeName === 'array') {\n const itemSchema = def.element ?? def.type\n return {\n type: 'array',\n items: zodToOpenAPISchema(itemSchema, strict),\n }\n }\n\n if (typeName === 'ZodRecord' || typeName === 'record') {\n return {\n type: 'object',\n additionalProperties: zodToOpenAPISchema(def.valueType, strict),\n }\n }\n\n if (typeName === 'ZodUnknown' || typeName === 'unknown') {\n return {}\n }\n\n if (strict) {\n throw new Error(`Unsupported Zod type for strict OpenAPI generation: ${typeName ?? 'unknown'}`)\n }\n return {\n 'x-nanoka-zod-unsupported': true,\n ...(typeName ? { 'x-nanoka-zod-type': typeName } : {}),\n }\n}\n\nfunction getZodObjectShape(schema: unknown): Record<string, unknown> {\n if (\n typeof schema === 'object' &&\n schema !== null &&\n 'shape' in schema &&\n typeof schema.shape === 'object' &&\n schema.shape !== null\n ) {\n return schema.shape as Record<string, unknown>\n }\n\n if (\n typeof schema === 'object' &&\n schema !== null &&\n '_def' in schema &&\n typeof schema._def === 'object' &&\n schema._def !== null &&\n 'shape' in schema._def\n ) {\n const shape = schema._def.shape\n return (typeof shape === 'function' ? shape() : shape) as Record<string, unknown>\n }\n\n return {}\n}\n\nfunction isRequiredZodSchema(schema: unknown): boolean {\n const def = getZodDef(schema)\n if (def === undefined) {\n return true\n }\n\n const typeName = getZodTypeName(def)\n return (\n typeName !== 'ZodOptional' &&\n typeName !== 'optional' &&\n typeName !== 'ZodDefault' &&\n typeName !== 'default'\n )\n}\n\nfunction getZodDef(schema: unknown): Record<string, unknown> | undefined {\n if (\n typeof schema === 'object' &&\n schema !== null &&\n '_def' in schema &&\n typeof schema._def === 'object' &&\n schema._def !== null\n ) {\n return schema._def as Record<string, unknown>\n }\n\n return undefined\n}\n\nfunction getZodTypeName(def: Record<string, unknown>): string | undefined {\n return typeof def.typeName === 'string'\n ? def.typeName\n : typeof def.type === 'string'\n ? def.type\n : undefined\n}\n\nfunction applyStringChecks(\n schema: OpenAPISchemaObject,\n def: Record<string, unknown>,\n): OpenAPISchemaObject {\n for (const check of getZodChecks(def)) {\n const checkDef = getZodCheckDef(check)\n if (checkDef.kind === 'email' || checkDef.format === 'email') {\n schema.format = 'email'\n }\n if (checkDef.kind === 'min' && typeof checkDef.value === 'number') {\n schema.minLength = checkDef.value\n }\n if (checkDef.kind === 'max' && typeof checkDef.value === 'number') {\n schema.maxLength = checkDef.value\n }\n if (checkDef.check === 'min_length' && typeof checkDef.minimum === 'number') {\n schema.minLength = checkDef.minimum\n }\n if (checkDef.check === 'max_length' && typeof checkDef.maximum === 'number') {\n schema.maxLength = checkDef.maximum\n }\n }\n\n return schema\n}\n\nfunction applyNumberChecks(\n schema: OpenAPISchemaObject,\n def: Record<string, unknown>,\n): OpenAPISchemaObject {\n for (const check of getZodChecks(def)) {\n const checkDef = getZodCheckDef(check)\n if (checkDef.kind === 'min' && typeof checkDef.value === 'number') {\n schema.minimum = checkDef.value\n }\n if (checkDef.kind === 'max' && typeof checkDef.value === 'number') {\n schema.maximum = checkDef.value\n }\n if (\n (checkDef.check === 'greater_than' || checkDef.check === 'number_format') &&\n typeof checkDef.minimum === 'number'\n ) {\n schema.minimum = checkDef.minimum\n }\n if (\n (checkDef.check === 'less_than' || checkDef.check === 'number_format') &&\n typeof checkDef.maximum === 'number'\n ) {\n schema.maximum = checkDef.maximum\n }\n }\n\n return schema\n}\n\nfunction hasIntegerCheck(def: Record<string, unknown>): boolean {\n return getZodChecks(def).some((check) => {\n const checkDef = getZodCheckDef(check)\n return (\n checkDef.kind === 'int' ||\n checkDef.format === 'safeint' ||\n checkDef.format === 'int32' ||\n checkDef.format === 'int64'\n )\n })\n}\n\nfunction getZodChecks(def: Record<string, unknown>): readonly unknown[] {\n return Array.isArray(def.checks) ? def.checks : []\n}\n\nfunction getZodCheckDef(check: unknown): Record<string, unknown> {\n if (typeof check !== 'object' || check === null) {\n return {}\n }\n if (\n '_zod' in check &&\n typeof check._zod === 'object' &&\n check._zod !== null &&\n 'def' in check._zod &&\n typeof check._zod.def === 'object' &&\n check._zod.def !== null\n ) {\n return check._zod.def as Record<string, unknown>\n }\n\n return check as Record<string, unknown>\n}\n","import {\n type AnySQLiteColumn,\n type SQLiteTableWithColumns,\n sqliteTable,\n} from 'drizzle-orm/sqlite-core'\nimport type { Field } from '../field/types'\nimport type { NonRelationKeys } from './types'\n\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\ntype ModelTable<Fields extends Record<string, Field<any, any, any>>> = SQLiteTableWithColumns<{\n name: string\n schema: undefined\n columns: { [K in NonRelationKeys<Fields>]: AnySQLiteColumn }\n dialect: 'sqlite'\n}>\n\n/**\n * Constructs a Drizzle SQLiteTable from a tableName and fields.\n * Each field is converted to a Drizzle column via field.drizzleColumn(key).\n * @internal\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\nexport function buildTable<Fields extends Record<string, Field<any, any, any>>>(\n tableName: string,\n fields: Fields,\n): ModelTable<Fields> {\n const columns: Record<string, any> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (field.kind === 'relation') continue\n columns[key] = field.drizzleColumn(key)\n }\n return sqliteTable(tableName, columns) as unknown as ModelTable<Fields>\n}\n","import { and, asc, desc, eq, inArray, SQL } from 'drizzle-orm'\nimport type { SQLiteTableWithColumns } from 'drizzle-orm/sqlite-core'\nimport { HTTPException } from 'hono/http-exception'\nimport type { Adapter } from '../adapter/types'\nimport type { Field, RelationDef, RelationTargetLike } from '../field/types'\nimport { buildTable } from './table'\nimport type {\n CreateInput,\n FindAllOptions,\n FindOneOptions,\n IdOrWhere,\n OrderBy,\n RowType,\n Where,\n WithOptions,\n WithResult,\n} from './types'\n\n/**\n * Validates and guards limit/offset parameters.\n * @internal\n */\nfunction guardLimit(limit: unknown): number {\n if (!Number.isInteger(limit)) {\n throw new HTTPException(400, { message: 'limit must be an integer' })\n }\n const n = limit as number\n if (n < 0) {\n throw new HTTPException(400, { message: 'limit must be >= 0' })\n }\n return n\n}\n\nfunction guardOffset(offset: unknown): number {\n if (!Number.isInteger(offset)) {\n throw new HTTPException(400, { message: 'offset must be an integer' })\n }\n const n = offset as number\n if (n < 0) {\n throw new HTTPException(400, { message: 'offset must be >= 0' })\n }\n return n\n}\n\n/**\n * Finds the primary key field from fields record.\n * @internal\n */\nfunction findPrimaryKey(\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n fields: Record<string, Field<any, any, any>>,\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n): [string, Field<any, any, any>] | null {\n let pkKey: string | undefined\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n let pkField: Field<any, any, any> | undefined\n let pkCount = 0\n\n for (const [key, field] of Object.entries(fields)) {\n if (field.modifiers.primary === true) {\n pkCount++\n if (pkCount === 1) {\n pkKey = key\n pkField = field\n }\n }\n }\n\n if (pkCount === 0) {\n return null\n }\n if (pkCount > 1) {\n throw new HTTPException(500, { message: 'model has multiple primary keys' })\n }\n if (pkKey === undefined || pkField === undefined) {\n return null\n }\n\n return [pkKey, pkField]\n}\n\n/**\n * Constructs a Drizzle where clause from an object.\n * All entries are combined with AND.\n * @internal\n */\nfunction buildWhereClause(\n table: SQLiteTableWithColumns<any>,\n fields: Record<string, Field<any, any, any>>,\n where: Where<Record<string, any>>,\n): ReturnType<typeof and> | null {\n const conditions: ReturnType<typeof eq>[] = []\n\n for (const [key, value] of Object.entries(where)) {\n // Multi-layered guard against identifier injection\n if (!Object.hasOwn(fields, key)) {\n throw new HTTPException(400, { message: 'invalid field in where clause' })\n }\n if (!Object.hasOwn(table, key)) {\n throw new HTTPException(400, { message: 'invalid column in table' })\n }\n // biome-ignore lint/suspicious/noExplicitAny: table column access is runtime-guarded by hasOwn\n const col = (table as unknown as Record<string, any>)[key]\n conditions.push(eq(col, value))\n }\n\n if (conditions.length === 0) {\n return null\n }\n if (conditions.length === 1) {\n return conditions[0]\n }\n return and(...conditions)\n}\n\nfunction resolveRelationTarget(field: RelationDef): RelationTargetLike {\n return typeof field.target === 'function' ? field.target() : field.target\n}\n\nfunction getTargetTable(target: RelationTargetLike): SQLiteTableWithColumns<any> {\n if (Object.hasOwn(target, 'table')) {\n return (target as unknown as { table: SQLiteTableWithColumns<any> }).table\n }\n return buildTable(target.tableName, target.fields as Record<string, Field<any, any, any>>)\n}\n\nfunction validateWithOptions(\n fields: Record<string, Field<any, any, any>>,\n withOptions: Record<string, unknown>,\n): void {\n if (withOptions === null || typeof withOptions !== 'object' || Array.isArray(withOptions)) {\n throw new HTTPException(400, { message: 'invalid with option' })\n }\n\n for (const [key, value] of Object.entries(withOptions)) {\n if (value !== true) {\n throw new HTTPException(400, { message: 'nested with is not supported' })\n }\n if (!Object.hasOwn(fields, key) || fields[key]?.kind !== 'relation') {\n throw new HTTPException(400, { message: 'invalid relation in with option' })\n }\n }\n}\n\nasync function loadRelations<\n Fields extends Record<string, Field<any, any, any>>,\n With extends WithOptions<Fields>,\n>(\n adapter: Adapter,\n _parentTable: SQLiteTableWithColumns<any>,\n parentFields: Fields,\n parentRows: RowType<Fields>[],\n withOptions: With,\n): Promise<WithResult<Fields, With>[]> {\n if (parentRows.length === 0) {\n return []\n }\n\n const rows = parentRows.map((row) => ({ ...row })) as WithResult<Fields, With>[]\n\n for (const relationKey of Object.keys(withOptions)) {\n const field = parentFields[relationKey]\n if (field?.kind !== 'relation') {\n throw new HTTPException(400, { message: 'invalid relation in with option' })\n }\n\n const relation = field as RelationDef\n const target = resolveRelationTarget(relation)\n const targetFields = target.fields as Record<string, Field<any, any, any>>\n const targetTable = getTargetTable(target)\n\n if (relation.relationKind === 'hasMany') {\n const parentPk = findPrimaryKey(parentFields)\n if (!parentPk) {\n throw new HTTPException(500, { message: 'model has no primary key' })\n }\n const parentPkKey = parentPk[0]\n const foreignKey = relation.foreignKey\n if (!Object.hasOwn(targetFields, foreignKey) || !Object.hasOwn(targetTable, foreignKey)) {\n throw new HTTPException(500, { message: 'invalid relation foreign key' })\n }\n\n const parentIds = Array.from(\n new Set(parentRows.map((row) => (row as Record<string, unknown>)[parentPkKey])),\n )\n const targetRows =\n parentIds.length === 0\n ? []\n : await adapter.drizzle\n .select()\n .from(targetTable)\n .where(\n inArray(\n (targetTable as unknown as Record<string, any>)[foreignKey],\n parentIds as any[],\n ),\n )\n\n const grouped = new Map<unknown, unknown[]>()\n for (const targetRow of targetRows as Record<string, unknown>[]) {\n const value = targetRow[foreignKey]\n const group = grouped.get(value)\n if (group === undefined) {\n grouped.set(value, [targetRow])\n } else {\n group.push(targetRow)\n }\n }\n\n for (const row of rows as Record<string, unknown>[]) {\n row[relationKey] = grouped.get(row[parentPkKey]) ?? []\n }\n } else {\n const foreignKey = relation.foreignKey\n if (!Object.hasOwn(parentFields, foreignKey) || !Object.hasOwn(_parentTable, foreignKey)) {\n throw new HTTPException(500, { message: 'invalid relation foreign key' })\n }\n\n const targetPk = findPrimaryKey(targetFields)\n if (!targetPk) {\n throw new HTTPException(500, { message: 'model has no primary key' })\n }\n const targetPkKey = targetPk[0]\n if (!Object.hasOwn(targetTable, targetPkKey)) {\n throw new HTTPException(500, { message: 'invalid relation primary key' })\n }\n\n const parentFkValues = Array.from(\n new Set(parentRows.map((row) => (row as Record<string, unknown>)[foreignKey])),\n )\n const targetRows =\n parentFkValues.length === 0\n ? []\n : await adapter.drizzle\n .select()\n .from(targetTable)\n .where(\n inArray(\n (targetTable as unknown as Record<string, any>)[targetPkKey],\n parentFkValues as any[],\n ),\n )\n\n const byPk = new Map<unknown, unknown>()\n for (const targetRow of targetRows as Record<string, unknown>[]) {\n byPk.set(targetRow[targetPkKey], targetRow)\n }\n\n for (const row of rows as Record<string, unknown>[]) {\n row[relationKey] = byPk.get(row[foreignKey]) ?? null\n }\n }\n }\n\n return rows\n}\n\n/**\n * Fetches multiple rows with limit, offset, optional ordering, and optional where clause.\n * @internal\n */\nexport async function findManyImpl<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n With extends WithOptions<Fields> | undefined = undefined,\n>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n fields: Fields,\n options: {\n limit: unknown\n offset?: unknown\n orderBy?: OrderBy<Fields>\n where?: Where<Fields> | SQL\n with?: With\n },\n): Promise<RowType<Fields>[] | WithResult<Fields, NonNullable<With>>[]> {\n const limit = guardLimit(options.limit)\n const offset = options.offset !== undefined ? guardOffset(options.offset) : 0\n\n // biome-ignore lint/suspicious/noExplicitAny: drizzle query builder type narrowing\n let query: any = adapter.drizzle.select().from(table).limit(limit).offset(offset)\n\n // Apply where clause\n if (options.where !== undefined) {\n if (options.where instanceof SQL) {\n query = query.where(options.where)\n } else {\n const whereClause = buildWhereClause(\n table,\n fields,\n options.where as Where<Record<string, any>>,\n )\n if (whereClause !== null) {\n query = query.where(whereClause)\n }\n }\n }\n\n // Apply ordering\n if (options.orderBy !== undefined) {\n const orderByList = Array.isArray(options.orderBy) ? options.orderBy : [options.orderBy]\n\n for (const orderByItem of orderByList) {\n let column: string\n let direction: 'asc' | 'desc' = 'asc'\n\n if (typeof orderByItem === 'string') {\n column = orderByItem\n } else if (\n typeof orderByItem === 'object' &&\n orderByItem !== null &&\n 'column' in orderByItem\n ) {\n column = orderByItem.column\n if (orderByItem.direction) {\n direction = orderByItem.direction\n }\n } else {\n throw new HTTPException(400, { message: 'invalid orderBy format' })\n }\n\n // Runtime guard against identifier injection (both fields and table to match where-clause guard)\n if (!Object.hasOwn(fields, column) || !Object.hasOwn(table, column)) {\n throw new HTTPException(400, { message: 'invalid field in orderBy' })\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: table column access is runtime-guarded by hasOwn\n const col = (table as unknown as Record<string, any>)[column]\n query = query.orderBy(direction === 'asc' ? asc(col) : desc(col))\n }\n }\n\n const rows = await query\n if (options.with !== undefined) {\n validateWithOptions(fields, options.with as Record<string, unknown>)\n return loadRelations(adapter, table, fields, rows, options.with as NonNullable<With>)\n }\n return rows\n}\n\n/**\n * Fetches all rows without a LIMIT clause.\n * For batch processing / admin tooling. Apply an app-level size guard when used in request handlers.\n * @internal\n */\nexport async function findAllImpl<\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field constraint\n Fields extends Record<string, Field<any, any, any>>,\n>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n fields: Fields,\n options?: FindAllOptions<Fields>,\n): Promise<RowType<Fields>[]> {\n const offset = options?.offset !== undefined ? guardOffset(options.offset) : undefined\n\n // SQLite requires LIMIT when OFFSET is used.\n // Number.MAX_SAFE_INTEGER is used as a sentinel \"no practical limit\" value when offset is specified.\n // biome-ignore lint/suspicious/noExplicitAny: drizzle query builder type narrowing\n let query: any =\n offset !== undefined\n ? adapter.drizzle.select().from(table).limit(Number.MAX_SAFE_INTEGER).offset(offset)\n : adapter.drizzle.select().from(table)\n\n // Apply where clause\n if (options?.where !== undefined) {\n if (options.where instanceof SQL) {\n query = query.where(options.where)\n } else {\n const whereClause = buildWhereClause(\n table,\n fields,\n options.where as Where<Record<string, any>>,\n )\n if (whereClause !== null) {\n query = query.where(whereClause)\n }\n }\n }\n\n // Apply ordering\n if (options?.orderBy !== undefined) {\n const orderByList = Array.isArray(options.orderBy) ? options.orderBy : [options.orderBy]\n\n for (const orderByItem of orderByList) {\n let column: string\n let direction: 'asc' | 'desc' = 'asc'\n\n if (typeof orderByItem === 'string') {\n column = orderByItem\n } else if (\n typeof orderByItem === 'object' &&\n orderByItem !== null &&\n 'column' in orderByItem\n ) {\n column = orderByItem.column\n if (orderByItem.direction) {\n direction = orderByItem.direction\n }\n } else {\n throw new HTTPException(400, { message: 'invalid orderBy format' })\n }\n\n // Runtime guard against identifier injection (both fields and table to match where-clause guard)\n if (!Object.hasOwn(fields, column) || !Object.hasOwn(table, column)) {\n throw new HTTPException(400, { message: 'invalid field in orderBy' })\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: table column access is runtime-guarded by hasOwn\n const col = (table as unknown as Record<string, any>)[column]\n query = query.orderBy(direction === 'asc' ? asc(col) : desc(col))\n }\n }\n\n const rows = await query\n return rows\n}\n\n/**\n * Fetches a single row by primary key or where clause.\n * @internal\n */\nexport async function findOneImpl<Fields extends Record<string, Field<any, any, any>>>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n fields: Fields,\n idOrWhere: IdOrWhere<Fields>,\n options?: FindOneOptions<Fields>,\n): Promise<RowType<Fields> | null> {\n let where: Where<Fields> | null = null\n\n if (typeof idOrWhere === 'string' || typeof idOrWhere === 'number') {\n // PK mode\n const pk = findPrimaryKey(fields)\n if (!pk) {\n throw new HTTPException(500, { message: 'model has no primary key' })\n }\n where = { [pk[0]]: idOrWhere } as Where<Fields>\n } else {\n where = idOrWhere as Where<Fields>\n }\n\n const whereClause = buildWhereClause(table, fields, where)\n if (!whereClause) {\n throw new HTTPException(400, { message: 'where clause must not be empty' })\n }\n\n if (options?.with !== undefined) {\n validateWithOptions(fields, options.with as Record<string, unknown>)\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: drizzle query type\n const rows = await (adapter.drizzle.select().from(table).where(whereClause).limit(1) as any)\n if (rows.length === 0) {\n return null\n }\n if (options?.with !== undefined) {\n const withRows = await loadRelations(adapter, table, fields, [rows[0]], options.with)\n return withRows[0] ?? null\n }\n return rows[0]\n}\n\n/**\n * Creates a new row and returns the created record.\n * @internal\n */\nexport async function createImpl<Fields extends Record<string, Field<any, any, any>>>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n data: CreateInput<Fields>,\n): Promise<RowType<Fields>> {\n const rows = await (adapter.drizzle\n .insert(table)\n .values(data as any)\n .returning() as any)\n return rows[0]\n}\n\n/**\n * Updates rows matching the given id or where clause.\n * @internal\n */\nexport async function updateImpl<Fields extends Record<string, Field<any, any, any>>>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n fields: Fields,\n idOrWhere: IdOrWhere<Fields>,\n data: Partial<RowType<Fields>>,\n): Promise<RowType<Fields> | null> {\n let where: Where<Fields> | null = null\n\n if (typeof idOrWhere === 'string' || typeof idOrWhere === 'number') {\n // PK mode\n const pk = findPrimaryKey(fields)\n if (!pk) {\n throw new HTTPException(500, { message: 'model has no primary key' })\n }\n where = { [pk[0]]: idOrWhere } as Where<Fields>\n } else {\n where = idOrWhere as Where<Fields>\n }\n\n const whereClause = buildWhereClause(table, fields, where)\n if (!whereClause) {\n throw new HTTPException(400, { message: 'where clause must not be empty' })\n }\n\n const rows = await (adapter.drizzle\n .update(table)\n .set(data as any)\n .where(whereClause)\n .returning() as any)\n return rows.length > 0 ? rows[0] : null\n}\n\n/**\n * Deletes rows matching the given id or where clause.\n * @internal\n */\nexport async function deleteImpl<Fields extends Record<string, Field<any, any, any>>>(\n adapter: Adapter,\n table: SQLiteTableWithColumns<any>,\n fields: Fields,\n idOrWhere: IdOrWhere<Fields>,\n): Promise<{ readonly deleted: number }> {\n let where: Where<Fields> | null = null\n\n if (typeof idOrWhere === 'string' || typeof idOrWhere === 'number') {\n // PK mode\n const pk = findPrimaryKey(fields)\n if (!pk) {\n throw new HTTPException(500, { message: 'model has no primary key' })\n }\n where = { [pk[0]]: idOrWhere } as Where<Fields>\n } else {\n where = idOrWhere as Where<Fields>\n }\n\n const whereClause = buildWhereClause(table, fields, where)\n if (!whereClause) {\n throw new HTTPException(400, { message: 'where clause must not be empty' })\n }\n\n const result = await adapter.drizzle.delete(table).where(whereClause).returning()\n return { deleted: result.length }\n}\n","import { type Hook, zValidator } from '@hono/zod-validator'\nimport type { Env, ValidationTargets } from 'hono'\nimport type { z } from 'zod'\nimport type { Adapter } from '../adapter/types'\nimport type { Field } from '../field/types'\nimport { toOpenAPIComponent, toOpenAPISchema } from '../openapi/generate'\nimport type { OpenAPIUsage, WithOpenAPIOption } from '../openapi/types'\nimport { createImpl, deleteImpl, findAllImpl, findManyImpl, findOneImpl, updateImpl } from './crud'\nimport { applySchemaOptions, buildBaseObject, derivePolicyOptions } from './schema'\nimport { buildTable } from './table'\nimport type {\n Apply,\n CreateInput,\n FieldsToZodShape,\n FindAllOptions,\n FindManyOptions,\n FindOneOptions,\n IdOrWhere,\n Model,\n NonRelationKeys,\n RowType,\n SchemaOptions,\n} from './types'\nimport { buildFieldAccessor } from './types'\n\n/**\n * Creates a Model instance from a tableName and fields definition.\n * The model supports deriving Zod schemas, Hono validators, and CRUD operations.\n *\n * @example\n * const User = defineModel('users', {\n * id: t.uuid().primary(),\n * name: t.string(),\n * email: t.string().email(),\n * passwordHash: t.string(),\n * })\n *\n * const CreateSchema = User.schema({ omit: ['passwordHash'] })\n * const users = await User.findMany(adapter, { limit: 20 })\n */\n// biome-ignore lint/suspicious/noExplicitAny: any is necessary for generic Field constraint\nexport function defineModel<Fields extends Record<string, Field<any, any, any>>>(\n tableName: string,\n fields: Fields,\n): Model<Fields> {\n const table = buildTable(tableName, fields)\n const accessor = buildFieldAccessor(fields)\n\n return {\n fields,\n tableName,\n table,\n\n schema<Opts extends SchemaOptions<NonRelationKeys<Fields> & string> | undefined>(\n opts?: Opts,\n ): Apply<FieldsToZodShape<Fields>, Opts> {\n const baseSchema = buildBaseObject(fields)\n const schema = applySchemaOptions(baseSchema, opts, accessor)\n // biome-ignore lint/suspicious/noExplicitAny: Zod .pick()/.omit() return type narrowing requires cast at boundary\n return schema as any\n },\n\n validator(\n target: keyof ValidationTargets,\n optsOrPreset?: 'create' | 'update' | SchemaOptions<NonRelationKeys<Fields> & string>,\n // biome-ignore lint/suspicious/noExplicitAny: Hook<T> is contravariant in T; any is required to bridge overload implementations\n hook?: Hook<any, Env, string, keyof ValidationTargets>,\n ) {\n let schema: z.ZodTypeAny\n if (optsOrPreset === 'create' || optsOrPreset === 'update') {\n schema = this.inputSchema(optsOrPreset)\n } else {\n schema = this.schema(optsOrPreset as SchemaOptions<NonRelationKeys<Fields> & string>)\n }\n // biome-ignore lint/suspicious/noExplicitAny: zValidator return type cast required at overload boundary\n return zValidator(target, schema, hook) as any\n },\n\n inputSchema(\n usage: 'create' | 'update',\n opts?: SchemaOptions<NonRelationKeys<Fields> & string>,\n // biome-ignore lint/suspicious/noExplicitAny: precise return type is enforced by Model<Fields> overload signatures\n ): any {\n const merged = derivePolicyOptions(\n fields,\n usage === 'create' ? 'input-create' : 'input-update',\n opts,\n accessor,\n )\n const baseSchema = buildBaseObject(fields)\n return applySchemaOptions(baseSchema, merged)\n },\n\n outputSchema(\n opts?: SchemaOptions<NonRelationKeys<Fields> & string>,\n // biome-ignore lint/suspicious/noExplicitAny: precise return type is enforced by Model<Fields> overload signatures\n ): any {\n const merged = derivePolicyOptions(fields, 'output', opts, accessor)\n const baseSchema = buildBaseObject(fields)\n return applySchemaOptions(baseSchema, merged)\n },\n\n toResponse(row: RowType<Fields>): unknown {\n return this.outputSchema().parse(row)\n },\n\n toResponseMany(rows: readonly RowType<Fields>[]): unknown[] {\n const schema = this.outputSchema()\n return rows.map((row) => schema.parse(row))\n },\n\n toOpenAPIComponent() {\n return toOpenAPIComponent(fields)\n },\n\n toOpenAPISchema(usage: OpenAPIUsage, opts?: { readonly with: Partial<Record<string, true>> }) {\n return toOpenAPISchema(\n fields,\n usage,\n opts ? { with: opts.with as WithOpenAPIOption } : undefined,\n )\n },\n\n findMany: ((adapter: Adapter, options: FindManyOptions<Fields>) =>\n findManyImpl(adapter, table, fields, options)) as Model<Fields>['findMany'],\n\n findAll(adapter: Adapter, options?: FindAllOptions<Fields>): Promise<RowType<Fields>[]> {\n return findAllImpl(adapter, table, fields, options)\n },\n\n findOne: ((adapter: Adapter, idOrWhere: IdOrWhere<Fields>, options?: FindOneOptions<Fields>) =>\n findOneImpl(adapter, table, fields, idOrWhere, options)) as Model<Fields>['findOne'],\n\n create(adapter: Adapter, data: CreateInput<Fields>): Promise<RowType<Fields>> {\n return createImpl(adapter, table, data)\n },\n\n update(\n adapter: Adapter,\n idOrWhere: IdOrWhere<Fields>,\n data: Partial<RowType<Fields>>,\n ): Promise<RowType<Fields> | null> {\n return updateImpl(adapter, table, fields, idOrWhere, data)\n },\n\n delete(adapter: Adapter, idOrWhere: IdOrWhere<Fields>): Promise<{ readonly deleted: number }> {\n return deleteImpl(adapter, table, fields, idOrWhere)\n },\n }\n}\n","import type { OpenAPIDocument, OpenAPIRouteMetadata, OpenAPISpecOptions } from './types'\n\nfunction honoPathToOpenAPI(path: string): string {\n return path.replace(/:([^/]+)/g, '{$1}')\n}\n\nexport function buildOpenAPIDocument(\n routes: readonly OpenAPIRouteMetadata[],\n options: OpenAPISpecOptions,\n): OpenAPIDocument {\n const paths: Record<string, Record<string, unknown>> = {}\n\n for (const route of routes) {\n const openAPIPath = honoPathToOpenAPI(route.path)\n if (!paths[openAPIPath]) {\n paths[openAPIPath] = {}\n }\n\n const operation: Record<string, unknown> = {}\n if (route.operationId) operation.operationId = route.operationId\n if (route.summary) operation.summary = route.summary\n if (route.description) operation.description = route.description\n if (route.tags) operation.tags = route.tags\n\n const parameters: unknown[] = []\n const pathParams = [...route.path.matchAll(/:([^/]+)/g)].map((m) => m[1])\n for (const param of pathParams) {\n const alreadyDefined = route.params?.some((p) => p.name === param && p.in === 'path')\n if (!alreadyDefined) {\n parameters.push({ name: param, in: 'path', required: true, schema: { type: 'string' } })\n }\n }\n if (route.params) {\n parameters.push(...route.params)\n }\n if (parameters.length > 0) operation.parameters = parameters\n\n if (route.requestBody) operation.requestBody = route.requestBody\n operation.responses = route.responses\n\n paths[openAPIPath][route.method] = operation\n }\n\n const doc: OpenAPIDocument = {\n openapi: '3.1.0',\n info: options.info,\n ...(options.servers ? { servers: options.servers } : {}),\n paths,\n }\n\n return doc\n}\n","import type { MiddlewareHandler } from 'hono'\n\nexport interface SwaggerUIOptions {\n readonly url: string\n readonly title?: string\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n}\n\nexport function swaggerUI(options: SwaggerUIOptions): MiddlewareHandler {\n const title = escapeHtml(options.title ?? 'API Documentation')\n const html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <title>${title}</title>\n <link rel=\"stylesheet\" href=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui.css\" />\n</head>\n<body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js\"></script>\n <script>\n SwaggerUIBundle({\n url: ${JSON.stringify(options.url)},\n dom_id: '#swagger-ui',\n presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],\n layout: 'BaseLayout',\n })\n </script>\n</body>\n</html>`\n\n return async (c) => {\n return c.html(html)\n }\n}\n","import { Hono } from 'hono'\nimport type { BlankEnv, Env, H } from 'hono/types'\nimport type { Adapter } from '../adapter/types'\nimport type { Field } from '../field/types'\nimport { defineModel } from '../model/define'\nimport type { IdOrWhere } from '../model/types'\nimport { buildOpenAPIDocument } from '../openapi/route'\nimport type { HttpMethod, OpenAPIRouteMetadata } from '../openapi/types'\nimport type { Nanoka, NanokaModel, RouteOpenAPIOption } from './types'\n\n/**\n * Creates a Nanoka application instance with the given database adapter.\n *\n * @param adapter - The database adapter (e.g., d1Adapter(env.DB))\n * @returns A Nanoka application (Hono extended with model(), db, and batch)\n *\n * @example\n * export default {\n * fetch(req: Request, env: Env, ctx: ExecutionContext) {\n * const app = nanoka(d1Adapter(env.DB))\n * const User = app.model('users', { id, name, email, passwordHash })\n * app.get('/users', async (c) => {\n * const users = await User.findMany({ limit: 20 })\n * return c.json(users)\n * })\n * return app.fetch(req, env, ctx)\n * }\n * }\n */\nexport function nanoka<E extends Env = BlankEnv>(adapter: Adapter): Nanoka<E> {\n const app = new Hono<E>() as Nanoka<E>\n const openapiRoutes: OpenAPIRouteMetadata[] = []\n\n Object.defineProperty(app, 'db', {\n get: () => adapter.drizzle,\n enumerable: true,\n })\n\n app.batch = ((queries: Parameters<Adapter['batch']>[0]) =>\n adapter.batch(queries)) as unknown as Adapter['batch']\n\n app.openapi = (metadata: OpenAPIRouteMetadata) => {\n openapiRoutes.push(metadata)\n return app\n }\n\n app.generateOpenAPISpec = (options) => buildOpenAPIDocument(openapiRoutes, options)\n\n function wrapWithOpenAPI(method: HttpMethod) {\n // biome-ignore lint/suspicious/noExplicitAny: original Hono method is typed as HandlerInterface which needs any at call site\n const original = (app as any)[method].bind(app)\n // biome-ignore lint/suspicious/noExplicitAny: overload bridge — type safety is provided by the Nanoka interface overload\n ;(app as any)[method] = (path: string, second: RouteOpenAPIOption | H, ...rest: H[]) => {\n if (\n second !== null &&\n typeof second === 'object' &&\n !Array.isArray(second) &&\n typeof (second as RouteOpenAPIOption).openapi === 'object'\n ) {\n const { openapi } = second as RouteOpenAPIOption\n openapiRoutes.push({ ...openapi, path, method })\n return original(path, ...rest)\n }\n return original(path, second, ...rest)\n }\n }\n\n for (const method of ['get', 'post', 'put', 'patch', 'delete'] as const) {\n wrapWithOpenAPI(method)\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: any is necessary for Field generic constraint\n app.model = function model<Fields extends Record<string, Field<any, any, any>>>(\n name: string,\n fields: Fields,\n ): NanokaModel<Fields> {\n const inner = defineModel(name, fields)\n\n return {\n fields: inner.fields,\n tableName: inner.tableName,\n table: inner.table,\n\n schema: (opts) => inner.schema(opts),\n\n validator: (\n ...args: [\n keyof import('hono').ValidationTargets,\n (\n | 'create'\n | 'update'\n | import('../model/types').SchemaOptions<\n import('../model/types').NonRelationKeys<Fields> & string\n >\n )?,\n import('@hono/zod-validator').Hook<\n // biome-ignore lint/suspicious/noExplicitAny: Hook<T> is contravariant in T; any is required to bridge overload implementations\n any,\n import('hono').Env,\n string,\n keyof import('hono').ValidationTargets\n >?,\n ]\n ) => {\n // `NanokaModel` interface の overload 定義 (router/types.ts) で type safety は担保する。\n // 実装は inner.validator に委譲するだけで、型は interface 側の overload に従う。\n // biome-ignore lint/suspicious/noExplicitAny: NanokaModel interface overloads provide type safety\n return (inner.validator as (...a: typeof args) => any)(...args)\n },\n\n inputSchema: (usage, opts) => inner.inputSchema(usage, opts),\n\n outputSchema: (opts) => inner.outputSchema(opts),\n\n toResponse: (row) => inner.toResponse(row),\n\n toResponseMany: (rows) => inner.toResponseMany(rows),\n\n toOpenAPIComponent: () => inner.toOpenAPIComponent(),\n\n toOpenAPISchema: (usage, opts?: { readonly with: Partial<Record<string, true>> }) =>\n // biome-ignore lint/suspicious/noExplicitAny: NanokaModel interface overloads provide type safety\n (inner.toOpenAPISchema as (u: typeof usage, o?: typeof opts) => any)(usage, opts),\n\n findMany: ((options: Parameters<NanokaModel<Fields>['findMany']>[0]) =>\n inner.findMany(adapter, options as any)) as NanokaModel<Fields>['findMany'],\n\n findAll: (options) => inner.findAll(adapter, options),\n\n findOne: ((\n idOrWhere: IdOrWhere<Fields>,\n options?: import('../model/types').FindOneOptions<Fields>,\n ) => inner.findOne(adapter, idOrWhere, options as any)) as NanokaModel<Fields>['findOne'],\n\n create: (data) => inner.create(adapter, data),\n\n update: (idOrWhere, data) => inner.update(adapter, idOrWhere, data),\n\n delete: (idOrWhere) => inner.delete(adapter, idOrWhere),\n }\n }\n\n return app\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nanokajs/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Thin wrapper over Hono + Drizzle + Zod for Cloudflare Workers + D1. 80% automatic, 20% explicit.",
|
|
6
6
|
"author": "Eiichiro Iriguchi <eiichiro_iriguchi@a-1ro.dev>",
|