hekireki 0.7.2 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -257,7 +257,7 @@ export const UserSchema = v.object({
257
257
  name: v.pipe(v.string(), v.minLength(1), v.maxLength(50)),
258
258
  })
259
259
 
260
- export type User = v.InferInput<typeof UserSchema>
260
+ export type User = v.InferOutput<typeof UserSchema>
261
261
 
262
262
  export const PostSchema = v.object({
263
263
  /**
@@ -278,21 +278,21 @@ export const PostSchema = v.object({
278
278
  userId: v.pipe(v.string(), v.uuid()),
279
279
  })
280
280
 
281
- export type Post = v.InferInput<typeof PostSchema>
281
+ export type Post = v.InferOutput<typeof PostSchema>
282
282
 
283
283
  export const UserRelationsSchema = v.object({
284
284
  ...UserSchema.entries,
285
285
  posts: v.array(PostSchema),
286
286
  })
287
287
 
288
- export type UserRelations = v.InferInput<typeof UserRelationsSchema>
288
+ export type UserRelations = v.InferOutput<typeof UserRelationsSchema>
289
289
 
290
290
  export const PostRelationsSchema = v.object({
291
291
  ...PostSchema.entries,
292
292
  user: UserSchema,
293
293
  })
294
294
 
295
- export type PostRelations = v.InferInput<typeof PostRelationsSchema>
295
+ export type PostRelations = v.InferOutput<typeof PostRelationsSchema>
296
296
  ```
297
297
 
298
298
  ### ArkType
@@ -329,26 +329,38 @@ export type Post = typeof PostSchema.infer
329
329
  import { Schema } from 'effect'
330
330
 
331
331
  export const UserSchema = Schema.Struct({
332
- /** Primary key */
332
+ /**
333
+ * Primary key
334
+ */
333
335
  id: Schema.UUID,
334
- /** Display name */
336
+ /**
337
+ * Display name
338
+ */
335
339
  name: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(50)),
336
340
  })
337
341
 
338
- export type User = Schema.Schema.Type<typeof UserSchema>
342
+ export type UserEncoded = typeof UserSchema.Encoded
339
343
 
340
344
  export const PostSchema = Schema.Struct({
341
- /** Primary key */
345
+ /**
346
+ * Primary key
347
+ */
342
348
  id: Schema.UUID,
343
- /** Article title */
349
+ /**
350
+ * Article title
351
+ */
344
352
  title: Schema.String.pipe(Schema.minLength(1), Schema.maxLength(100)),
345
- /** Body content (no length limit) */
353
+ /**
354
+ * Body content (no length limit)
355
+ */
346
356
  content: Schema.String,
347
- /** Foreign key referencing User.id */
357
+ /**
358
+ * Foreign key referencing User.id
359
+ */
348
360
  userId: Schema.UUID,
349
361
  })
350
362
 
351
- export type Post = Schema.Schema.Type<typeof PostSchema>
363
+ export type PostEncoded = typeof PostSchema.Encoded
352
364
  ```
353
365
 
354
366
  ### TypeBox
@@ -7,14 +7,8 @@ async function fmt(input) {
7
7
  singleQuote: true,
8
8
  semi: false
9
9
  });
10
- if (errors.length > 0) return {
11
- ok: false,
12
- error: errors.map((e) => e.message).join("\n")
13
- };
14
- return {
15
- ok: true,
16
- value: code
17
- };
10
+ if (errors.length > 0) throw new Error(errors.map((e) => e.message).join("\n"));
11
+ return code;
18
12
  }
19
13
 
20
14
  //#endregion
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { t as fmt } from "../../format-CzXgkLDe.js";
3
- import { c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, s as makeValidationExtractor, t as getBool } from "../../utils-COHZyQue.js";
4
- import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-ChsFqlYX.js";
2
+ import { t as fmt } from "../../format-DwiYldCm.js";
3
+ import { c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, s as makeValidationExtractor, t as getBool } from "../../utils-0tE5jzYR.js";
4
+ import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-DHllEbMR.js";
5
5
  import path from "node:path";
6
6
  import pkg from "@prisma/generator-helper";
7
7
 
@@ -66,12 +66,9 @@ async function main(options) {
66
66
  file: path.join(output, "index.ts")
67
67
  };
68
68
  const enableRelation = getBool(options.generator.config?.relation);
69
- const fmtResult = await fmt([ajv(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeAjvRelations) : ""].filter(Boolean).join("\n\n"));
70
- if (!fmtResult.ok) throw new Error(`Format error: ${fmtResult.error}`);
71
- const mkdirResult = await mkdir(resolved.dir);
72
- if (!mkdirResult.ok) throw new Error(`Failed to create directory: ${mkdirResult.error}`);
73
- const writeResult = await writeFile(resolved.file, fmtResult.value);
74
- if (!writeResult.ok) throw new Error(`Failed to write file: ${writeResult.error}`);
69
+ const code = await fmt([ajv(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeAjvRelations) : ""].filter(Boolean).join("\n\n"));
70
+ await mkdir(resolved.dir);
71
+ await writeFile(resolved.file, code);
75
72
  }
76
73
  generatorHandler({
77
74
  onManifest() {
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { t as fmt } from "../../format-CzXgkLDe.js";
3
- import { c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, l as schemaFromFields, s as makeValidationExtractor, t as getBool } from "../../utils-COHZyQue.js";
4
- import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-ChsFqlYX.js";
2
+ import { t as fmt } from "../../format-DwiYldCm.js";
3
+ import { c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, l as schemaFromFields, s as makeValidationExtractor, t as getBool } from "../../utils-0tE5jzYR.js";
4
+ import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-DHllEbMR.js";
5
5
  import path from "node:path";
6
6
  import pkg from "@prisma/generator-helper";
7
7
 
@@ -68,12 +68,9 @@ async function main(options) {
68
68
  file: path.join(output, "index.ts")
69
69
  };
70
70
  const enableRelation = getBool(options.generator.config?.relation);
71
- const fmtResult = await fmt([arktype(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeArktypeRelations) : ""].filter(Boolean).join("\n\n"));
72
- if (!fmtResult.ok) throw new Error(`Format error: ${fmtResult.error}`);
73
- const mkdirResult = await mkdir(resolved.dir);
74
- if (!mkdirResult.ok) throw new Error(`Failed to create directory: ${mkdirResult.error}`);
75
- const writeResult = await writeFile(resolved.file, fmtResult.value);
76
- if (!writeResult.ok) throw new Error(`Failed to write file: ${writeResult.error}`);
71
+ const code = await fmt([arktype(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeArktypeRelations) : ""].filter(Boolean).join("\n\n"));
72
+ await mkdir(resolved.dir);
73
+ await writeFile(resolved.file, code);
77
74
  }
78
75
  generatorHandler({
79
76
  onManifest() {
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { d as mkdir, f as writeFile, n as getString, p as writeFileBinary, u as stripAnnotations } from "../../utils-COHZyQue.js";
2
+ import { d as mkdir, f as writeFile, n as getString, p as writeFileBinary, u as stripAnnotations } from "../../utils-0tE5jzYR.js";
3
3
  import path from "node:path";
4
4
  import pkg from "@prisma/generator-helper";
5
5
  import { Resvg } from "@resvg/resvg-js";
@@ -129,23 +129,13 @@ function dbmlContent(datamodel, mapToDbSchema = false) {
129
129
  ].join("\n\n");
130
130
  }
131
131
  async function makeDbmlFile(outputDir, content, fileName) {
132
- const writeResult = await writeFile(`${outputDir}/${fileName}`, content);
133
- if (!writeResult.ok) return {
134
- ok: false,
135
- error: `Failed to write DBML: ${writeResult.error}`
136
- };
137
- return { ok: true };
132
+ await writeFile(`${outputDir}/${fileName}`, content);
138
133
  }
139
134
  async function makePng(outputDir, dbml, fileName) {
140
- return makePngFile(`${outputDir}/${fileName}`, dbml);
135
+ await makePngFile(`${outputDir}/${fileName}`, dbml);
141
136
  }
142
137
  async function makePngFile(outputPath, dbml) {
143
- const writeResult = await writeFileBinary(outputPath, new Resvg(run(dbml, "svg"), { font: { loadSystemFonts: true } }).render().asPng());
144
- if (!writeResult.ok) return {
145
- ok: false,
146
- error: `Failed to write PNG: ${writeResult.error}`
147
- };
148
- return { ok: true };
138
+ await writeFileBinary(outputPath, new Resvg(run(dbml, "svg"), { font: { loadSystemFonts: true } }).render().asPng());
149
139
  }
150
140
 
151
141
  //#endregion
@@ -158,15 +148,9 @@ async function main(options) {
158
148
  const mapToDbSchema = getString(config?.mapToDbSchema) !== "false";
159
149
  const content = dbmlContent(options.dmmf.datamodel, mapToDbSchema);
160
150
  if (output.endsWith(".png") || output.endsWith(".dbml")) {
161
- const mkdirResult = await mkdir(path.dirname(output));
162
- if (!mkdirResult.ok) throw new Error(`Failed to create directory: ${mkdirResult.error}`);
163
- if (output.endsWith(".png")) {
164
- const pngResult = await makePngFile(output, content);
165
- if (!pngResult.ok) throw new Error(pngResult.error);
166
- } else {
167
- const dbmlResult = await writeFile(output, content);
168
- if (!dbmlResult.ok) throw new Error(`Failed to write DBML: ${dbmlResult.error}`);
169
- }
151
+ await mkdir(path.dirname(output));
152
+ if (output.endsWith(".png")) await makePngFile(output, content);
153
+ else await writeFile(output, content);
170
154
  } else {
171
155
  const resolved = path.extname(output) ? {
172
156
  dir: path.dirname(output),
@@ -175,16 +159,10 @@ async function main(options) {
175
159
  dir: output,
176
160
  file: path.join(output, "schema.dbml")
177
161
  };
178
- const mkdirResult = await mkdir(resolved.dir);
179
- if (!mkdirResult.ok) throw new Error(`Failed to create directory: ${mkdirResult.error}`);
162
+ await mkdir(resolved.dir);
180
163
  const fileName = path.basename(resolved.file);
181
- if (fileName.endsWith(".png")) {
182
- const pngResult = await makePng(resolved.dir, content, fileName);
183
- if (!pngResult.ok) throw new Error(pngResult.error);
184
- } else {
185
- const dbmlResult = await makeDbmlFile(resolved.dir, content, fileName);
186
- if (!dbmlResult.ok) throw new Error(dbmlResult.error);
187
- }
164
+ if (fileName.endsWith(".png")) await makePng(resolved.dir, content, fileName);
165
+ else await makeDbmlFile(resolved.dir, content, fileName);
188
166
  }
189
167
  }
190
168
  generatorHandler({
@@ -33,21 +33,6 @@ const transformDMMF = (dmmf) => {
33
33
  };
34
34
  };
35
35
 
36
- //#endregion
37
- //#region src/generator/docs/generator/helpers.ts
38
- const capitalize = (str) => str[0].toUpperCase() + str.slice(1);
39
- const lowerCase = (name) => name.substring(0, 1).toLowerCase() + name.substring(1);
40
- const primitiveTypes = [
41
- "String",
42
- "Boolean",
43
- "Int",
44
- "Float",
45
- "Json",
46
- "DateTime",
47
- "Null"
48
- ];
49
- const isScalarType = (type) => primitiveTypes.includes(type);
50
-
51
36
  //#endregion
52
37
  //#region src/generator/docs/styles.ts
53
38
  const globalCss = css`
