@kiri-orm/core 0.1.2 → 0.1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kiri-orm/core",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "main": "./src/index.js",
6
6
  "types": "./dist/types/index.d.ts",
@@ -1,33 +1,114 @@
1
1
  import { CastError } from "../errors.js";
2
2
 
3
- function isValidDate(d) {
4
- return d instanceof Date && !Number.isNaN(d.getTime());
3
+ // year first; separators must match; optional time part with optional zone
4
+ const DATE_RE =
5
+ /^(\d{4})([-/.])(\d{1,2})\2(\d{1,2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?\s*(Z|[+-]\d{2}(?::?\d{2})?)?)?$/i;
6
+
7
+ function isLeap(y) {
8
+ return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
9
+ }
10
+
11
+ function daysInMonth(y, m) {
12
+ if (m === 2) return isLeap(y) ? 29 : 28;
13
+ return m === 4 || m === 6 || m === 9 || m === 11 ? 30 : 31;
14
+ }
15
+
16
+ function isRealCalendarDate(y, m, d) {
17
+ return m >= 1 && m <= 12 && d >= 1 && d <= daysInMonth(y, m);
18
+ }
19
+
20
+ function format(y, m, d) {
21
+ return `${String(y).padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
22
+ }
23
+
24
+ function normalizeOffset(z) {
25
+ if (z.toUpperCase() === "Z") return "Z";
26
+ const sign = z[0];
27
+ const digits = z.slice(1).replace(":", "");
28
+ const hh = digits.slice(0, 2);
29
+ const mm = digits.slice(2) || "00";
30
+ return `${sign}${hh}:${mm}`;
31
+ }
32
+
33
+ // Calendar day of an instant in a given IANA timezone.
34
+ function dayInZone(instant, timeZone) {
35
+ const parts = new Intl.DateTimeFormat("en-US", {
36
+ timeZone,
37
+ year: "numeric",
38
+ month: "numeric",
39
+ day: "numeric",
40
+ }).formatToParts(instant);
41
+ const get = (t) => Number(parts.find((p) => p.type === t).value);
42
+ return format(get("year"), get("month"), get("day"));
43
+ }
44
+
45
+ function parseString(field, raw) {
46
+ const match = DATE_RE.exec(raw.trim());
47
+ if (!match) return null;
48
+
49
+ const y = Number(match[1]);
50
+ const m = Number(match[3]);
51
+ const d = Number(match[4]);
52
+ if (!isRealCalendarDate(y, m, d)) return null;
53
+
54
+ const hasTime = match[5] !== undefined;
55
+ if (hasTime) {
56
+ const [hh, mi, ss] = [match[5], match[6], match[7] ?? "0"].map(Number);
57
+ if (hh > 23 || mi > 59 || ss > 59) return null;
58
+ }
59
+
60
+ const offset = match[8];
61
+ if (hasTime && offset && field?.timeZone) {
62
+ // The string is an instant: convert it to a day in the field's zone.
63
+ const iso =
64
+ `${format(y, m, d)}T${match[5]}:${match[6]}:${String(match[7] ?? "0").padStart(2, "0")}` +
65
+ normalizeOffset(offset);
66
+ const instant = new Date(iso);
67
+ return Number.isNaN(instant.getTime())
68
+ ? null
69
+ : dayInZone(instant, field.timeZone);
70
+ }
71
+
72
+ // Default: the date exactly as written; time and offset are ignored.
73
+ return format(y, m, d);
74
+ }
75
+
76
+ function fromDateObject(dt) {
77
+ if (Number.isNaN(dt.getTime())) return null;
78
+ return format(dt.getFullYear(), dt.getMonth() + 1, dt.getDate());
5
79
  }
6
80
 
7
- /**
8
- * A calendar date (no time component, though the canonical runtime
9
- * representation is still a JS Date - the schema-sync layer in a later
10
- * phase is what maps this to a DATE vs DATETIME column per dialect).
11
- */
12
81
  export const dateType = {
13
82
  name: "date",
14
83
 
84
+ // validate stays strict: it only accepts the canonical stored form.
15
85
  validate(field, value) {
16
- if (!isValidDate(value)) {
17
- return [`expected a valid Date, got ${JSON.stringify(value)}`];
18
- }
19
- return [];
86
+ const ok =
87
+ typeof value === "string" &&
88
+ /^\d{4}-\d{2}-\d{2}$/.test(value) &&
89
+ isRealCalendarDate(
90
+ +value.slice(0, 4),
91
+ +value.slice(5, 7),
92
+ +value.slice(8, 10),
93
+ );
94
+ return ok
95
+ ? []
96
+ : [
97
+ `expected a real calendar date as "YYYY-MM-DD", got ${JSON.stringify(value)}`,
98
+ ];
20
99
  },
21
100
 
22
101
  cast(field, value) {
23
- if (isValidDate(value)) return value;
24
- if (typeof value === "string" || typeof value === "number") {
25
- const parsed = new Date(value);
26
- if (isValidDate(parsed)) return parsed;
102
+ let result = null;
103
+ if (typeof value === "string") result = parseString(field, value);
104
+ else if (value instanceof Date) result = fromDateObject(value);
105
+
106
+ if (result === null) {
107
+ throw new CastError(`cannot cast ${JSON.stringify(value)} to date`, {
108
+ fieldType: "date",
109
+ value,
110
+ });
27
111
  }
28
- throw new CastError(`cannot cast ${JSON.stringify(value)} to date`, {
29
- fieldType: "date",
30
- value,
31
- });
112
+ return result;
32
113
  },
33
114
  };
@@ -1,9 +1,18 @@
1
1
  import { Repository } from "../crud/repository.js";
2
- import { createEntity, diffEntity, mergeRecordIntoEntity, ENTITY_META } from "../uow/entity.js";
2
+ import {
3
+ createEntity,
4
+ diffEntity,
5
+ mergeRecordIntoEntity,
6
+ ENTITY_META,
7
+ } from "../uow/entity.js";
3
8
  import { withPrimaryKey } from "../crud/select.js";
4
9
  import { paginateWith } from "../crud/paginate.js";
5
10
  import { HOOK_NAMES } from "../uow/hooks.js";
6
- import { attachRelation, attachManyRelation, detachRelation } from "../relations/attach-detach.js";
11
+ import {
12
+ attachRelation,
13
+ attachManyRelation,
14
+ detachRelation,
15
+ } from "../relations/attach-detach.js";
7
16
  import { createRecords } from "../crud/create-many.js";
8
17
  import { assertPrimaryKeyUntouched } from "../crud/prepare-write.js";
9
18
  import { defaultFieldTypeRegistry } from "../fields/default-registry.js";
@@ -11,11 +20,14 @@ import { getConnection } from "./connect.js";
11
20
  import { state } from "./state.js";
12
21
  import { currentIdentityMap } from "./identity-scope.js";
13
22
  import { primaryKeyOf } from "../models/primary-key.js";
23
+ import { SaveDeletedError } from "./errors.js";
14
24
 
15
25
  const assertKnownHooks = (name, hooks) => {
16
26
  for (const hookName of Object.keys(hooks)) {
17
27
  if (!HOOK_NAMES.includes(hookName)) {
18
- throw new TypeError(`Model "${name}": unknown hook "${hookName}". Valid hooks: ${HOOK_NAMES.join(", ")}`);
28
+ throw new TypeError(
29
+ `Model "${name}": unknown hook "${hookName}". Valid hooks: ${HOOK_NAMES.join(", ")}`,
30
+ );
19
31
  }
20
32
  }
21
33
  };
@@ -24,7 +36,9 @@ function registerHooks(name, hooks) {
24
36
  if (!hooks) return;
25
37
  assertKnownHooks(name, hooks);
26
38
  for (const [hookName, handlerOrHandlers] of Object.entries(hooks)) {
27
- const handlers = Array.isArray(handlerOrHandlers) ? handlerOrHandlers : [handlerOrHandlers];
39
+ const handlers = Array.isArray(handlerOrHandlers)
40
+ ? handlerOrHandlers
41
+ : [handlerOrHandlers];
28
42
  for (const fn of handlers) state.hooks.on(name, hookName, fn);
29
43
  }
30
44
  }
@@ -35,7 +49,9 @@ function addMixinHooks(mixinName, hooks) {
35
49
  assertKnownHooks(mixinName, hooks);
36
50
  const merged = { ...state.mixinHooks.get(mixinName) };
37
51
  for (const [hookName, handlerOrHandlers] of Object.entries(hooks)) {
38
- const incoming = Array.isArray(handlerOrHandlers) ? handlerOrHandlers : [handlerOrHandlers];
52
+ const incoming = Array.isArray(handlerOrHandlers)
53
+ ? handlerOrHandlers
54
+ : [handlerOrHandlers];
39
55
  merged[hookName] = [...(merged[hookName] ?? []), ...incoming];
40
56
  }
41
57
  state.mixinHooks.set(mixinName, merged);
@@ -91,7 +107,10 @@ export function extendModel(name, extension = {}) {
91
107
  const { fields, relations, mixins, hooks, origin } = extension;
92
108
  const targetIsMixin = state.registry.isAbstract(name);
93
109
  if (hooks && !targetIsMixin) assertKnownHooks(name, hooks); // before anything is registered
94
- state.registry.define({ extend: name, fields, relations, mixins }, { origin });
110
+ state.registry.define(
111
+ { extend: name, fields, relations, mixins },
112
+ { origin },
113
+ );
95
114
  if (targetIsMixin) addMixinHooks(name, hooks);
96
115
  else registerHooks(name, hooks);
97
116
  return getOrCreateModelHandle(name);
@@ -129,7 +148,10 @@ export function extendModel(name, extension = {}) {
129
148
  */
130
149
  export function defineMixin(name, definition) {
131
150
  const { fields, relations, mixins, hooks, origin } = definition;
132
- state.registry.define({ name, abstract: true, fields, relations, mixins }, { origin });
151
+ state.registry.define(
152
+ { name, abstract: true, fields, relations, mixins },
153
+ { origin },
154
+ );
133
155
  addMixinHooks(name, hooks);
134
156
  }
135
157
 
@@ -196,7 +218,10 @@ export function createModel(name, schema) {
196
218
  const { fields, relations, hooks, table, mixins, origin } = schema;
197
219
  // Returns null (rather than throwing) if `mixins` names a model that doesn't exist yet: the
198
220
  // model then simply waits for it. Either way the Model below works once everything is defined.
199
- const descriptorNow = state.registry.define({ name, table, fields, relations, mixins }, { origin });
221
+ const descriptorNow = state.registry.define(
222
+ { name, table, fields, relations, mixins },
223
+ { origin },
224
+ );
200
225
 
201
226
  // A mixin's hooks are picked up here, at creation time - see defineMixin()'s docstring for
202
227
  // why that's a deliberate, one-time pull rather than something a later mixin change reaches
@@ -232,7 +257,12 @@ function getOrCreateModelHandle(name) {
232
257
  const descriptor = () => state.registry.getModel(name);
233
258
 
234
259
  function repo() {
235
- return new Repository(getConnection(), descriptor(), undefined, state.registry);
260
+ return new Repository(
261
+ getConnection(),
262
+ descriptor(),
263
+ undefined,
264
+ state.registry,
265
+ );
236
266
  }
237
267
 
238
268
  function identityKey(id) {
@@ -243,12 +273,20 @@ function getOrCreateModelHandle(name) {
243
273
  // Outside withIdentityMap() every call builds a fresh document.
244
274
  const identityMap = currentIdentityMap();
245
275
  const key = primaryKeyOf(descriptor());
246
- const tracked = identityMap && key !== null && record[key] !== undefined && record[key] !== null;
276
+ const tracked =
277
+ identityMap &&
278
+ key !== null &&
279
+ record[key] !== undefined &&
280
+ record[key] !== null;
247
281
 
248
282
  if (tracked && identityMap.has(identityKey(record[key]))) {
249
283
  // Same rule as UnitOfWork: the in-memory instance wins for field values it already has,
250
284
  // missing fields are filled in, relations are refreshed (see mergeRecordIntoEntity()).
251
- return mergeRecordIntoEntity(identityMap.get(identityKey(record[key])), record, descriptor());
285
+ return mergeRecordIntoEntity(
286
+ identityMap.get(identityKey(record[key])),
287
+ record,
288
+ descriptor(),
289
+ );
252
290
  }
253
291
 
254
292
  const document = createEntity(record, descriptor(), name, {
@@ -268,7 +306,8 @@ function getOrCreateModelHandle(name) {
268
306
  modelRegistry: state.registry,
269
307
  fieldTypeRegistry: defaultFieldTypeRegistry,
270
308
  hooks: state.hooks,
271
- wrap: (modelName, record) => state.wrappers.get(modelName)?.(record) ?? record,
309
+ wrap: (modelName, record) =>
310
+ state.wrappers.get(modelName)?.(record) ?? record,
272
311
  };
273
312
  }
274
313
 
@@ -281,9 +320,27 @@ function getOrCreateModelHandle(name) {
281
320
 
282
321
  try {
283
322
  assertPrimaryKeyUntouched(descriptor(), dirty); // before any hook sees an id change
284
- await state.hooks.run(name, "beforeUpdate", entity, dirty, originalSnapshot);
285
- await state.hooks.run(name, "beforeSave", entity, dirty, originalSnapshot);
286
- await repo().update({ [primaryKeyOf(descriptor())]: original[primaryKeyOf(descriptor())] }, dirty, options);
323
+ await state.hooks.run(
324
+ name,
325
+ "beforeUpdate",
326
+ entity,
327
+ dirty,
328
+ originalSnapshot,
329
+ );
330
+ await state.hooks.run(
331
+ name,
332
+ "beforeSave",
333
+ entity,
334
+ dirty,
335
+ originalSnapshot,
336
+ );
337
+ const result = await repo().update(
338
+ { [primaryKeyOf(descriptor())]: original[primaryKeyOf(descriptor())] },
339
+ dirty,
340
+ options,
341
+ );
342
+ if (!result)
343
+ throw new SaveDeletedError("save() did not affect any rows.");
287
344
  } catch (err) {
288
345
  for (const key of Object.keys(dirty)) entity[key] = original[key];
289
346
  throw err;
@@ -321,10 +378,15 @@ function getOrCreateModelHandle(name) {
321
378
  * @param {{ trx?: import('knex').Knex.Transaction }} [options] - pass `{ trx }` from runInTransaction() to include this write in an ongoing transaction
322
379
  */
323
380
  async create(data, options = {}) {
324
- const [entity] = await createRecords(createRuntime(options), descriptor(), [data], {
325
- trx: options.trx,
326
- labels: [""],
327
- });
381
+ const [entity] = await createRecords(
382
+ createRuntime(options),
383
+ descriptor(),
384
+ [data],
385
+ {
386
+ trx: options.trx,
387
+ labels: [""],
388
+ },
389
+ );
328
390
  return entity;
329
391
  },
330
392
 
@@ -340,7 +402,12 @@ function getOrCreateModelHandle(name) {
340
402
  * @param {{ trx?: import('knex').Knex.Transaction, chunkSize?: number }} [options]
341
403
  */
342
404
  async createMany(dataList, options = {}) {
343
- return createRecords(createRuntime(options), descriptor(), dataList, options);
405
+ return createRecords(
406
+ createRuntime(options),
407
+ descriptor(),
408
+ dataList,
409
+ options,
410
+ );
344
411
  },
345
412
 
346
413
  /**
@@ -352,13 +419,19 @@ function getOrCreateModelHandle(name) {
352
419
  * @param {{ trx?: import('knex').Knex.Transaction, limit?: number, select?: string[], with?: string[]|object }} [options]
353
420
  */
354
421
  async find(filter = {}, options = {}) {
355
- const records = await repo().find(filter, withPrimaryKey(descriptor(), options));
422
+ const records = await repo().find(
423
+ filter,
424
+ withPrimaryKey(descriptor(), options),
425
+ );
356
426
  return records.map(wrapDocument);
357
427
  },
358
428
 
359
429
  /** @param {{ trx?: import('knex').Knex.Transaction, with?: string[] }} [options] */
360
430
  async findOne(filter = {}, options = {}) {
361
- const results = await repo().find(filter, withPrimaryKey(descriptor(), { ...options, limit: 1 }));
431
+ const results = await repo().find(
432
+ filter,
433
+ withPrimaryKey(descriptor(), { ...options, limit: 1 }),
434
+ );
362
435
  return results.length > 0 ? wrapDocument(results[0]) : null;
363
436
  },
364
437
 
@@ -393,9 +466,13 @@ function getOrCreateModelHandle(name) {
393
466
  */
394
467
  async paginate(filter = {}, options = {}) {
395
468
  return paginateWith(
396
- { modelName: name, count: (f, o) => handle.count(f, o), find: (f, o) => handle.find(f, o) },
469
+ {
470
+ modelName: name,
471
+ count: (f, o) => handle.count(f, o),
472
+ find: (f, o) => handle.find(f, o),
473
+ },
397
474
  filter,
398
- options
475
+ options,
399
476
  );
400
477
  },
401
478
 
@@ -435,7 +512,14 @@ function getOrCreateModelHandle(name) {
435
512
  /** @param {{ trx?: import('knex').Knex.Transaction }} [options] */
436
513
  async attach(source, relationName, targetIds, options = {}) {
437
514
  const db = options.trx ?? getConnection();
438
- return attachRelation(db, descriptor(), name, source, relationName, targetIds);
515
+ return attachRelation(
516
+ db,
517
+ descriptor(),
518
+ name,
519
+ source,
520
+ relationName,
521
+ targetIds,
522
+ );
439
523
  },
440
524
 
441
525
  /**
@@ -453,7 +537,14 @@ function getOrCreateModelHandle(name) {
453
537
  /** @param {{ trx?: import('knex').Knex.Transaction }} [options] */
454
538
  async detach(source, relationName, targetIds, options = {}) {
455
539
  const db = options.trx ?? getConnection();
456
- return detachRelation(db, descriptor(), name, source, relationName, targetIds);
540
+ return detachRelation(
541
+ db,
542
+ descriptor(),
543
+ name,
544
+ source,
545
+ relationName,
546
+ targetIds,
547
+ );
457
548
  },
458
549
  };
459
550
  state.models.set(name, handle);
@@ -0,0 +1,6 @@
1
+ export class SaveDeletedError extends Error {
2
+ constructor(message) {
3
+ super(message);
4
+ this.name = "SavedDeletedError";
5
+ }
6
+ }