shutro 0.3.0 → 0.3.2

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.
@@ -9,6 +9,15 @@ export declare function externalIdTableStatements(): readonly {
9
9
  }[];
10
10
  /** `env.refId(model, id)`. */
11
11
  export declare function refId<M extends string>(env: Env, model: M, id: string): Promise<Id<M>>;
12
+ /**
13
+ * `env.setExternalId(model, id, externalId)` (RFC 0017 §4): names a record outside module data, as an import does
14
+ * (`__import__.partner_42`), so a later file can find it again with `env.refId`. The module part may not be an
15
+ * installed module's: those ids are its data, deleted by `loadData` when no longer declared. The record must exist
16
+ * and be readable in the scope. Naming the same record again does nothing; an id that names another record is
17
+ * refused. The row commits or rolls back with the scope's transaction.
18
+ * @throws {UnknownExternalIdError} for a malformed id, a module's id, an unreadable record or an id already taken
19
+ */
20
+ export declare function setExternalId(env: Env, model: string, id: number, externalId: string): Promise<void>;
12
21
  /** What {@link loadData} did for one module. */
13
22
  export interface DataLoadResult {
14
23
  readonly module: string;
@@ -55,6 +55,33 @@ async function resolveExternalId(internals, id, model) {
55
55
  export async function refId(env, model, id) {
56
56
  return (await resolveExternalId(internalsOf(env), id, model));
57
57
  }
58
+ const MODULE_PART = /^[a-z0-9_]+$/;
59
+ /**
60
+ * `env.setExternalId(model, id, externalId)` (RFC 0017 §4): names a record outside module data, as an import does
61
+ * (`__import__.partner_42`), so a later file can find it again with `env.refId`. The module part may not be an
62
+ * installed module's: those ids are its data, deleted by `loadData` when no longer declared. The record must exist
63
+ * and be readable in the scope. Naming the same record again does nothing; an id that names another record is
64
+ * refused. The row commits or rolls back with the scope's transaction.
65
+ * @throws {UnknownExternalIdError} for a malformed id, a module's id, an unreadable record or an id already taken
66
+ */
67
+ export async function setExternalId(env, model, id, externalId) {
68
+ const internals = internalsOf(env);
69
+ const [module, name] = split(externalId);
70
+ if (!externalId.includes('.') || !MODULE_PART.test(module) || name === '')
71
+ throw new UnknownExternalIdError(`'${externalId}' is not an external id.`, 'Write it as module.name, e.g. __import__.partner_42.');
72
+ if (internals.registry.modules.some((m) => m.name === module))
73
+ throw new UnknownExternalIdError(`The external id '${externalId}' belongs to the module '${module}': its ids are its data.`, 'Use a module part no installed module has, e.g. __import__.');
74
+ const records = env.model(model);
75
+ const visible = await records.search({ where: { id }, limit: 1 });
76
+ if (visible.length === 0)
77
+ throw new UnknownExternalIdError(`No ${model} record ${id} to name '${externalId}'.`, 'Name a record that exists and that the scope can read.');
78
+ if (!(await tableExists(internals)))
79
+ for (const text of DDL)
80
+ await internals.query({ text, params: [] });
81
+ const [row] = await internals.query(compile(sql `INSERT INTO ${sql.id(EXTERNAL_ID_TABLE)} (module, name, model, res_id, noupdate) VALUES (${module}, ${name}, ${model}, ${id}, ${true}) ON CONFLICT (module, name) DO UPDATE SET updated_at = ${sql.id(EXTERNAL_ID_TABLE)}.updated_at RETURNING model, res_id`));
82
+ if (row !== undefined && (row.model !== model || Number(row.res_id) !== id))
83
+ throw new UnknownExternalIdError(`The external id '${externalId}' already names ${row.model} record ${row.res_id}.`, 'Use another name, or update that record instead.');
84
+ }
58
85
  /** A stable text of declared values for checksums: refs by id, Decimals as strings, sorted keys. */
59
86
  function stable(value) {
60
87
  if (isRef(value))
@@ -251,6 +251,11 @@ export declare class Env<S = unknown> {
251
251
  ref<M extends ModelName<S>>(model: M, id: string): Promise<RecordSet<S, M, ListLoaded<never>>>;
252
252
  /** The id of the record with external id `id`. @throws {UnknownExternalIdError} */
253
253
  refId<M extends ModelName<S>>(model: M, id: string): Promise<Id<M>>;
254
+ /**
255
+ * Names record `id` of `model` with external id `externalId` outside module data (imports, RFC 0017 §4).
256
+ * @throws {UnknownExternalIdError} for a module's id, an unreadable record or an id naming another record
257
+ */
258
+ setExternalId<M extends ModelName<S>>(model: M, id: Id<M> | number, externalId: string): Promise<void>;
254
259
  /**
255
260
  * Runtime security administration (RFC 0014 §7.10): roles, model access, record rules and permission grants, on top
256
261
  * of the code's declarations. Administrators (or superuser scopes) only; each change is validated against the
@@ -4,7 +4,7 @@ import { randomUUID } from 'node:crypto';
4
4
  import { isRetryable, } from '../../driver-pg/index.js';
5
5
  import { InvalidSequenceError } from '../../sequence/index.js';
6
6
  import { compile, sql as sqlTag } from '../../sql/index.js';
7
- import { refId } from '../data/load.js';
7
+ import { refId, setExternalId } from '../data/load.js';
8
8
  import { AccessError, CompanyNotAllowedError, ConcurrentUpdateError, FlagNotAllowedError, InvalidIdentityError, NoEnvironmentError, NoRegistryError, TransactionScopeError, } from '../errors.js';
9
9
  import { emitEvent, enqueueJob, ensureEventTables } from '../events/events.js';
10
10
  import { subscribe, work, } from '../events/workers.js';
@@ -157,6 +157,13 @@ export class Env {
157
157
  async refId(model, id) {
158
158
  return refId(this, model, id);
159
159
  }
160
+ /**
161
+ * Names record `id` of `model` with external id `externalId` outside module data (imports, RFC 0017 §4).
162
+ * @throws {UnknownExternalIdError} for a module's id, an unreadable record or an id naming another record
163
+ */
164
+ async setExternalId(model, id, externalId) {
165
+ return setExternalId(this, model, Number(id), externalId);
166
+ }
160
167
  /**
161
168
  * Runtime security administration (RFC 0014 §7.10): roles, model access, record rules and permission grants, on top
162
169
  * of the code's declarations. Administrators (or superuser scopes) only; each change is validated against the
@@ -20,11 +20,38 @@ function isX2Many(field) {
20
20
  function scalarKeys(model) {
21
21
  return Object.keys(model.fields).filter((k) => !isX2Many(model.fields[k]));
22
22
  }
23
+ /**
24
+ * The ids of a draft's many2many after a handler sets it: a list of ids, or commands (`set`, `link`, `unlink`,
25
+ * `clear`) applied to its current ids. The draft keeps ids, as for given values, so computes read it like any set.
26
+ */
27
+ function many2manyIds(current, value) {
28
+ if (Array.isArray(value))
29
+ return value.filter((v) => typeof v === 'number');
30
+ const commands = (value ?? {});
31
+ let list = commands['clear'] === true ? [] : [...current];
32
+ if (Array.isArray(commands['set']))
33
+ list = [...commands['set']];
34
+ if (Array.isArray(commands['link']))
35
+ for (const id of commands['link'])
36
+ if (!list.includes(id))
37
+ list.push(id);
38
+ if (Array.isArray(commands['unlink'])) {
39
+ const gone = new Set(commands['unlink']);
40
+ list = list.filter((id) => !gone.has(id));
41
+ }
42
+ return list;
43
+ }
23
44
  /** Writes one draft value into the cache: `null` is always allowed, everything else is normalized like a write. */
24
45
  function setDraftValue(model, values, key, value, translation) {
25
46
  const field = model.fields[key];
26
47
  if (field === undefined || key === 'id')
27
48
  fail(model, [key], `'${key}' is not a field.`, `Fields: ${Object.keys(model.fields).join(', ')}.`);
49
+ if (field.kind === 'many2many') {
50
+ values.set(key, value === null || value === undefined
51
+ ? []
52
+ : many2manyIds(values.get(key) ?? [], value));
53
+ return;
54
+ }
28
55
  if (value === null || value === undefined) {
29
56
  values.set(key, null);
30
57
  return;
@@ -198,6 +225,9 @@ export async function runOnchange(host, model, input) {
198
225
  // The input to compare against: a record's values and the given ones; for a new draft the given ones only, so
199
226
  // its defaults come back (a new form shows them).
200
227
  const [beforeRow] = host.read(model, [vid], keys.filter((k) => input.id === undefined || input.id === null ? k in input.values : values.has(k)));
228
+ // Many2many fields come back as their ids when a handler changed them (a line's taxes from its product).
229
+ const sets = Object.keys(model.fields).filter((k) => model.fields[k].kind === 'many2many' && canField(internals, model, k, 'read'));
230
+ const setsBefore = new Map(sets.map((k) => [k, JSON.stringify(values.get(k) ?? [])]));
201
231
  // Handlers, cascading once per key: the draft's, then each new child row's for the fields it was given
202
232
  // (feedback #10), so a line's product handler runs inside the order being edited and sees its values.
203
233
  await runHandlers(host, model, vid, input.id ?? null, input.changed, warnings);
@@ -225,6 +255,11 @@ export async function runOnchange(host, model, input) {
225
255
  if (JSON.stringify(row?.[key] ?? null) !== JSON.stringify(beforeRow?.[key] ?? null))
226
256
  out[key] = row?.[key];
227
257
  }
258
+ for (const key of sets) {
259
+ const now = values.get(key) ?? [];
260
+ if (JSON.stringify(now) !== setsBefore.get(key))
261
+ out[key] = [...now];
262
+ }
228
263
  const children = {};
229
264
  for (const [key, ids] of childIds) {
230
265
  const target = internals.registry.get(model.fields[key].target ?? '').model;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shutro",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "The ORM built for business software: type-safe, secure-by-default, multi-company, audit-ready PostgreSQL ORM for Node.js and TypeScript.",
5
5
  "keywords": [
6
6
  "orm",
@@ -32,7 +32,7 @@
32
32
  "node": ">=24"
33
33
  },
34
34
  "bin": {
35
- "shutro": "./dist/cli/bin.js"
35
+ "shutro": "dist/cli/bin.js"
36
36
  },
37
37
  "exports": {
38
38
  ".": {