@things-factory/figure-service 10.1.313 → 10.1.314

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.
@@ -0,0 +1,285 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IMPORT_MAX_BYTES = exports.IMPORT_BATCH = void 0;
4
+ exports.withImportPlan = withImportPlan;
5
+ exports.importFromSource = importFromSource;
6
+ exports.transferOriginOf = transferOriginOf;
7
+ const tslib_1 = require("tslib");
8
+ const crypto_1 = require("crypto");
9
+ const jszip_1 = tslib_1.__importDefault(require("jszip"));
10
+ const figure_model_1 = require("@hatiolab/figure-model");
11
+ const shell_1 = require("@things-factory/shell");
12
+ const figure_js_1 = require("./figure.js");
13
+ const figure_history_js_1 = require("./figure-history.js");
14
+ const figure_replaced_draft_js_1 = require("./figure-replaced-draft.js");
15
+ const figure_transfer_record_js_1 = require("./figure-transfer-record.js");
16
+ const figure_namespace_entity_js_1 = require("./figure-namespace-entity.js");
17
+ const figure_format_js_1 = require("./figure-format.js");
18
+ const figure_namespace_js_1 = require("./figure-namespace.js");
19
+ const figure_rename_js_1 = require("./figure-rename.js");
20
+ const figure_mesh_store_js_1 = require("./figure-mesh-store.js");
21
+ const figure_glb_js_1 = require("./figure-glb.js");
22
+ const figure_thumbnail_store_js_1 = require("./figure-thumbnail-store.js");
23
+ const figure_release_js_1 = require("./figure-release.js");
24
+ const figure_import_source_js_1 = require("./figure-import-source.js");
25
+ /*
26
+ * Taking figures from another figure server (ADR-0231): its released figures, read with its install key through the
27
+ * doors a board server installs through, become this server's figures, to be edited here. A figure of the same type here
28
+ * is written over, its draft kept; none, it is made under this domain's namespace. Released there, it is released here
29
+ * -- through this server's own gate, under a number no board has seen with other content.
30
+ */
31
+ /** The most releases asked of the other server at once (its package door's limit). */
32
+ exports.IMPORT_BATCH = 200;
33
+ /** The most bytes taken from it at once. */
34
+ exports.IMPORT_MAX_BYTES = 256 * 1024 * 1024;
35
+ const hashOf = (text) => (0, crypto_1.createHash)('sha256').update(text).digest('hex');
36
+ const ownOfType = (tx, domain, type) => tx.getRepository(figure_js_1.Figure).findOne({ where: { domain: { id: domain.id }, type } });
37
+ const lastRecordOf = (tx, domain, figureId) => tx.getRepository(figure_transfer_record_js_1.FigureTransferRecord).findOne({ where: { domain: { id: domain.id }, figureId }, order: { createdAt: 'DESC' } });
38
+ async function defaultNamespaceOf(tx, domain) {
39
+ const named = await tx.getRepository(figure_namespace_entity_js_1.FigureNamespace).findOne({ where: { domain: { id: domain.id }, isDefault: true } });
40
+ return named?.name ?? domain.subdomain ?? '';
41
+ }
42
+ /** The other server's figures with what taking each would do here. Nothing is written. */
43
+ async function withImportPlan(tx, domain, source, rows) {
44
+ const fallback = await defaultNamespaceOf(tx, domain);
45
+ const out = [];
46
+ for (const row of rows) {
47
+ const existing = await ownOfType(tx, domain, row.type);
48
+ out.push({ ...row, namespaceHere: existing ? (0, figure_namespace_js_1.namespaceOf)(existing) : fallback, plan: existing ? await planOf(tx, domain, source, row, existing) : 'create' });
49
+ }
50
+ return out;
51
+ }
52
+ async function planOf(tx, domain, source, row, existing) {
53
+ const last = await lastRecordOf(tx, domain, existing.id);
54
+ const here = existing.source ? hashOf(existing.source) : '';
55
+ /*
56
+ Work here that writing over would lose: changed since it was last taken, or -- never taken -- a draft no release
57
+ here holds. The confirmation says so.
58
+ */
59
+ if (last ? here !== last.writtenHash : existing.state !== 'released')
60
+ return 'modified-here';
61
+ if (last && last.sourceUrl === source.url && last.sourceFigureId === row.figureId && last.sourceVersion === row.version)
62
+ return 'unchanged';
63
+ return 'overwrite';
64
+ }
65
+ /**
66
+ * Takes the chosen releases from the other server (`refs`, {namespace}/{type}@{version}, with the figure id the catalog
67
+ * gave each). Each figure in a transaction of its own: one refused, the others go on.
68
+ */
69
+ async function importFromSource(run, domain, user, source, chosen, options = {}) {
70
+ const outcomes = [];
71
+ const unique = [...new Map(chosen.map(one => [one.ref, one])).values()];
72
+ for (let at = 0; at < unique.length; at += exports.IMPORT_BATCH) {
73
+ const part = unique.slice(at, at + exports.IMPORT_BATCH);
74
+ const bytes = await (0, figure_import_source_js_1.sourceReleases)(source, part.map(one => one.ref), exports.IMPORT_MAX_BYTES, options.doFetch);
75
+ const read = await readPackage(bytes);
76
+ if (!read) {
77
+ outcomes.push(...part.map(one => refused(one.ref, new shell_1.Refusal('figure-import-unreadable', {}, 'What the figure server sent cannot be read.'))));
78
+ continue;
79
+ }
80
+ for (const problem of read.refused)
81
+ outcomes.push({ ref: problem.ref ?? '', type: (0, figure_model_1.parseFigureRef)(problem.ref ?? '')?.type ?? '', outcome: 'refused', code: problem.code, notices: [] });
82
+ for (const release of read.releases) {
83
+ const figureId = part.find(one => one.ref === release.ref)?.figureId ?? '';
84
+ try {
85
+ outcomes.push(await run(tx => takeIn(tx, domain, user, source, release, figureId, read.blobs, options)));
86
+ }
87
+ catch (e) {
88
+ outcomes.push(refused(release.ref, e, options.t));
89
+ }
90
+ }
91
+ }
92
+ return outcomes;
93
+ }
94
+ async function readPackage(bytes) {
95
+ let zip;
96
+ try {
97
+ zip = await jszip_1.default.loadAsync(bytes);
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ const files = new Map();
103
+ for (const [path, entry] of Object.entries(zip.files))
104
+ if (!entry.dir)
105
+ files.set(path, await entry.async('uint8array'));
106
+ const read = (0, figure_model_1.readFigurePackage)(files, data => (0, figure_thumbnail_store_js_1.sha256Of)(Buffer.from(data)));
107
+ return read.problems.length ? null : read;
108
+ }
109
+ function refused(ref, e, t) {
110
+ const type = (0, figure_model_1.parseFigureRef)(ref)?.type ?? '';
111
+ if (e instanceof shell_1.Refusal)
112
+ return { ref, type, outcome: 'refused', code: e.code, message: (0, shell_1.speakRefusal)(e, { t }).message, notices: [] };
113
+ if (e instanceof figure_glb_js_1.GlbRefusal)
114
+ return { ref, type, outcome: 'refused', code: 'figure-import-mesh-refused', message: e.message, notices: [] };
115
+ if (e instanceof figure_format_js_1.FigureSourceError)
116
+ return { ref, type, outcome: 'refused', code: 'figure-import-source-invalid', message: e.message, notices: [] };
117
+ return { ref, type, outcome: 'refused', code: 'figure-import-failed', message: e?.message ?? String(e), notices: [] };
118
+ }
119
+ /** What the catalogue says of a figure, as its release carries it. Tags do not travel with a release: those here stay. */
120
+ function catalogueOf(release) {
121
+ return {
122
+ name: release.name,
123
+ names: release.names ?? null,
124
+ description: release.description ?? null,
125
+ category: release.category ?? null,
126
+ deprecated: !!release.deprecated,
127
+ /* A release names the figure to use instead by its full name; here it is a type of the same domain. */
128
+ supersededBy: release.supersededBy ? release.supersededBy.split('/').pop() : null
129
+ };
130
+ }
131
+ function sameCatalogue(row, catalogue) {
132
+ const norm = (value) => JSON.stringify(value == null || value === '' ? null : value);
133
+ return Object.keys(catalogue).every(key => key === 'deprecated' ? !!row.deprecated === catalogue.deprecated : norm(row[key]) === norm(catalogue[key]));
134
+ }
135
+ async function takeIn(tx, domain, user, source, release, remoteFigureId, blobs, options) {
136
+ const ref = (0, figure_model_1.parseFigureRef)(release.ref);
137
+ const figures = tx.getRepository(figure_js_1.Figure);
138
+ const existing = await ownOfType(tx, domain, ref.type);
139
+ if (!existing && (await (0, figure_rename_js_1.typeReleasedBefore)({ figures, histories: tx.getRepository(figure_history_js_1.FigureHistory) }, domain, ref.type)))
140
+ throw new shell_1.Refusal('figure-import-type-released-before', { type: ref.type }, '{type} was released here before and deleted; its name is not used again.');
141
+ const notices = [];
142
+ const namespace = existing ? (0, figure_namespace_js_1.namespaceOf)(existing) : await (0, figure_namespace_js_1.namespaceForNewFigure)(tx, domain, null, user);
143
+ /* A board names the figure by {namespace}/{type}: another namespace here means its boards must be renamed. */
144
+ if (ref.namespace !== namespace)
145
+ notices.push({ code: 'namespace-changed', params: { from: ref.namespace, to: namespace } });
146
+ /* The release's own copy carries its size range written down; the figure here is the author's draft of it. */
147
+ let text = (0, figure_format_js_1.draftSourceOfRelease)(release.source);
148
+ /* Link records point at the other server's figures: at this server's copy of them where it has one, else dropped. */
149
+ const asset = (0, figure_model_1.parseFigureAsset)(text);
150
+ const places = await linkPlacesOf(tx, domain, source);
151
+ const relinked = (0, figure_model_1.figureRelinked)(asset, link => places.get(`${link.figure}@${link.version}`) ?? null);
152
+ if (relinked.asset !== asset)
153
+ text = (0, figure_model_1.serializeFigureAsset)(relinked.asset);
154
+ for (const link of relinked.dropped)
155
+ notices.push({ code: 'link-dropped', params: { id: link.id } });
156
+ const { source: draft, derived } = (0, figure_format_js_1.parseSource)(text);
157
+ for (const hash of (0, figure_model_1.figureFilesOf)(JSON.parse(draft)))
158
+ await (0, figure_mesh_store_js_1.keepMesh)(tx, domain, user, Buffer.from(blobs.get(hash).bytes), options.files ?? (0, figure_thumbnail_store_js_1.thumbnailFiles)());
159
+ const picture = release.thumbnail ? blobs.get(release.thumbnail) : undefined;
160
+ const sameSource = !!existing && existing.source === draft;
161
+ const thumbnailHash = picture
162
+ ? await (0, figure_thumbnail_store_js_1.keepThumbnail)(tx, domain, user, `data:${picture.contentType};base64,${Buffer.from(picture.bytes).toString('base64')}`, options.files ?? (0, figure_thumbnail_store_js_1.thumbnailFiles)())
163
+ : sameSource
164
+ ? (existing.thumbnailHash ?? null)
165
+ : null;
166
+ const catalogue = catalogueOf(release);
167
+ if (sameSource && existing.state === 'released' && sameCatalogue(existing, catalogue) && thumbnailHash === (existing.thumbnailHash ?? null))
168
+ return { ref: release.ref, type: ref.type, outcome: 'unchanged', state: 'released', notices: [] };
169
+ let id;
170
+ if (existing) {
171
+ /* The draft it writes over is kept, and comes back with the same undo as a revert's. */
172
+ if (!sameSource)
173
+ await tx.getRepository(figure_replaced_draft_js_1.FigureReplacedDraft).save({
174
+ domain: { id: domain.id },
175
+ figureId: existing.id,
176
+ kind: 'transfer',
177
+ source: existing.source,
178
+ properties: existing.properties,
179
+ thumbnail: existing.thumbnail,
180
+ thumbnailHash: existing.thumbnailHash,
181
+ state: existing.state,
182
+ version: existing.version,
183
+ writtenSource: draft,
184
+ writtenSourceHash: hashOf(draft),
185
+ requestId: (0, crypto_1.randomUUID)(),
186
+ ...(user ? { creator: { id: user.id } } : {})
187
+ });
188
+ /* Only over what was read: a save that lands in between is not written over without a word. */
189
+ const written = await figures.update({ id: existing.id, domain: { id: domain.id }, source: existing.source }, {
190
+ source: draft,
191
+ ...derived,
192
+ ...catalogue,
193
+ thumbnail: null,
194
+ thumbnailHash,
195
+ thumbnailUpdatedAt: thumbnailHash === existing.thumbnailHash ? existing.thumbnailUpdatedAt : new Date(),
196
+ state: 'draft',
197
+ ...(user ? { updater: { id: user.id } } : {})
198
+ });
199
+ if (written.affected !== 1)
200
+ throw new shell_1.Refusal('figure-import-conflict', { type: ref.type }, '{type} was changed here while it was being taken. Take it again.');
201
+ id = existing.id;
202
+ }
203
+ else {
204
+ const saved = await figures.save({
205
+ type: ref.type,
206
+ namespace,
207
+ source: draft,
208
+ ...derived,
209
+ ...catalogue,
210
+ thumbnailHash,
211
+ ...(thumbnailHash ? { thumbnailUpdatedAt: new Date() } : {}),
212
+ state: 'draft',
213
+ version: 0,
214
+ domain,
215
+ creator: user,
216
+ updater: user
217
+ });
218
+ id = saved.id;
219
+ }
220
+ let state = 'draft';
221
+ let version;
222
+ if (options.mayRelease === false)
223
+ notices.push({ code: 'release-not-allowed' });
224
+ else {
225
+ const row = await figures.findOneOrFail({ where: { id, domain: { id: domain.id } } });
226
+ /*
227
+ New here, the same namespace, and what it releases the very release it was there: the same number, so a board that
228
+ installed it from there sees it installed. Otherwise past both servers' last numbers, so no number already out
229
+ there comes back with other content.
230
+ */
231
+ const releasedHereBefore = await tx.getRepository(figure_history_js_1.FigureHistory).count({ where: { domain: { id: domain.id }, type: ref.type } });
232
+ const same = !existing && !releasedHereBefore && ref.namespace === namespace && hashOf((0, figure_format_js_1.releaseRecordOf)(draft).source) === hashOf(release.source);
233
+ try {
234
+ const released = await (0, figure_release_js_1.releaseFigureRow)(tx, domain, user, row, {
235
+ comment: `${source.url} ${release.ref}`,
236
+ t: options.t,
237
+ lng: options.lng,
238
+ versionFor: lastHere => (same ? ref.version : Math.max(lastHere, ref.version) + 1)
239
+ });
240
+ state = 'released';
241
+ version = released.version;
242
+ }
243
+ catch (e) {
244
+ /* This server's gate said no: the figure stays a draft here, and the reasons are said. */
245
+ if (e instanceof figure_release_js_1.FigureReleaseBlocked)
246
+ notices.push({ code: 'release-blocked', params: { reasons: e.reasons } });
247
+ else if (e instanceof shell_1.Refusal)
248
+ notices.push({ code: 'release-blocked', params: { reasons: [(0, shell_1.speakRefusal)(e, { t: options.t }).message] } });
249
+ else
250
+ throw e;
251
+ }
252
+ }
253
+ await tx.getRepository(figure_transfer_record_js_1.FigureTransferRecord).save({
254
+ domain: { id: domain.id },
255
+ figureId: id,
256
+ outcome: existing ? 'overwritten' : 'created',
257
+ sourceUrl: source.url,
258
+ sourceDomain: source.domain,
259
+ sourceNamespace: ref.namespace,
260
+ sourceFigureId: remoteFigureId,
261
+ sourceState: 'released',
262
+ sourceVersion: ref.version,
263
+ receivedHash: hashOf(release.source),
264
+ writtenHash: hashOf(draft),
265
+ releasedVersion: version ?? null,
266
+ notices,
267
+ exportedAt: release.releasedAt ? new Date(release.releasedAt) : null,
268
+ ...(user ? { creator: { id: user.id }, updater: { id: user.id } } : {})
269
+ });
270
+ return { ref: release.ref, type: ref.type, outcome: existing ? 'overwritten' : 'created', state, ...(version !== undefined ? { version } : {}), notices };
271
+ }
272
+ /** The figures taken from this server before: the other server's figure and version, and what they are here. */
273
+ async function linkPlacesOf(tx, domain, source) {
274
+ const records = await tx.getRepository(figure_transfer_record_js_1.FigureTransferRecord).find({ where: { domain: { id: domain.id }, sourceUrl: source.url } });
275
+ const places = new Map();
276
+ for (const record of records)
277
+ if (record.sourceFigureId && record.sourceVersion != null && record.releasedVersion != null)
278
+ places.set(`${record.sourceFigureId}@${record.sourceVersion}`, { figure: record.figureId, version: record.releasedVersion });
279
+ return places;
280
+ }
281
+ /** The last time a figure was taken from another figure server, for its detail panel ("taken from"). */
282
+ async function transferOriginOf(tx, domain, figureId) {
283
+ return await lastRecordOf(tx, domain, figureId);
284
+ }
285
+ //# sourceMappingURL=figure-import.js.map
@@ -16,11 +16,11 @@ const figure_type_js_1 = require("./figure-type.js");
16
16
  const figure_revert_js_1 = require("./figure-revert.js");
17
17
  const figure_proposal_js_1 = require("./figure-proposal.js");
18
18
  const figure_propose_type_js_1 = require("./figure-propose-type.js");
19
- const figure_format_js_1 = require("./figure-format.js");
19
+ const figure_release_js_1 = require("./figure-release.js");
20
20
  const figure_rename_js_1 = require("./figure-rename.js");
21
21
  const figure_namespace_js_1 = require("./figure-namespace.js");
22
22
  const figure_categories_js_1 = require("./figure-categories.js");
23
- const figure_format_js_2 = require("./figure-format.js");
23
+ const figure_format_js_1 = require("./figure-format.js");
24
24
  const figure_propose_steps_js_1 = require("./figure-propose-steps.js");
25
25
  const figure_ai_trace_js_1 = require("./figure-ai-trace.js");
26
26
  const figure_write_js_1 = require("./figure-write.js");
@@ -163,7 +163,7 @@ let FigureMutation = class FigureMutation {
163
163
  throw new Error((0, figure_rename_js_1.releasedBeforeMessage)(figure.type));
164
164
  }
165
165
  // 형식을 어기면 여기서 던진다. 파생값은 서버가 계산한다.
166
- const { source, derived, violations } = (0, figure_format_js_2.parseSource)(figure.source);
166
+ const { source, derived, violations } = (0, figure_format_js_1.parseSource)(figure.source);
167
167
  await (0, figure_mesh_store_js_1.requireMeshFiles)(tx, domain, source);
168
168
  const { thumbnail, ...rest } = figure;
169
169
  const saved = await repository.save({
@@ -209,7 +209,7 @@ let FigureMutation = class FigureMutation {
209
209
  let violations = [];
210
210
  let source = figure.source;
211
211
  if (patch.source !== undefined && patch.source !== figure.source) {
212
- const parsed = (0, figure_format_js_2.parseSource)(patch.source);
212
+ const parsed = (0, figure_format_js_1.parseSource)(patch.source);
213
213
  await (0, figure_mesh_store_js_1.requireMeshFiles)(tx, domain, parsed.source);
214
214
  source = parsed.source;
215
215
  derived = parsed.derived;
@@ -317,7 +317,6 @@ let FigureMutation = class FigureMutation {
317
317
  async releaseFigure(id, comment, context) {
318
318
  const { domain, user, tx } = context.state;
319
319
  const repository = tx.getRepository(figure_js_1.Figure);
320
- const historyRepository = tx.getRepository(figure_history_js_1.FigureHistory);
321
320
  let figure = await ownFigure(repository, domain, id);
322
321
  if (figure.state === 'released') {
323
322
  throw new Error(`Figure '${figure.type}' 은 이미 발행되어 있다. 고쳐서 다시 내려면 초안으로 되돌린 뒤 발행한다`);
@@ -328,62 +327,7 @@ let FigureMutation = class FigureMutation {
328
327
  Re-read under the claim so a catalogue edit made before it is not overwritten by the old entity. */
329
328
  await (0, figure_write_js_1.compareAndSwapFigure)(criteria => repository.update({ ...criteria, state: figure.state, version: figure.version }, { state: figure.state }), id, domain.id, figure.source);
330
329
  figure = await ownFigure(repository, domain, id);
331
- /* A release promises boards the full name {namespace}/{type}: it goes out only under a namespace the domain owns and has active. */
332
- const namespace = (0, figure_namespace_js_1.namespaceOf)(figure);
333
- await (0, figure_namespace_js_1.assertReleasableNamespace)(tx, domain, namespace, user);
334
- (0, figure_categories_js_1.assertReleasableCategory)(figure.category, figure.type);
335
- /*
336
- ── 게이트는 여기 있어야 한다 ────────────────────────────────────────────
337
- 화면도 같은 판정을 미리 물어(`inspectFigure`) 이유를 보여 주지만, **막는 자리는 이곳뿐이다.**
338
- 물어본 뒤 정본이 바뀌었을 수 있고, 화면을 거치지 않는 부름도 있다.
339
-
340
- 막는 이유는 사유와 함께 낸다. 「발행할 수 없습니다」로 뭉치면 무엇을 고쳐야 하는지 모른다.
341
- */
342
- /*
343
- 직전 발행 버전을 먼저 꺼낸다. 버전 번호를 세는 데도 쓰고, **약속을 깨는 발행인가**를 견주는 데도
344
- 쓴다(ADR-0063 결정 3) — 도면은 type 만 적고 늘 최신 발행 버전을 그리므로, 다시 발행하는 것은
345
- 그 type 을 놓아 둔 모든 도면에게 같은 약속을 다시 하는 일이다.
346
- */
347
- const released = await historyRepository
348
- .createQueryBuilder('history')
349
- .where('history.originalId = :id', { id: figure.id })
350
- .orderBy('history.version', 'DESC')
351
- .limit(1)
352
- .getOne();
353
- const capabilities = await (0, capability_module_store_js_1.prepareCapabilityModules)({ getRepository: shell_1.getRepository }, context.state.domain);
354
- const inspection = (0, figure_format_js_1.inspectSource)(figure.source, released?.source, context.t, figure.type, figure.category, { domain: context.state.domain, lng: context.lng, capabilities });
355
- if (inspection.blocked) {
356
- const reasons = inspection.findings
357
- .filter(finding => finding.blocking)
358
- .map(finding => (finding.at ? `${finding.message} (${finding.at})` : finding.message));
359
- throw new Error(`Figure '${figure.type}' 은 아직 발행할 수 없다 — ${reasons.join(' · ')}`);
360
- }
361
- const nextVersion = released?.version ? Number(released.version) + 1 : 1;
362
- /* What this release records about itself: its format, and what changed against the last one (ADR-0104). */
363
- const record = (0, figure_format_js_1.releaseRecordOf)(figure.source, released?.source);
364
- return await repository.save({
365
- /*
366
- `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.
367
-
368
- 버전 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 버전의 도메인이 비고 그 버전은
369
- 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은
370
- 자리에서 domain 을 함께 넣는다.
371
- */
372
- domain,
373
- ...figure,
374
- version: nextVersion,
375
- state: 'released',
376
- updater: user,
377
- /* 버전 구독자가 이것들을 버전의 comment · assetFormat · kernelVersion · changes 로 옮긴다. Figure 의 칸이 아니다. */
378
- /* The release's own copy, its size range written down; the figure keeps the author's (ADR-0087 decision 6). */
379
- __releaseSource: record.source,
380
- __releaseComment: comment ?? null,
381
- __releaseFormat: record.format,
382
- __releaseKernel: record.kernel,
383
- __releaseChanges: record.changes,
384
- __releaseMetrics: record.metrics,
385
- __releaseTopView: record.topView
386
- });
330
+ return await (0, figure_release_js_1.releaseFigureRow)(tx, domain, user, figure, { comment, t: context.t, lng: context.lng });
387
331
  }
388
332
  /**
389
333
  * 옛 버전으로 되돌린다.
@@ -0,0 +1,24 @@
1
+ import type { EntityManager } from 'typeorm';
2
+ import { Figure } from './figure.js';
3
+ /** A release the gate stopped: the reasons, each as the inspection says it, and where. */
4
+ export declare class FigureReleaseBlocked extends Error {
5
+ readonly reasons: string[];
6
+ constructor(type: string, reasons: string[]);
7
+ }
8
+ export interface FigureReleaseOptions {
9
+ comment?: string | null;
10
+ /** The reader's words for the gate's findings. */
11
+ t?: (key: string, options?: any) => string;
12
+ lng?: string;
13
+ /**
14
+ * The version number this release takes, given the last one this server released of the figure (0 when none). The
15
+ * next number when left out. A figure moved from another figure server takes a number of its own (ADR-0231 decision 4).
16
+ */
17
+ versionFor?: (lastHere: number) => number;
18
+ }
19
+ /**
20
+ * Releases a figure's draft (the row as read under the caller's claim on it): the gate, the version number, the
21
+ * release's own record. One path for a person's release and for a figure moved from another figure server, so a moved
22
+ * figure goes out only as this server would release it (ADR-0231 decision 5).
23
+ */
24
+ export declare function releaseFigureRow(tx: EntityManager, domain: any, user: any, figure: Figure, options?: FigureReleaseOptions): Promise<Figure>;
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FigureReleaseBlocked = void 0;
4
+ exports.releaseFigureRow = releaseFigureRow;
5
+ const shell_1 = require("@things-factory/shell");
6
+ const capability_module_store_js_1 = require("../capability-module/capability-module-store.js");
7
+ const figure_js_1 = require("./figure.js");
8
+ const figure_history_js_1 = require("./figure-history.js");
9
+ const figure_format_js_1 = require("./figure-format.js");
10
+ const figure_namespace_js_1 = require("./figure-namespace.js");
11
+ const figure_categories_js_1 = require("./figure-categories.js");
12
+ /** A release the gate stopped: the reasons, each as the inspection says it, and where. */
13
+ class FigureReleaseBlocked extends Error {
14
+ constructor(type, reasons) {
15
+ super(`Figure '${type}' 은 아직 발행할 수 없다 — ${reasons.join(' · ')}`);
16
+ this.reasons = reasons;
17
+ }
18
+ }
19
+ exports.FigureReleaseBlocked = FigureReleaseBlocked;
20
+ /**
21
+ * Releases a figure's draft (the row as read under the caller's claim on it): the gate, the version number, the
22
+ * release's own record. One path for a person's release and for a figure moved from another figure server, so a moved
23
+ * figure goes out only as this server would release it (ADR-0231 decision 5).
24
+ */
25
+ async function releaseFigureRow(tx, domain, user, figure, options = {}) {
26
+ const repository = tx.getRepository(figure_js_1.Figure);
27
+ const historyRepository = tx.getRepository(figure_history_js_1.FigureHistory);
28
+ /* A release promises boards the full name {namespace}/{type}: it goes out only under a namespace the domain owns and has active. */
29
+ const namespace = (0, figure_namespace_js_1.namespaceOf)(figure);
30
+ await (0, figure_namespace_js_1.assertReleasableNamespace)(tx, domain, namespace, user);
31
+ (0, figure_categories_js_1.assertReleasableCategory)(figure.category, figure.type);
32
+ /*
33
+ ── 게이트는 여기 있어야 한다 ────────────────────────────────────────────
34
+ 화면도 같은 판정을 미리 물어(`inspectFigure`) 이유를 보여 주지만, **막는 자리는 이곳뿐이다.**
35
+ 물어본 뒤 정본이 바뀌었을 수 있고, 화면을 거치지 않는 부름도 있다.
36
+
37
+ 막는 이유는 사유와 함께 낸다. 「발행할 수 없습니다」로 뭉치면 무엇을 고쳐야 하는지 모른다.
38
+ */
39
+ /*
40
+ 직전 발행 버전을 먼저 꺼낸다. 버전 번호를 세는 데도 쓰고, **약속을 깨는 발행인가**를 견주는 데도
41
+ 쓴다(ADR-0063 결정 3) — 도면은 type 만 적고 늘 최신 발행 버전을 그리므로, 다시 발행하는 것은
42
+ 그 type 을 놓아 둔 모든 도면에게 같은 약속을 다시 하는 일이다.
43
+ */
44
+ const released = await historyRepository
45
+ .createQueryBuilder('history')
46
+ .where('history.originalId = :id', { id: figure.id })
47
+ .orderBy('history.version', 'DESC')
48
+ .limit(1)
49
+ .getOne();
50
+ const capabilities = await (0, capability_module_store_js_1.prepareCapabilityModules)({ getRepository: shell_1.getRepository }, domain);
51
+ const inspection = (0, figure_format_js_1.inspectSource)(figure.source, released?.source, options.t, figure.type, figure.category, { domain, lng: options.lng, capabilities });
52
+ if (inspection.blocked) {
53
+ const reasons = inspection.findings
54
+ .filter(finding => finding.blocking)
55
+ .map(finding => (finding.at ? `${finding.message} (${finding.at})` : finding.message));
56
+ throw new FigureReleaseBlocked(figure.type, reasons);
57
+ }
58
+ const lastHere = released?.version ? Number(released.version) : 0;
59
+ const nextVersion = options.versionFor ? options.versionFor(lastHere) : lastHere + 1;
60
+ /* What this release records about itself: its format, and what changed against the last one (ADR-0104). */
61
+ const record = (0, figure_format_js_1.releaseRecordOf)(figure.source, released?.source);
62
+ return await repository.save({
63
+ /*
64
+ `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.
65
+
66
+ 버전 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 버전의 도메인이 비고 그 버전은
67
+ 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은
68
+ 자리에서 domain 을 함께 넣는다.
69
+ */
70
+ domain,
71
+ ...figure,
72
+ version: nextVersion,
73
+ state: 'released',
74
+ updater: user,
75
+ /* 버전 구독자가 이것들을 버전의 comment · assetFormat · kernelVersion · changes 로 옮긴다. Figure 의 칸이 아니다. */
76
+ /* The release's own copy, its size range written down; the figure keeps the author's (ADR-0087 decision 6). */
77
+ __releaseSource: record.source,
78
+ __releaseComment: options.comment ?? null,
79
+ __releaseFormat: record.format,
80
+ __releaseKernel: record.kernel,
81
+ __releaseChanges: record.changes,
82
+ __releaseMetrics: record.metrics,
83
+ __releaseTopView: record.topView
84
+ });
85
+ }
86
+ //# sourceMappingURL=figure-release.js.map
@@ -8,14 +8,16 @@ import { Domain } from '@things-factory/shell';
8
8
  * what a board uses. Kept in the same transaction as the revert that replaces the draft -- kept, or neither happens.
9
9
  * `requestId` makes a retried revert (its answer lost) the same revert, not a second one.
10
10
  *
11
- * An undo of a revert is a revert too (`kind: 'undo'`): it keeps what it replaces the same way.
11
+ * An undo of a revert is a revert too (`kind: 'undo'`): it keeps what it replaces the same way. So does a figure taken in
12
+ * from another figure server over this one (`kind: 'transfer'`, ADR-0231 decision 6): the draft it wrote over comes back
13
+ * with the same undo.
12
14
  */
13
15
  export declare class FigureReplacedDraft {
14
16
  readonly id?: string;
15
17
  domain?: Domain;
16
18
  domainId?: string;
17
19
  figureId?: string;
18
- kind?: 'revert' | 'undo';
20
+ kind?: 'revert' | 'undo' | 'transfer';
19
21
  source?: string;
20
22
  properties?: string;
21
23
  thumbnail?: string;
@@ -14,7 +14,9 @@ const shell_1 = require("@things-factory/shell");
14
14
  * what a board uses. Kept in the same transaction as the revert that replaces the draft -- kept, or neither happens.
15
15
  * `requestId` makes a retried revert (its answer lost) the same revert, not a second one.
16
16
  *
17
- * An undo of a revert is a revert too (`kind: 'undo'`): it keeps what it replaces the same way.
17
+ * An undo of a revert is a revert too (`kind: 'undo'`): it keeps what it replaces the same way. So does a figure taken in
18
+ * from another figure server over this one (`kind: 'transfer'`, ADR-0231 decision 6): the draft it wrote over comes back
19
+ * with the same undo.
18
20
  */
19
21
  let FigureReplacedDraft = class FigureReplacedDraft {
20
22
  };
@@ -39,7 +41,9 @@ tslib_1.__decorate([
39
41
  ], FigureReplacedDraft.prototype, "figureId", void 0);
40
42
  tslib_1.__decorate([
41
43
  (0, typeorm_1.Column)({ default: 'revert' }),
42
- (0, type_graphql_1.Field)({ description: "What replaced it: 'revert' (a released version written over it) or 'undo' (an undo of a revert)." }),
44
+ (0, type_graphql_1.Field)({
45
+ description: "What replaced it: 'revert' (a released version written over it), 'undo' (an undo of a revert) or 'transfer' (the figure taken in from another figure server)."
46
+ }),
43
47
  tslib_1.__metadata("design:type", String)
44
48
  ], FigureReplacedDraft.prototype, "kind", void 0);
45
49
  tslib_1.__decorate([
@@ -0,0 +1,35 @@
1
+ import { User } from '@things-factory/auth-base';
2
+ import { Domain } from '@things-factory/shell';
3
+ /**
4
+ * One figure taken in from another figure server, one row per run (ADR-0231 decision 13). Where it came from, what
5
+ * came and what was written: the detail panel's "taken from", and whether the figure was changed here since -- the
6
+ * next import's "changed on this server" -- read it.
7
+ */
8
+ export declare class FigureTransferRecord {
9
+ readonly id?: string;
10
+ domain?: Domain;
11
+ domainId?: string;
12
+ figureId?: string;
13
+ outcome?: string;
14
+ sourceUrl?: string;
15
+ sourceDomain?: string;
16
+ sourceNamespace?: string;
17
+ sourceFigureId?: string;
18
+ sourceState?: string;
19
+ sourceVersion?: number;
20
+ receivedHash?: string;
21
+ writtenHash?: string;
22
+ releasedVersion?: number;
23
+ notices?: {
24
+ code: string;
25
+ params?: Record<string, unknown>;
26
+ }[];
27
+ exportedBy?: string;
28
+ exportedAt?: Date;
29
+ createdAt?: Date;
30
+ updatedAt?: Date;
31
+ creator?: User;
32
+ creatorId?: string;
33
+ updater?: User;
34
+ updaterId?: string;
35
+ }