@@ -76,16 +61,24 @@ const globalCss = css`
76
61
  --code-bg: #374151;
77
62
  --code-color: #e5e7eb;
78
63
  }
79
- * { box-sizing: border-box; }
64
+ * {
65
+ box-sizing: border-box;
66
+ }
80
67
  body {
81
68
  margin: 0;
82
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
69
+ font-family:
70
+ -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
83
71
  background-color: var(--bg-primary);
84
72
  color: var(--text-primary);
85
73
  min-height: 100vh;
86
74
  }
87
- a { color: var(--link-color); text-decoration: none; }
88
- a:hover { text-decoration: underline; }
75
+ a {
76
+ color: var(--link-color);
77
+ text-decoration: none;
78
+ }
79
+ a:hover {
80
+ text-decoration: underline;
81
+ }
89
82
  }
90
83
  `;
91
84
  const containerClass = css`
@@ -218,7 +211,8 @@ const codeBlockClass = css`
218
211
  padding: 1em;
219
212
  border-radius: 0.5em;
220
213
  overflow: auto;
221
- font-family: 'SFMono-Regular', Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;
214
+ font-family:
215
+ 'SFMono-Regular', Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;
222
216
  font-size: 14px;
223
217
  line-height: 1.5;
224
218
  margin: 0;
@@ -261,6 +255,21 @@ const ml4Class = css`
261
255
  margin-left: 1rem;
262
256
  `;
263
257
 
258
+ //#endregion
259
+ //#region src/generator/docs/generator/helpers.ts
260
+ const capitalize = (str) => str[0].toUpperCase() + str.slice(1);
261
+ const lowerCase = (name) => name.substring(0, 1).toLowerCase() + name.substring(1);
262
+ const primitiveTypes = [
263
+ "String",
264
+ "Boolean",
265
+ "Int",
266
+ "Float",
267
+ "Json",
268
+ "DateTime",
269
+ "Null"
270
+ ];
271
+ const isScalarType = (type) => primitiveTypes.includes(type);
272
+
264
273
  //#endregion
265
274
  //#region src/generator/docs/generator/apitypes.tsx
