hekireki 0.2.4 → 0.2.6

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.
@@ -2,69 +2,58 @@ import fsp from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { snakeCase } from '../../../shared/utils/index.js';
4
4
  import { prismaTypeToEctoType } from '../utils/prisma-type-to-ecto-type.js';
5
- /* ───────── Utilities ────────────────────────── */
6
- /** UUID PK :binary_id / otherwise :id */
7
- function getPrimaryKeyType(field) {
8
- const def = field.default;
9
- return def && typeof def === 'object' && 'name' in def && def.name === 'uuid' ? 'binary_id' : 'id';
10
- }
11
- /** Convert readonly models to mutable copies */
12
- function makeMutable(models) {
13
- return models.map((m) => ({
14
- ...m,
15
- fields: m.fields?.map((f) => ({ ...f })) ?? [],
16
- }));
5
+ function getPrimaryKeyConfig(field) {
6
+ if (field.type === 'String' &&
7
+ field.default &&
8
+ typeof field.default === 'object' &&
9
+ 'name' in field.default &&
10
+ field.default.name === 'uuid') {
11
+ return {
12
+ line: '@primary_key {:id, :binary_id, autogenerate: true}',
13
+ typeSpec: 'Ecto.UUID.t()',
14
+ omitIdFieldInSchema: true,
15
+ };
16
+ }
17
+ return {
18
+ line: '@primary_key false',
19
+ typeSpec: 'String.t()',
20
+ omitIdFieldInSchema: false,
21
+ };
17
22
  }
18
- /* ───────── Main generator ───────────────────── */
19
23
  export function ectoSchemas(models, app) {
20
- const mutableModels = makeMutable(models);
21
- /** Timestamp column aliases (snake_case & camelCase) */
22
- const insertedAliases = ['inserted_at', 'created_at', 'createdAt'];
23
- const updatedAliases = ['updated_at', 'modified_at', 'updatedAt', 'modifiedAt'];
24
- return mutableModels
24
+ return models
25
25
  .map((model) => {
26
- /* ── Primary-key handling ─────────────────── */
27
- const idFields = model.fields.filter((f) => f.isId);
28
- const isCompositePK = model.primaryKey && model.primaryKey.fields.length > 1;
29
- if (!(idFields.length || isCompositePK))
26
+ const idField = model.fields.find((f) => f.isId);
27
+ if (!idField)
30
28
  return '';
31
- const pkField = idFields[0];
32
- const pkType = pkField ? getPrimaryKeyType(pkField) : 'id';
33
- /* ── Timestamp field detection ────────────── */
34
- const insertedField = model.fields.find((f) => insertedAliases.includes(f.name));
35
- const updatedField = model.fields.find((f) => updatedAliases.includes(f.name));
36
- /** Columns removed from explicit `field/3` declarations */
37
- const excludedNames = [
38
- ...(insertedField ? [insertedField.name] : []),
39
- ...(updatedField ? [updatedField.name] : []),
29
+ const pk = getPrimaryKeyConfig(idField);
30
+ const fields = model.fields.filter((f) => !(f.relationName || (f.isId && pk.omitIdFieldInSchema)));
31
+ const typeSpecFields = [
32
+ `id: ${pk.typeSpec}`,
33
+ ...fields.map((f) => `${f.name}: ${ectoTypeToTypespec(prismaTypeToEctoType(f.type))}`),
34
+ ];
35
+ const typeSpecLines = [
36
+ ' @type t :: %__MODULE__{',
37
+ ...typeSpecFields.map((line, i) => {
38
+ const isLast = i === typeSpecFields.length - 1;
39
+ return ` ${line}${isLast ? '' : ','}`;
40
+ }),
41
+ ' }',
40
42
  ];
41
- /* ── Plain fields (no relations / no timestamps) */
42
- const fields = model.fields.filter((f) => !(f.relationName || excludedNames.includes(f.name)));
43
- /* ── Build timestamps() line (const-only) ─────── */
44
- const timestampsLine = (() => {
45
- if (!(insertedField || updatedField))
46
- return '';
47
- const hasCustom = (insertedField && insertedField.name !== 'inserted_at') ||
48
- (updatedField && updatedField.name !== 'updated_at');
49
- if (!hasCustom)
50
- return ' timestamps()'; // both defaults → short form
51
- // Always include both keys when custom names are involved
52
- const insertedName = insertedField ? insertedField.name : 'inserted_at';
53
- const updatedName = updatedField ? updatedField.name : 'updated_at';
54
- return ` timestamps(inserted_at: :${insertedName}, updated_at: :${updatedName})`;
55
- })();
56
- /* ── Assemble final module code ───────────── */
43
+ const schemaFields = fields.map((f) => {
44
+ const type = prismaTypeToEctoType(f.type);
45
+ return ` field(:${f.name}, :${type})`;
46
+ });
57
47
  const lines = [
58
48
  `defmodule ${app}.${model.name} do`,
59
49
  ' use Ecto.Schema',
60
- ' @primary_key false',
50
+ '',
51
+ ` ${pk.line}`,
52
+ '',
53
+ ...typeSpecLines,
54
+ '',
61
55
  ` schema "${snakeCase(model.name)}" do`,
62
- ...fields.map((f) => {
63
- const type = f.isId ? pkType : prismaTypeToEctoType(f.type);
64
- const primary = f.isId && !isCompositePK ? ', primary_key: true' : '';
65
- return ` field(:${f.name}, :${type}${primary})`;
66
- }),
67
- ...(timestampsLine ? [timestampsLine] : []),
56
+ ...schemaFields,
68
57
  ' end',
69
58
  'end',
70
59
  ];
@@ -73,11 +62,29 @@ export function ectoSchemas(models, app) {
73
62
  .filter(Boolean)
74
63
  .join('\n\n');
75
64
  }
76
- /* ───────── File writer ───────────────────────── */
65
+ function ectoTypeToTypespec(type) {
66
+ switch (type) {
67
+ case 'string':
68
+ return 'String.t()';
69
+ case 'integer':
70
+ return 'integer()';
71
+ case 'float':
72
+ return 'float()';
73
+ case 'boolean':
74
+ return 'boolean()';
75
+ case 'binary_id':
76
+ return 'Ecto.UUID.t()';
77
+ case 'naive_datetime':
78
+ return 'NaiveDateTime.t()';
79
+ case 'utc_datetime':
80
+ return 'DateTime.t()';
81
+ default:
82
+ return 'term()';
83
+ }
84
+ }
77
85
  export async function writeEctoSchemasToFiles(models, app, outDir) {
78
- const mutableModels = makeMutable(models);
79
86
  await fsp.mkdir(outDir, { recursive: true });
80
- for (const model of mutableModels) {
87
+ for (const model of models) {
81
88
  const code = ectoSchemas([model], app);
82
89
  if (!code.trim())
83
90
  continue;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hekireki",
3
3
  "type": "module",
4
- "version": "0.2.4",
4
+ "version": "0.2.6",
5
5
  "license": "MIT",
6
6
  "description": "Hekireki is a tool that generates validation schemas for Zod and Valibot, as well as ER diagrams, from Prisma schemas annotated with comments.",
7
7
  "keywords": [