266
275
  const TypeRefLink = ({ typeRef, kind }) => {
@@ -940,14 +949,14 @@ const MainContent = ({ models, types }) => /* @__PURE__ */ jsxs("div", {
940
949
  class: mainContentClass,
941
950
  children: [models, types]
942
951
  });
943
- const generateHTML = async (data) => {
944
- return "<!DOCTYPE html>" + await (/* @__PURE__ */ jsx(Layout, { children: /* @__PURE__ */ jsxs("div", {
952
+ const generateHTML = (data) => {
953
+ return `<!DOCTYPE html>${(/* @__PURE__ */ jsx(Layout, { children: /* @__PURE__ */ jsxs("div", {
945
954
  class: containerClass,
946
955
  children: [/* @__PURE__ */ jsx(Sidebar, { toc: createTOC(data) }), /* @__PURE__ */ jsx(MainContent, {
947
956
  models: createModels(data),
948
957
  types: createTypes(data)
949
958
  })]
950
- }) })).toString();
959
+ }) })).toString()}`;
951
960
  };
952
961
 
953
962
  //#endregion
@@ -963,7 +972,7 @@ generatorHandler({
963
972
  async onGenerate(options) {
964
973
  if (!options.generator.isCustomOutput || !options.generator.output?.value) throw new Error("output is required for Hekireki-Docs. Please specify output in your generator config.");
965
974
  const output = options.generator.output.value;
966
- const html = await generateHTML(transformDMMF(options.dmmf));
975
+ const html = generateHTML(transformDMMF(options.dmmf));
967
976
  await fs.mkdir(output, { recursive: true });
968
977
  await fs.writeFile(path.join(output, "index.html"), html);
969
978
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as fmt } from "../../format-CzXgkLDe.js";
3
- import { d as mkdir, f as writeFile, o as makeSnakeCase } from "../../utils-COHZyQue.js";
2
+ import { t as fmt } from "../../format-DwiYldCm.js";
3
+ import { d as mkdir, f as writeFile, o as makeSnakeCase } from "../../utils-0tE5jzYR.js";
4
4
  import path from "node:path";
5
5
  import pkg from "@prisma/generator-helper";
6
6
 
@@ -23,7 +23,7 @@ const MYSQL_SCALAR_MAP = {
23
23
  Float: "double()",
24
24
  Decimal: "decimal()",
25
25
  Boolean: "boolean()",
26
- DateTime: "datetime()",
26
+ DateTime: "datetime({ fsp: 3 })",
27
27
  Json: "json()",
28
28
  Bytes: "binary()"
29
29
  };
@@ -34,7 +34,7 @@ const SQLITE_SCALAR_MAP = {
34
34
  Float: "real()",
35
35
  Decimal: "numeric()",
36
36
  Boolean: "integer({ mode: 'boolean' })",
37
- DateTime: "integer({ mode: 'timestamp' })",
37
+ DateTime: "integer({ mode: 'timestamp_ms' })",
38
38
  Json: "text({ mode: 'json' })",
39
39
  Bytes: "blob()"
40
40
  };
@@ -88,8 +88,8 @@ function mysqlNativeType(name, args) {
88
88
  }
89
89
  case "Date": return "date()";
90
90
  case "Time": return args[0] ? `time({ fsp: ${args[0]} })` : "time()";
91
- case "DateTime": return args[0] ? `datetime({ fsp: ${args[0]} })` : "datetime()";
92
- case "Timestamp": return args[0] ? `timestamp({ fsp: ${args[0]} })` : "timestamp()";
91
+ case "DateTime": return `datetime({ fsp: ${args[0] ?? 3} })`;
92
+ case "Timestamp": return `timestamp({ fsp: ${args[0] ?? 3} })`;
93
93
  case "Json": return "json()";
94
94
  case "Binary": return args[0] ? `binary({ length: ${args[0]} })` : "binary()";
95
95
  case "VarBinary": return args[0] ? `varbinary({ length: ${args[0]} })` : "varbinary()";
@@ -169,36 +169,117 @@ function makeColumnExpr(field, provider, imports, enums) {
169
169
  const rest = baseExpr.slice(parenIdx + 1);
170
170
  return rest === ")" ? `${baseFnName}('${colName}')` : `${baseFnName}('${colName}', ${rest}`;
171
171
  }
172
- function makeDefaultChain(dflt, fieldType, provider, imports) {
173
- if (dflt === void 0 || dflt === null) return "";
172
+ function resolveDefaultValue(dflt, fieldType, provider) {
173
+ if (dflt === void 0 || dflt === null) return {
174
+ chain: "",
175
+ needsSql: false,
176
+ needsCuid: false
177
+ };
174
178
  if (isFieldDefault(dflt)) switch (dflt.name) {
175
- case "autoincrement": return "";
179
+ case "autoincrement": return {
180
+ chain: "",
181
+ needsSql: false,
182
+ needsCuid: false
183
+ };
176
184
  case "now":
177
- if (provider === "sqlite") {
178
- imports.addOrm("sql");
179
- return ".default(sql`(unixepoch())`)";
180
- }
181
- if (provider === "mysql") {
182
- imports.addOrm("sql");
183
- return ".default(sql`now()`)";
184
- }
185
- return ".defaultNow()";
186
- case "uuid": return ".$defaultFn(() => crypto.randomUUID())";
187
- case "cuid":
188
- imports.addExternal("@paralleldrive/cuid2", "createId");
189
- return ".$defaultFn(() => createId())";
185
+ if (provider === "sqlite") return {
186
+ chain: ".default(sql`(unixepoch() * 1000)`)",
187
+ needsSql: true,
188
+ needsCuid: false
189
+ };
190
+ if (provider === "mysql") return {
191
+ chain: ".default(sql`CURRENT_TIMESTAMP(3)`)",
192
+ needsSql: true,
193
+ needsCuid: false
194
+ };
195
+ return {
196
+ chain: ".defaultNow()",
197
+ needsSql: false,
198
+ needsCuid: false
199
+ };
200
+ case "uuid": return {
201
+ chain: ".$defaultFn(() => crypto.randomUUID())",
202
+ needsSql: false,
203
+ needsCuid: false
204
+ };
205
+ case "cuid": return {
206
+ chain: ".$defaultFn(() => createId())",
207
+ needsSql: false,
208
+ needsCuid: true
209
+ };
190
210
  case "dbgenerated":
191
- if (typeof dflt.args[0] === "string") {
192
- imports.addOrm("sql");
193
- return `.default(sql\`${dflt.args[0]}\`)`;
194
- }
195
- return "";
196
- default: return "";
211
+ if (typeof dflt.args[0] === "string") return {
212
+ chain: `.default(sql\`${dflt.args[0]}\`)`,
213
+ needsSql: true,
214
+ needsCuid: false
215
+ };
216
+ return {
217
+ chain: "",
218
+ needsSql: false,
219
+ needsCuid: false
220
+ };
221
+ default: return {
222
+ chain: "",
223
+ needsSql: false,
224
+ needsCuid: false
225
+ };
197
226
  }
198
- if (typeof dflt === "string") return `.default('${dflt}')`;
199
- if (typeof dflt === "number") return fieldType === "Decimal" ? `.default('${dflt}')` : `.default(${dflt})`;
200
- if (typeof dflt === "boolean") return `.default(${dflt})`;
201
- return "";
227
+ if (typeof dflt === "string") return {
228
+ chain: `.default('${dflt}')`,
229
+ needsSql: false,
230
+ needsCuid: false
231
+ };
232
+ if (typeof dflt === "number") return {
233
+ chain: fieldType === "Decimal" ? `.default('${dflt}')` : `.default(${dflt})`,
234
+ needsSql: false,
235
+ needsCuid: false
236
+ };
237
+ if (typeof dflt === "boolean") return {
238
+ chain: `.default(${dflt})`,
239
+ needsSql: false,
240
+ needsCuid: false
241
+ };
242
+ return {
243
+ chain: "",
244
+ needsSql: false,
245
+ needsCuid: false
246
+ };
247
+ }
248
+ function resolveUpdatedAtDefault(provider) {
249
+ if (provider === "sqlite") return {
250
+ chain: ".default(sql`(unixepoch() * 1000)`)",
251
+ needsSql: true
252
+ };
253
+ if (provider === "mysql") return {
254
+ chain: ".default(sql`CURRENT_TIMESTAMP(3)`)",
255
+ needsSql: true
256
+ };
257
+ return {
258
+ chain: ".defaultNow()",
259
+ needsSql: false
260
+ };
261
+ }
262
+ function makeDefaultChain(dflt, fieldType, provider, imports) {
263
+ const result = resolveDefaultValue(dflt, fieldType, provider);
264
+ if (result.needsSql) imports.addOrm("sql");
265
+ if (result.needsCuid) imports.addExternal("@paralleldrive/cuid2", "createId");
266
+ return result.chain;
267
+ }
268
+ const PRISMA_ACTION_MAP = {
269
+ Cascade: "cascade",
270
+ SetNull: "set null",
271
+ Restrict: "restrict",
272
+ NoAction: "no action",
273
+ SetDefault: "set default"
274
+ };
275
+ function makeFkReference(field, model) {
276
+ const relField = model.fields.find((f) => f.kind === "object" && f.relationFromFields && f.relationFromFields.includes(field.name));
277
+ if (!(relField?.relationFromFields && relField.relationToFields)) return "";
278
+ const targetVar = toCamelCase(relField.type);
279
+ const toCol = relField.relationToFields[0] ?? "id";
280
+ const onDelete = relField.relationOnDelete;
281
+ const drizzleAction = onDelete ? PRISMA_ACTION_MAP[onDelete] : void 0;
282
+ return `.references(() => ${targetVar}.${toCol}${drizzleAction ? `, { onDelete: '${drizzleAction}' }` : ""})`;
202
283
  }
203
284
  function makeColumn(field, model, provider, imports, enums) {
204
285
  if (field.kind === "object") return null;
@@ -210,24 +291,29 @@ function makeColumn(field, model, provider, imports, enums) {
210
291
  field.isId && !hasCompositePK ? isAutoincrement && provider === "sqlite" ? ".primaryKey({ autoIncrement: true })" : ".primaryKey()" : "",
211
292
  field.isRequired && !field.isId && !(isAutoincrement && provider === "postgresql") ? ".notNull()" : "",
212
293
  field.isUnique ? ".unique()" : "",
213
- isAutoincrement ? provider === "mysql" ? ".autoincrement()" : "" : makeDefaultChain(field.default, field.type, provider, imports),
294
+ makeFkReference(field, model),
295
+ isAutoincrement ? provider === "mysql" ? ".autoincrement()" : "" : field.isUpdatedAt && (field.default === void 0 || field.default === null) ? (() => {
296
+ const r = resolveUpdatedAtDefault(provider);
297
+ if (r.needsSql) imports.addOrm("sql");
298
+ return r.chain;
299
+ })() : makeDefaultChain(field.default, field.type, provider, imports),
214
300
  field.isUpdatedAt ? ".$onUpdate(() => new Date())" : "",
215
301
  field.isList && field.kind === "scalar" && provider === "postgresql" ? ".array()" : ""
216
302
  ].join("");
217
303
  return `${field.name}: ${colExpr}${chain}`;
218
304
  }
219
- function makeCompositeConstraints(model, imports, indexes) {
305
+ function makeCompositeConstraints(model, imports, indexes, tableName) {
220
306
  const pkLine = model.primaryKey ? (() => {
221
307
  imports.addCore("primaryKey");
222
308
  return `primaryKey({ columns: [${model.primaryKey.fields.map((f) => `table.${f}`).join(", ")}] })`;
223
309
  })() : null;
224
- const uniqueLines = model.uniqueFields.map((fields) => {
310
+ const uniqueLines = model.uniqueFields.filter((fields) => fields.length > 1).map((fields) => {
225
311
  imports.addCore("unique");
226
312
  return `unique().on(${fields.map((f) => `table.${f}`).join(", ")})`;
227
313
  });
228
314
  const indexLines = indexes.filter((idx) => idx.model === model.name && (idx.type === "normal" || idx.type === "fulltext")).map((idx) => {
229
315
  imports.addCore("index");
230
- return `index('${idx.dbName ?? idx.name ?? `idx_${idx.fields.map((f) => f.name).join("_")}`}').on(${idx.fields.map((f) => `table.${f.name}`).join(", ")})`;
316
+ return `index('${idx.dbName ?? idx.name ?? `idx_${tableName}_${idx.fields.map((f) => f.name).join("_")}`}').on(${idx.fields.map((f) => `table.${f.name}`).join(", ")})`;
231
317
  });
232
318
  const all = [
233
319
  pkLine,
@@ -242,7 +328,7 @@ function makeTable(model, provider, imports, enums, indexes) {
242
328
  const varName = toCamelCase(model.name);
243
329
  const tableName = model.dbName ?? makeSnakeCase(model.name);
244
330
  const columns = model.fields.map((field) => makeColumn(field, model, provider, imports, enums)).filter((c) => c !== null).join(", ");
245
- const constraints = makeCompositeConstraints(model, imports, indexes);
331
+ const constraints = makeCompositeConstraints(model, imports, indexes, tableName);
246
332
  return constraints ? `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} }, (table) => [${constraints}])` : `export const ${varName} = ${tableFunc}('${tableName}', { ${columns} })`;
247
333
  }
248
334
  function makeRelationField(field, model, _models, relFields) {
@@ -312,12 +398,9 @@ async function main(options) {
312
398
  file: path.join(output, "schema.ts")
313
399
  };
314
400
  const provider = options.datasources[0]?.activeProvider ?? "postgresql";
315
- const fmtResult = await fmt(drizzleSchema(options.dmmf.datamodel, provider, options.dmmf.datamodel.indexes));
316
- if (!fmtResult.ok) throw new Error(`Format error: ${fmtResult.error}`);
317
- const mkdirResult = await mkdir(resolved.dir);
318
- if (!mkdirResult.ok) throw new Error(`Failed to create directory: ${mkdirResult.error}`);
319
- const writeResult = await writeFile(resolved.file, fmtResult.value);
320
- if (!writeResult.ok) throw new Error(`Failed to write file: ${writeResult.error}`);
401
+ const formatted = await fmt(drizzleSchema(options.dmmf.datamodel, provider, options.dmmf.datamodel.indexes));
402
+ await mkdir(resolved.dir);
403
+ await writeFile(resolved.file, formatted);
321
404
  }
322
405
  generatorHandler({
323
406
  onManifest() {
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { d as mkdir, f as writeFile, o as makeSnakeCase } from "../../utils-COHZyQue.js";
2
+ import { d as mkdir, f as writeFile, o as makeSnakeCase } from "../../utils-0tE5jzYR.js";
3
3
  import { join } from "node:path";
4
4
  import pkg from "@prisma/generator-helper";
5
5
 
@@ -148,6 +148,7 @@ function getAssociations(model, allModels) {
148
148
  };
149
149
  }
150
150
  function ectoSchemas(models, app, allModels, enums) {
151
+ const appName = Array.isArray(app) ? app.join(".") : app;
151
152
  const contextModels = allModels ?? models;
152
153
  return models.map((model) => {
153
154
  const idField = model.fields.find((f) => f.isId);
@@ -181,9 +182,9 @@ function ectoSchemas(models, app, allModels, enums) {
181
182
  const typeSpec = f.isList ? `[${baseTypeSpec}]` : baseTypeSpec;
182
183
  return `${makeSnakeCase(f.name)}: ${typeSpec}${nullSuffix}`;
183
184
  }),
184
- ...associations.belongsTo.map((a) => `${makeSnakeCase(a.name)}: ${app}.${a.targetModel}.t() | nil`),
185
- ...associations.hasOne.map((a) => `${makeSnakeCase(a.name)}: ${app}.${a.targetModel}.t() | nil`),
186
- ...associations.hasMany.map((a) => `${makeSnakeCase(a.name)}: [${app}.${a.targetModel}.t()]`)
185
+ ...associations.belongsTo.map((a) => `${makeSnakeCase(a.name)}: ${appName}.${a.targetModel}.t() | nil`),
186
+ ...associations.hasOne.map((a) => `${makeSnakeCase(a.name)}: ${appName}.${a.targetModel}.t() | nil`),
187
+ ...associations.hasMany.map((a) => `${makeSnakeCase(a.name)}: [${appName}.${a.targetModel}.t()]`)
187
188
  ];
188
189
  const typeSpecLines = [
189
190
  " @type t :: %__MODULE__{",
@@ -233,18 +234,18 @@ function ectoSchemas(models, app, allModels, enums) {
233
234
  if (needsSource || isPkField) opts.push("define_field: false");
234
235
  if (a.fkType && (!useBinaryId || a.fkType !== "binary_id")) opts.push(`type: :${a.fkType}`);
235
236
  if (a.references !== "id") opts.push(`references: :${a.references}`);
236
- return ` belongs_to(:${snakeAssocName}, ${app}.${a.targetModel}, ${opts.join(", ")})`;
237
+ return ` belongs_to(:${snakeAssocName}, ${appName}.${a.targetModel}, ${opts.join(", ")})`;
237
238
  });
238
239
  const hasOneLines = associations.hasOne.map((a) => {
239
240
  const snakeFk = makeSnakeCase(a.foreignKey);
240
- return ` has_one(:${makeSnakeCase(a.name)}, ${app}.${a.targetModel}, foreign_key: :${snakeFk})`;
241
+ return ` has_one(:${makeSnakeCase(a.name)}, ${appName}.${a.targetModel}, foreign_key: :${snakeFk})`;
241
242
  });
242
243
  const hasManyLines = associations.hasMany.map((a) => {
243
244
  const snakeFk = makeSnakeCase(a.foreignKey);
244
- return ` has_many(:${makeSnakeCase(a.name)}, ${app}.${a.targetModel}, foreign_key: :${snakeFk})`;
245
+ return ` has_many(:${makeSnakeCase(a.name)}, ${appName}.${a.targetModel}, foreign_key: :${snakeFk})`;
245
246
  });
246
247
  return [
247
- `defmodule ${app}.${model.name} do`,
248
+ `defmodule ${appName}.${model.name} do`,
248
249
  " use Ecto.Schema",
249
250
  ...model.documentation ? [
250
251
  ` @moduledoc """`,
@@ -270,20 +271,14 @@ function ectoSchemas(models, app, allModels, enums) {
270
271
  }).filter(Boolean).join("\n\n");
271
272
  }
272
273
  async function writeEctoSchemasToFiles(models, app, outDir, enums) {
273
- const mkdirResult = await mkdir(outDir);
274
- if (!mkdirResult.ok) return mkdirResult;
274
+ await mkdir(outDir);
275
275
  for (const model of models) {
276
276
  const code = ectoSchemas([model], app, models, enums);
277
277
  if (!code.trim()) continue;
278
278
  const filePath = join(outDir, `${makeSnakeCase(model.name)}.ex`);
279
- const writeResult = await writeFile(filePath, code);
280
- if (!writeResult.ok) return writeResult;
279
+ await writeFile(filePath, code);
281
280
  console.log(`wrote ${filePath}`);
282
281
  }
283
- return {
284
- ok: true,
285
- value: void 0
286
- };
287
282
  }
288
283
 
289
284
  //#endregion
@@ -294,8 +289,7 @@ async function main(options) {
294
289
  const output = options.generator.output.value;
295
290
  const app = options.generator.config?.app ?? "MyApp";
296
291
  const enums = options.dmmf.datamodel.enums;
297
- const result = await writeEctoSchemasToFiles(options.dmmf.datamodel.models, app, output, enums);
298
- if (!result.ok) throw new Error(`Failed to write Ecto schemas: ${result.error}`);
292
+ await writeEctoSchemasToFiles(options.dmmf.datamodel.models, app, output, enums);
299
293
  }
300
294
  generatorHandler({
301
295
  onManifest() {
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import { t as fmt } from "../../format-CzXgkLDe.js";
3
- import { c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, l as schemaFromFields, s as makeValidationExtractor, t as getBool } from "../../utils-COHZyQue.js";
4
- import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-ChsFqlYX.js";
2
+ import { t as fmt } from "../../format-DwiYldCm.js";
3
+ import { c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, l as schemaFromFields, s as makeValidationExtractor, t as getBool } from "../../utils-0tE5jzYR.js";
4
+ import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-DHllEbMR.js";
5
5
  import path from "node:path";
6
6
  import pkg from "@prisma/generator-helper";
7
7
 
8
8
  //#region src/helper/effect.ts
9
9
  function makeEffectInfer(modelName) {
10
- return `export type ${modelName} = Schema.Schema.Type<typeof ${modelName}Schema>`;
10
+ return `export type ${modelName}Encoded = typeof ${modelName}Schema.Encoded`;
11
11
  }
12
12
  function makeEffectSchema(modelName, fields) {
13
13
  return `export const ${modelName}Schema = Schema.Struct({\n${fields}\n})`;
14
14
  }
15
15
  function makeEffectProperties(fields, comment) {
16
16
  return fields.map((field) => {
17
- return `${comment && field.comment.length > 0 ? `${field.comment.map((c) => ` /** ${c} */`).join("\n")}\n` : ""} ${field.fieldName}: ${field.validation ?? "Schema.Unknown"},`;
17
+ return `${comment && field.comment.length > 0 ? ` /**\n${field.comment.map((c) => ` * ${c}`).join("\n")}\n */\n` : ""} ${field.fieldName}: ${field.validation ?? "Schema.Unknown"},`;
18
18
  }).join("\n");
19
19
  }
20
20
  function makeEffectEnumExpression(values) {
@@ -37,7 +37,7 @@ function makeEffectSchemas(modelFields, comment) {
37
37
  function makeEffectRelations(model, relProps, options) {
38
38
  if (relProps.length === 0) return null;
39
39
  const fields = `${`...${model.name}Schema.fields,`}${relProps.map((r) => `${r.key}:${r.isMany ? `Schema.Array(${r.targetModel}Schema)` : `${r.targetModel}Schema`},`).join("")}`;
40
- const typeLine = options?.includeType ? `\n\nexport type ${model.name}Relations = Schema.Schema.Type<typeof ${model.name}RelationsSchema>` : "";
40
+ const typeLine = options?.includeType ? `\n\nexport type ${model.name}RelationsEncoded = typeof ${model.name}RelationsSchema.Encoded` : "";
41
41
  return `export const ${model.name}RelationsSchema = Schema.Struct({${fields}})${typeLine}`;
42
42
  }
43
43
  function effect(models, type, comment, enums) {
@@ -68,12 +68,9 @@ async function main(options) {
68
68
  file: path.join(output, "index.ts")
69
69
  };
70
70
  const enableRelation = getBool(options.generator.config?.relation);
71
- const fmtResult = await fmt([effect(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeEffectRelations) : ""].filter(Boolean).join("\n\n"));
72
- if (!fmtResult.ok) throw new Error(`Format error: ${fmtResult.error}`);
73
- const mkdirResult = await mkdir(resolved.dir);
74
- if (!mkdirResult.ok) throw new Error(`Failed to create directory: ${mkdirResult.error}`);
75
- const writeResult = await writeFile(resolved.file, fmtResult.value);
76
- if (!writeResult.ok) throw new Error(`Failed to write file: ${writeResult.error}`);
71
+ const code = await fmt([effect(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeEffectRelations) : ""].filter(Boolean).join("\n\n"));
72
+ await mkdir(resolved.dir);
73
+ await writeFile(resolved.file, code);
77
74
  }
78
75
  generatorHandler({
79
76
  onManifest() {
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { d as mkdir, f as writeFile, n as getString, o as makeSnakeCase } from "../../utils-COHZyQue.js";
2
+ import { d as mkdir, f as writeFile, n as getString, o as makeSnakeCase } from "../../utils-0tE5jzYR.js";
3
3
  import path, { dirname } from "node:path";
4
4
  import pkg from "@prisma/generator-helper";
5
5
 
@@ -332,15 +332,9 @@ function generateGormModels(models, enums, indexes, packageName = "model") {
332
332
  return lines.join("\n");
333
333
  }
334
334
  async function writeGormFile(models, outPath, enums, indexes, packageName = "model") {
335
- const mkdirResult = await mkdir(dirname(outPath));
336
- if (!mkdirResult.ok) return mkdirResult;
337
- const writeResult = await writeFile(outPath, generateGormModels(models, enums, indexes, packageName));
338
- if (!writeResult.ok) return writeResult;
335
+ await mkdir(dirname(outPath));
336
+ await writeFile(outPath, generateGormModels(models, enums, indexes, packageName));
339
337
  console.log(`wrote ${outPath}`);
340
- return {
341
- ok: true,
342
- value: void 0
343
- };
344
338
  }
345
339
 
346
340
  //#endregion
@@ -353,8 +347,7 @@ async function main(options) {
353
347
  const packageName = getString(options.generator.config.package, "model");
354
348
  const enums = options.dmmf.datamodel.enums;
355
349
  const indexes = options.dmmf.datamodel.indexes;
356
- const result = await writeGormFile(options.dmmf.datamodel.models, resolved, enums, indexes, packageName);
357
- if (!result.ok) throw new Error(`Failed to write GORM models: ${result.error}`);
350
+ await writeGormFile(options.dmmf.datamodel.models, resolved, enums, indexes, packageName);
358
351
  }
359
352
  generatorHandler({
360
353
  onManifest() {
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { d as mkdir, f as writeFile, u as stripAnnotations } from "../../utils-COHZyQue.js";
2
+ import { d as mkdir, f as writeFile, u as stripAnnotations } from "../../utils-0tE5jzYR.js";
3
3
  import path from "node:path";
4
4
  import pkg from "@prisma/generator-helper";
5
5
 
@@ -68,10 +68,8 @@ async function main(options) {
68
68
  dir: output,
69
69
  file: path.join(output, "ER.md")
70
70
  };
71
- const mkdirResult = await mkdir(resolved.dir);
72
- if (!mkdirResult.ok) throw new Error(`Failed to create directory: ${mkdirResult.error}`);
73
- const writeResult = await writeFile(resolved.file, content.join("\n"));
74
- if (!writeResult.ok) throw new Error(`Failed to write file: ${writeResult.error}`);
71
+ await mkdir(resolved.dir);
72
+ await writeFile(resolved.file, content.join("\n"));
75
73
  }
76
74
  generatorHandler({
77
75
  onManifest() {
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { d as mkdir, f as writeFile, n as getString, o as makeSnakeCase } from "../../utils-COHZyQue.js";
2
+ import { d as mkdir, f as writeFile, n as getString, o as makeSnakeCase } from "../../utils-0tE5jzYR.js";
3
3
  import { join } from "node:path";
4
4
  import pkg from "@prisma/generator-helper";
5
5
 
@@ -349,8 +349,7 @@ function generatePreludeRs(models) {
349
349
  }).join("\n")}\n`;
350
350
  }
351
351
  async function writeSeaOrmFiles(models, outDir, enums, serde = {}) {
352
- const mkdirResult = await mkdir(outDir);
353
- if (!mkdirResult.ok) return mkdirResult;
352
+ await mkdir(outDir);
354
353
  const moduleNames = [];
355
354
  const m2mJunctions = /* @__PURE__ */ new Set();
356
355
  const m2mPairs = [];
@@ -377,8 +376,7 @@ async function writeSeaOrmFiles(models, outDir, enums, serde = {}) {
377
376
  ""
378
377
  ].join("\n");
379
378
  const filePath = join(outDir, `${moduleName}.rs`);
380
- const writeResult = await writeFile(filePath, code);
381
- if (!writeResult.ok) return writeResult;
379
+ await writeFile(filePath, code);
382
380
  moduleNames.push(moduleName);
383
381
  console.log(`wrote ${filePath}`);
384
382
  }
@@ -387,8 +385,7 @@ async function writeSeaOrmFiles(models, outDir, enums, serde = {}) {
387
385
  if (!code.trim()) continue;
388
386
  const moduleName = toModuleName(model.name);
389
387
  const filePath = join(outDir, `${moduleName}.rs`);
390
- const writeResult = await writeFile(filePath, code);
391
- if (!writeResult.ok) return writeResult;
388
+ await writeFile(filePath, code);
392
389
  moduleNames.push(moduleName);
393
390
  console.log(`wrote ${filePath}`);
394
391
  }
@@ -396,27 +393,20 @@ async function writeSeaOrmFiles(models, outDir, enums, serde = {}) {
396
393
  const moduleName = toSnakeCase(`${pair.left}To${pair.right}`);
397
394
  const code = generateM2MEntity(pair.left, pair.right, models, serde);
398
395
  const filePath = join(outDir, `${moduleName}.rs`);
399
- const writeResult = await writeFile(filePath, code);
400
- if (!writeResult.ok) return writeResult;
396
+ await writeFile(filePath, code);
401
397
  moduleNames.push(moduleName);
402
398
  console.log(`wrote ${filePath}`);
403
399
  }
404
400
  const preludeCode = generatePreludeRs(models);
405
401
  const preludePath = join(outDir, "prelude.rs");
406
- const preludeResult = await writeFile(preludePath, preludeCode);
407
- if (!preludeResult.ok) return preludeResult;
402
+ await writeFile(preludePath, preludeCode);
408
403
  moduleNames.push("prelude");
409
404
  console.log(`wrote ${preludePath}`);
410
405
  moduleNames.sort();
411
406
  const modCode = generateModRs(moduleNames);
412
407
  const modPath = join(outDir, "mod.rs");
413
- const modResult = await writeFile(modPath, modCode);
414
- if (!modResult.ok) return modResult;
408
+ await writeFile(modPath, modCode);
415
409
  console.log(`wrote ${modPath}`);
416
- return {
417
- ok: true,
418
- value: void 0
419
- };
420
410
  }
421
411
 
422
412
  //#endregion
@@ -427,8 +417,7 @@ async function main(options) {
427
417
  const output = options.generator.output.value;
428
418
  const serde = { renameAll: getString(options.generator.config?.renameAll) };
429
419
  const enums = options.dmmf.datamodel.enums;
430
- const result = await writeSeaOrmFiles(options.dmmf.datamodel.models, output, enums, serde);
431
- if (!result.ok) throw new Error(`Failed to write SeaORM entities: ${result.error}`);
420
+ await writeSeaOrmFiles(options.dmmf.datamodel.models, output, enums, serde);
432
421
  }
433
422
  generatorHandler({
434
423
  onManifest() {
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { d as mkdir, f as writeFile, o as makeSnakeCase } from "../../utils-COHZyQue.js";
2
+ import { d as mkdir, f as writeFile, o as makeSnakeCase } from "../../utils-0tE5jzYR.js";
3
3
  import path, { dirname } from "node:path";
4
4
  import pkg from "@prisma/generator-helper";
5
5
 
@@ -421,15 +421,9 @@ function generateSingleFile(models, enums, indexes) {
421
421
  ].join("\n");
422
422
  }
423
423
  async function writeSQLAlchemyFile(models, outPath, enums, indexes) {
424
- const mkdirResult = await mkdir(dirname(outPath));
425
- if (!mkdirResult.ok) return mkdirResult;
426
- const writeResult = await writeFile(outPath, generateSingleFile(models, enums, indexes));
427
- if (!writeResult.ok) return writeResult;
424
+ await mkdir(dirname(outPath));
425
+ await writeFile(outPath, generateSingleFile(models, enums, indexes));
428
426
  console.log(`wrote ${outPath}`);
429
- return {
430
- ok: true,
431
- value: void 0
432
- };
433
427
  }
434
428
 
435
429
  //#endregion
@@ -441,8 +435,7 @@ async function main(options) {
441
435
  const resolved = path.extname(output) ? output : path.join(output, "models.py");
442
436
  const enums = options.dmmf.datamodel.enums;
443
437
  const indexes = options.dmmf.datamodel.indexes;
444
- const result = await writeSQLAlchemyFile(options.dmmf.datamodel.models, resolved, enums, indexes);
445
- if (!result.ok) throw new Error(`Failed to write SQLAlchemy models: ${result.error}`);
438
+ await writeSQLAlchemyFile(options.dmmf.datamodel.models, resolved, enums, indexes);
446
439
  }
447
440
  generatorHandler({
448
441
  onManifest() {
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { t as fmt } from "../../format-CzXgkLDe.js";
3
- import { c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, l as schemaFromFields, s as makeValidationExtractor, t as getBool } from "../../utils-COHZyQue.js";
4
- import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-ChsFqlYX.js";
2
+ import { t as fmt } from "../../format-DwiYldCm.js";
3
+ import { c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, l as schemaFromFields, s as makeValidationExtractor, t as getBool } from "../../utils-0tE5jzYR.js";
4
+ import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-DHllEbMR.js";
5
5
  import path from "node:path";
6
6
  import pkg from "@prisma/generator-helper";
7
7
 
@@ -72,12 +72,9 @@ async function main(options) {
72
72
  file: path.join(output, "index.ts")
73
73
  };
74
74
  const enableRelation = getBool(options.generator.config?.relation);
75
- const fmtResult = await fmt([typebox(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeTypeBoxRelations) : ""].filter(Boolean).join("\n\n"));
76
- if (!fmtResult.ok) throw new Error(`Format error: ${fmtResult.error}`);
77
- const mkdirResult = await mkdir(resolved.dir);
78
- if (!mkdirResult.ok) throw new Error(`Failed to create directory: ${mkdirResult.error}`);
79
- const writeResult = await writeFile(resolved.file, fmtResult.value);
80
- if (!writeResult.ok) throw new Error(`Failed to write file: ${writeResult.error}`);
75
+ const code = await fmt([typebox(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeTypeBoxRelations) : ""].filter(Boolean).join("\n\n"));
76
+ await mkdir(resolved.dir);
77
+ await writeFile(resolved.file, code);
81
78
  }
82
79
  generatorHandler({
83
80
  onManifest() {
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { t as fmt } from "../../format-CzXgkLDe.js";
3
- import { a as makePropertiesGenerator, c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, l as schemaFromFields, s as makeValidationExtractor, t as getBool } from "../../utils-COHZyQue.js";
4
- import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-ChsFqlYX.js";
2
+ import { t as fmt } from "../../format-DwiYldCm.js";
3
+ import { a as makePropertiesGenerator, c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, l as schemaFromFields, s as makeValidationExtractor, t as getBool } from "../../utils-0tE5jzYR.js";
4
+ import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-DHllEbMR.js";
5
5
  import path from "node:path";
6
6
  import pkg from "@prisma/generator-helper";
7
7
 
8
8
  //#region src/helper/valibot.ts
9
9
  function makeValibotInfer(modelName) {
10
- return `export type ${modelName} = v.InferInput<typeof ${modelName}Schema>`;
10
+ return `export type ${modelName} = v.InferOutput<typeof ${modelName}Schema>`;
11
11
  }
12
12
  function makeValibotSchema(modelName, fields) {
13
13
  return `export const ${modelName}Schema = v.object({\n${fields}\n})`;
@@ -33,7 +33,7 @@ function makeValibotRelations(model, relProps, options) {
33
33
  if (relProps.length === 0) return null;
34
34
  const base = ` ...${model.name}Schema.entries,`;
35
35
  const rels = relProps.map((r) => ` ${r.key}: ${r.isMany ? `v.array(${r.targetModel}Schema)` : `${r.targetModel}Schema`},`).join("\n");
36
- const typeLine = options?.includeType ? `\n\nexport type ${model.name}Relations = v.InferInput<typeof ${model.name}RelationsSchema>` : "";
36
+ const typeLine = options?.includeType ? `\n\nexport type ${model.name}Relations = v.InferOutput<typeof ${model.name}RelationsSchema>` : "";
37
37
  return `export const ${model.name}RelationsSchema = v.object({\n${base}\n${rels}\n})${typeLine}`;
38
38
  }
39
39
  function valibot(models, type, comment, enums) {
@@ -64,12 +64,9 @@ async function main(options) {
64
64
  file: path.join(output, "index.ts")
65
65
  };
66
66
  const enableRelation = getBool(options.generator.config?.relation);
67
- const fmtResult = await fmt([valibot(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeValibotRelations) : ""].filter(Boolean).join("\n\n"));
68
- if (!fmtResult.ok) throw new Error(`Format error: ${fmtResult.error}`);
69
- const mkdirResult = await mkdir(resolved.dir);
70
- if (!mkdirResult.ok) throw new Error(`Failed to create directory: ${mkdirResult.error}`);
71
- const writeResult = await writeFile(resolved.file, fmtResult.value);
72
- if (!writeResult.ok) throw new Error(`Failed to write file: ${writeResult.error}`);
67
+ const code = await fmt([valibot(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeValibotRelations) : ""].filter(Boolean).join("\n\n"));
68
+ await mkdir(resolved.dir);
69
+ await writeFile(resolved.file, code);
73
70
  }
74
71
  generatorHandler({
75
72
  onManifest() {
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { t as fmt } from "../../format-CzXgkLDe.js";
3
- import { a as makePropertiesGenerator, c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, l as schemaFromFields, n as getString, s as makeValidationExtractor, t as getBool } from "../../utils-COHZyQue.js";
4
- import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-ChsFqlYX.js";
2
+ import { t as fmt } from "../../format-DwiYldCm.js";
3
+ import { a as makePropertiesGenerator, c as parseDocumentWithoutAnnotations, d as mkdir, f as writeFile, l as schemaFromFields, n as getString, s as makeValidationExtractor, t as getBool } from "../../utils-0tE5jzYR.js";
4
+ import { n as validationSchemas, t as makeRelationsOnly } from "../../prisma-DHllEbMR.js";
5
5
  import path from "node:path";
6
6
  import pkg from "@prisma/generator-helper";
7
7
 
@@ -65,12 +65,9 @@ async function main(options) {
65
65
  };
66
66
  const zodVersion = getString(options.generator.config?.zod, "v4");
67
67
  const enableRelation = getBool(options.generator.config?.relation);
68
- const fmtResult = await fmt([zod(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), zodVersion, options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeZodRelations) : ""].filter(Boolean).join("\n\n"));
69
- if (!fmtResult.ok) throw new Error(`Format error: ${fmtResult.error}`);
70
- const mkdirResult = await mkdir(resolved.dir);
71
- if (!mkdirResult.ok) throw new Error(`Failed to create directory: ${mkdirResult.error}`);
72
- const writeResult = await writeFile(resolved.file, fmtResult.value);
73
- if (!writeResult.ok) throw new Error(`Failed to write file: ${writeResult.error}`);
68
+ const code = await fmt([zod(options.dmmf.datamodel.models, getBool(options.generator.config?.type), getBool(options.generator.config?.comment), zodVersion, options.dmmf.datamodel.enums), enableRelation ? makeRelationsOnly(options.dmmf, getBool(options.generator.config?.type), makeZodRelations) : ""].filter(Boolean).join("\n\n"));
69
+ await mkdir(resolved.dir);
70
+ await writeFile(resolved.file, code);
74
71
  }
75
72
  generatorHandler({
76
73
  onManifest() {
@@ -1,4 +1,4 @@
1
- import { i as isFields, r as groupByModel } from "./utils-COHZyQue.js";
1
+ import { i as isFields, r as groupByModel } from "./utils-0tE5jzYR.js";
2
2
 
3
3
  //#region src/helper/prisma.ts
4
4
  function collectRelationProps(models) {
@@ -60,7 +60,7 @@ function validationSchemas(models, type, comment, config) {
60
60
  modelName: model.name,
61
61
  fieldName: f.name
62
62
  })));
63
- for (const { modelName, fieldName } of missing) console.warn(`Warning: Field "${modelName}.${fieldName}" has no ${config.annotationPrefix} annotation and will be omitted from the schema`);
63
+ if (config.onWarning) for (const { modelName, fieldName } of missing) config.onWarning(`Warning: Field "${modelName}.${fieldName}" has no ${config.annotationPrefix} annotation and will be omitted from the schema`);
64
64
  const schemas = Object.values(groupByModel(isFields(modelFields))).map((fields) => ({
65
65
  schema: config.schemas(fields, comment),
66
66
  inferType: type ? config.inferType(fields[0].modelName) : ""
@@ -2,46 +2,13 @@ import fs from "node:fs/promises";
2
2
 
3
3
  //#region src/fsp/index.ts
4
4
  async function mkdir(dir) {
5
- try {
6
- await fs.mkdir(dir, { recursive: true });
7
- return {
8
- ok: true,
9
- value: void 0
10
- };
11
- } catch (e) {
12
- return {
13
- ok: false,
14
- error: e instanceof Error ? e.message : String(e)
15
- };
16
- }
5
+ await fs.mkdir(dir, { recursive: true });
17
6
  }
18
7
  async function writeFile(path, data) {
19
- try {
20
- await fs.writeFile(path, data, "utf-8");
21
- return {
22
- ok: true,
23
- value: void 0
24
- };
25
- } catch (e) {
26
- return {
27
- ok: false,
28
- error: e instanceof Error ? e.message : String(e)
29
- };
30
- }
8
+ await fs.writeFile(path, data, "utf-8");
31
9
  }
32
10
  async function writeFileBinary(path, data) {
33
- try {
34
- await fs.writeFile(path, data);
35
- return {
36
- ok: true,
37
- value: void 0
38
- };
39
- } catch (e) {
40
- return {
41
- ok: false,
42
- error: e instanceof Error ? e.message : String(e)
43
- };
44
- }
11
+ await fs.writeFile(path, data);
45
12
  }
46
13
 
47
14
  //#endregion
package/package.json CHANGED
@@ -1,64 +1,63 @@
1
1
  {
2
2
  "name": "hekireki",
3
- "type": "module",
4
- "version": "0.7.2",
5
- "license": "MIT",
3
+ "version": "0.7.4",
6
4
  "description": "Hekireki is a tool that generates validation schemas for Zod, Valibot, ArkType, and Effect Schema, as well as ER diagrams and DBML, from Prisma schemas annotated with comments.",
7
5
  "keywords": [
8
- "prisma",
9
- "zod",
10
- "valibot",
6
+ "ajv",
11
7
  "arktype",
12
- "effect",
13
- "mermaid",
14
- "ecto",
15
8
  "dbml",
16
- "typebox",
17
- "ajv",
18
- "json-schema",
19
9
  "docs",
20
10
  "documentation",
21
- "gorm",
11
+ "ecto",
12
+ "effect",
22
13
  "go",
14
+ "gorm",
15
+ "json-schema",
16
+ "mermaid",
17
+ "prisma",
18
+ "rust",
23
19
  "sea-orm",
24
- "rust"
20
+ "typebox",
21
+ "valibot",
22
+ "zod"
25
23
  ],
26
24
  "homepage": "https://github.com/nakita628/hekireki",
27
- "publishConfig": {
28
- "access": "public"
25
+ "bugs": {
26
+ "url": "https://github.com/nakita628/hekireki/issues"
29
27
  },
28
+ "license": "MIT",
30
29
  "repository": {
31
30
  "type": "git",
32
31
  "url": "git+https://github.com/nakita628/hekireki.git"
33
32
  },
34
- "bugs": {
35
- "url": "https://github.com/nakita628/hekireki/issues"
36
- },
37
- "files": [
38
- "dist"
39
- ],
40
33
  "bin": {
41
34
  "hekireki": "dist/cli/index.js",
42
- "hekireki-zod": "dist/generator/zod/index.js",
43
- "hekireki-valibot": "dist/generator/valibot/index.js",
44
- "hekireki-mermaid-er": "dist/generator/mermaid-er/index.js",
45
- "hekireki-ecto": "dist/generator/ecto/index.js",
35
+ "hekireki-ajv": "dist/generator/ajv/index.js",
46
36
  "hekireki-arktype": "dist/generator/arktype/index.js",
47
- "hekireki-effect": "dist/generator/effect/index.js",
48
37
  "hekireki-dbml": "dist/generator/dbml/index.js",
49
38
  "hekireki-docs": "dist/generator/docs/index.js",
50
39
  "hekireki-drizzle": "dist/generator/drizzle/index.js",
51
- "hekireki-typebox": "dist/generator/typebox/index.js",
52
- "hekireki-ajv": "dist/generator/ajv/index.js",
53
- "hekireki-sqlalchemy": "dist/generator/sqlalchemy/index.js",
40
+ "hekireki-ecto": "dist/generator/ecto/index.js",
41
+ "hekireki-effect": "dist/generator/effect/index.js",
54
42
  "hekireki-gorm": "dist/generator/gorm/index.js",
55
- "hekireki-sea-orm": "dist/generator/sea-orm/index.js"
43
+ "hekireki-mermaid-er": "dist/generator/mermaid-er/index.js",
44
+ "hekireki-sea-orm": "dist/generator/sea-orm/index.js",
45
+ "hekireki-sqlalchemy": "dist/generator/sqlalchemy/index.js",
46
+ "hekireki-typebox": "dist/generator/typebox/index.js",
47
+ "hekireki-valibot": "dist/generator/valibot/index.js",
48
+ "hekireki-zod": "dist/generator/zod/index.js"
49
+ },
50
+ "files": [
51
+ "dist"
52
+ ],
53
+ "type": "module",
54
+ "publishConfig": {
55
+ "access": "public"
56
56
  },
57
57
  "scripts": {
58
58
  "generate": "prisma generate",
59
59
  "deps": "rm -rf node_modules && pnpm install",
60
60
  "build": "tsdown",
61
- "typecheck": "tsc --noEmit",
62
61
  "release": "npm pkg fix && pnpm build && npm publish"
63
62
  },
64
63
  "dependencies": {
@@ -70,19 +69,23 @@
70
69
  "oxfmt": "^0.33.0"
71
70
  },
72
71
  "devDependencies": {
72
+ "@paralleldrive/cuid2": "^2.3.1",
73
73
  "@prisma/client": "^7.4.0",
74
+ "@sinclair/typebox": "^0.34.33",
74
75
  "@types/node": "^25.2.3",
75
76
  "@typescript/native-preview": "7.0.0-dev.20260218.1",
77
+ "ajv": "^8.17.1",
76
78
  "arktype": "^2.1.29",
79
+ "better-auth": "^1.5.5",
80
+ "drizzle-kit": "^0.31.9",
81
+ "drizzle-orm": "^0.45.1",
77
82
  "effect": "^3.19.18",
83
+ "json-schema-to-ts": "^3.1.1",
78
84
  "prisma": "^7.4.0",
79
85
  "tsdown": "^0.20.3",
80
86
  "tsx": "^4.21.0",
81
87
  "typescript": "^5.9.3",
82
88
  "valibot": "1.2.0",
83
- "@sinclair/typebox": "^0.34.33",
84
- "ajv": "^8.17.1",
85
- "json-schema-to-ts": "^3.1.1",
86
89
  "zod": "^4.3.6"
87
90
  }
88
91
  }