@things-factory/figure-service 10.1.37 → 10.1.38

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,44 @@
1
+ import type { Inspection } from './figure-gate.js';
2
+ import type { ParsedSource } from './figure-source.js';
3
+ export type FigureFormat = 'v2' | 'v3';
4
+ /**
5
+ * Which format this source is written in, read from the `version` the asset carries.
6
+ *
7
+ * @throws {FigureSourceError} when the text is not JSON, or carries no version this server knows.
8
+ */
9
+ export declare function formatOf(sourceJson: string): FigureFormat;
10
+ /**
11
+ * Validates a source of either format and computes what the catalogue shows.
12
+ *
13
+ * A V3 asset is measured with `v3CostOf`, which charges the same per-shape estimate V2 charges, so the
14
+ * budget columns mean one thing across the two formats. `score` is left null for V3: the V2 score is a
15
+ * measure of V2 reuse and carrying it over would put a number in the column that nothing computed.
16
+ *
17
+ * @throws {FigureSourceError} when the source breaks its own format.
18
+ */
19
+ export declare function parseAnySource(sourceJson: string): ParsedSource & {
20
+ format: FigureFormat;
21
+ };
22
+ /**
23
+ * Whether this source may be published, and why not.
24
+ *
25
+ * For V3 the judgement is `inspectV3Asset`: every part inside the volume the asset declares, over the whole
26
+ * state range, and the face it says it is mounted on lying in that plane. A verdict reached by sampling is
27
+ * reported as a finding of its own rather than hidden — an author releasing a figure the gate could only
28
+ * sample should be told so, because nothing proved it holds between the states that were checked.
29
+ */
30
+ /** The request's translator. Always called with params — `t(key, undefined)` loses the locale. */
31
+ export type Translate = (key: string, options?: Record<string, unknown>) => string;
32
+ export declare function inspectAnySource(sourceJson?: string | null, releasedJson?: string | null, t?: Translate): Inspection;
33
+ /**
34
+ * What a consumer is handed for a released figure.
35
+ *
36
+ * V2 hands over a compiled blueprint; V3 hands over the asset itself, because the thing that draws a V3 asset
37
+ * — `registerFigureV3` in things-scene — takes the asset and compiles it with the kernel. The format travels
38
+ * with it so the consumer calls the right registration rather than sniffing the payload a second time.
39
+ */
40
+ export declare function consumablePayloadOf(sourceJson: string): {
41
+ format: FigureFormat;
42
+ blueprint?: unknown;
43
+ asset?: unknown;
44
+ };
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatOf = formatOf;
4
+ exports.parseAnySource = parseAnySource;
5
+ exports.inspectAnySource = inspectAnySource;
6
+ exports.consumablePayloadOf = consumablePayloadOf;
7
+ /*
8
+ * Which format a stored source is written in, and one door per job that reads either.
9
+ *
10
+ * ## Why this exists
11
+ *
12
+ * The cutover (ADR-0087) converts assets to V3 and the `source` column holds one or the other while that
13
+ * happens. Every server path that reads a source — saving, publishing, restoring a version, handing a
14
+ * blueprint to a board — had exactly one implementation, the V2 one, so a V3 asset saved through
15
+ * `saveFigureV3` could not be published, restored or drawn. Branching at each of those four places would put
16
+ * the same question in four voices; it is asked once, here.
17
+ *
18
+ * ## How the format is known
19
+ *
20
+ * The asset says so. A V2 source carries `version: 2`; a V3 asset carries `version: 'figure-v3-asset-1'`.
21
+ * Nothing is guessed from the shape of the object: a source that says neither is refused by name, because a
22
+ * source the server cannot identify is one it must not save.
23
+ *
24
+ * ## What is not here
25
+ *
26
+ * No conversion. This door reads what is stored; turning a V2 asset into a V3 one is `convertV2ToV3`, run
27
+ * deliberately against a recoverable copy (the designer's step 3), never as a side effect of a save.
28
+ */
29
+ const figure_model_1 = require("@hatiolab/figure-model");
30
+ const figure_gate_js_1 = require("./figure-gate.js");
31
+ const figure_source_js_1 = require("./figure-source.js");
32
+ /** The version each format stamps on its own source. */
33
+ const V3_ASSET_VERSION = 'figure-v3-asset-1';
34
+ /**
35
+ * Which format this source is written in, read from the `version` the asset carries.
36
+ *
37
+ * @throws {FigureSourceError} when the text is not JSON, or carries no version this server knows.
38
+ */
39
+ function formatOf(sourceJson) {
40
+ let parsed;
41
+ try {
42
+ parsed = JSON.parse(sourceJson);
43
+ }
44
+ catch (e) {
45
+ throw new figure_source_js_1.FigureSourceError([
46
+ { code: 'source-not-json', message: `정본이 JSON 이 아니다: ${e.message}`, at: 'source' }
47
+ ]);
48
+ }
49
+ const version = parsed?.version;
50
+ if (version === V3_ASSET_VERSION)
51
+ return 'v3';
52
+ if (typeof version === 'number')
53
+ return 'v2';
54
+ throw new figure_source_js_1.FigureSourceError([
55
+ {
56
+ code: 'source-format-unknown',
57
+ message: `정본의 판을 알 수 없다 — V2 는 숫자 version 을, V3 자산은 '${V3_ASSET_VERSION}' 을 적는다`,
58
+ at: 'version'
59
+ }
60
+ ]);
61
+ }
62
+ /**
63
+ * Validates a source of either format and computes what the catalogue shows.
64
+ *
65
+ * A V3 asset is measured with `v3CostOf`, which charges the same per-shape estimate V2 charges, so the
66
+ * budget columns mean one thing across the two formats. `score` is left null for V3: the V2 score is a
67
+ * measure of V2 reuse and carrying it over would put a number in the column that nothing computed.
68
+ *
69
+ * @throws {FigureSourceError} when the source breaks its own format.
70
+ */
71
+ function parseAnySource(sourceJson) {
72
+ if (formatOf(sourceJson) === 'v2')
73
+ return { ...(0, figure_source_js_1.parseSource)(sourceJson), format: 'v2' };
74
+ let asset;
75
+ try {
76
+ asset = (0, figure_model_1.parseV3Asset)(sourceJson);
77
+ (0, figure_model_1.compileV3Asset)(asset);
78
+ }
79
+ catch (e) {
80
+ const error = e;
81
+ throw new figure_source_js_1.FigureSourceError([
82
+ { code: error.code ?? 'v3-asset-invalid', message: error.message ?? String(e), at: error.path }
83
+ ]);
84
+ }
85
+ const cost = (0, figure_model_1.v3CostOf)(asset);
86
+ return {
87
+ format: 'v3',
88
+ source: (0, figure_model_1.serializeV3Asset)(asset),
89
+ derived: { score: null, triangles: cost.triangles, groups: cost.groups },
90
+ violations: []
91
+ };
92
+ }
93
+ /**
94
+ * A V3 finding in the words of the release panel.
95
+ *
96
+ * The gate says what it measured as a code and values (`part`, `axis`, `mm`, `degrees`) and an English `detail`
97
+ * for logs. The sentence an author reads is made here, where the request's language is known (ADR-0054) — not in
98
+ * figure-model, which knows no locale, and not on the screen, which would then have a second account of the same
99
+ * refusal. The English line is the fallback when a key is missing, so a missing translation reads as English
100
+ * rather than as the key printed raw.
101
+ *
102
+ * The words are the modeller's: 「공간 선언」 for the volume a figure takes up and 「장착면」 for the face it stands on
103
+ * (`figure.text.mounting-face-explained`). The same register as the V2 blockers since 2026-09-19 — a fact, then
104
+ * the way out — because at ADR-0087 step 5 these become the only findings an author sees.
105
+ */
106
+ function v3Wording(violation, say) {
107
+ const part = violation.part ?? '';
108
+ const axis = (violation.axis ?? '').toUpperCase();
109
+ const mm = violation.mm ?? 0;
110
+ const degrees = violation.degrees ?? 0;
111
+ const key = (field) => `figure.gate.${violation.code.toLowerCase().replace(/_/g, '-')}.${field}`;
112
+ switch (violation.code) {
113
+ case 'PART_OUTSIDE_OCCUPANCY':
114
+ return {
115
+ message: say(key('message'), { part, axis, mm }, `'${part}' goes ${mm} mm past the declared space on ${axis}.`),
116
+ why: say(key('why'), {}, 'The declared space sets the scale a figure is placed at. What lies past it is left out of that scale, so on a board this part lands outside the place given to the figure.'),
117
+ how: say(key('how'), { part, axis, mm }, `Use "fit to parts" to declare the space from the parts again, or move '${part}' ${mm} mm inward on ${axis}.`)
118
+ };
119
+ case 'OCCUPANCY_UNDECLARED':
120
+ return violation.axis
121
+ ? {
122
+ message: say(`figure.gate.occupancy-empty-axis.message`, { axis }, `The declared space is empty on ${axis}.`),
123
+ why: say(key('why'), {}, 'Without a declared space the scale a figure is placed at cannot be set.'),
124
+ how: say(key('how'), {}, 'Use "fit to parts" to declare the space from the parts as they are now.')
125
+ }
126
+ : {
127
+ message: say(key('message'), {}, 'This figure has not declared the space it takes up.'),
128
+ why: say(key('why'), {}, 'Without a declared space the scale a figure is placed at cannot be set.'),
129
+ how: say(key('how'), {}, 'Use "fit to parts" to declare the space from the parts as they are now.')
130
+ };
131
+ case 'PARTS_OFF_PLACEMENT_FACE':
132
+ return {
133
+ message: say(key('message'), { part, mm }, `The mounting face of '${part}' is ${mm} mm off the plane the figure stands on.`),
134
+ why: say(key('why'), {}, 'The figure is declared to stand on that face. If the face does not reach the plane, the figure floats on the board by that much, and whatever is placed on it floats too.'),
135
+ how: say(key('how'), { part, mm }, `Move '${part}' ${mm} mm on Y so the face meets the plane, or choose a different mounting face.`)
136
+ };
137
+ case 'PLACEMENT_FACE_TILTED':
138
+ return {
139
+ message: say(key('message'), { part, degrees }, `The mounting face of '${part}' is tilted ${degrees}° from the plane the figure stands on.`),
140
+ why: say(key('why'), {}, 'A tilted face cannot lie on the plane, so how the figure stands is not settled.'),
141
+ how: say(key('how'), { part }, `Choose a mounting face parallel to the plane, or turn '${part}' upright.`)
142
+ };
143
+ }
144
+ }
145
+ function sayerOf(t) {
146
+ return (key, params, english) => (t ? t(key, { ...params, defaultValue: english }) : english);
147
+ }
148
+ function inspectAnySource(sourceJson, releasedJson, t) {
149
+ if (!sourceJson)
150
+ return (0, figure_gate_js_1.inspectSource)(sourceJson, releasedJson);
151
+ let format;
152
+ try {
153
+ format = formatOf(sourceJson);
154
+ }
155
+ catch (e) {
156
+ const findings = e.findings ?? [{ code: 'source-unreadable', message: String(e) }];
157
+ return { blocked: true, findings: findings.map(f => ({ ...f, blocking: true })) };
158
+ }
159
+ if (format === 'v2')
160
+ return (0, figure_gate_js_1.inspectSource)(sourceJson, releasedJson);
161
+ let inspection;
162
+ try {
163
+ inspection = (0, figure_model_1.inspectV3Asset)((0, figure_model_1.parseV3Asset)(sourceJson));
164
+ }
165
+ catch (e) {
166
+ const error = e;
167
+ return {
168
+ blocked: true,
169
+ findings: [{ code: error.code ?? 'v3-asset-invalid', message: error.message ?? String(e), at: error.path, blocking: true }]
170
+ };
171
+ }
172
+ const say = sayerOf(t);
173
+ const findings = inspection.violations.map(violation => ({
174
+ code: violation.code.toLowerCase().replace(/_/g, '-'),
175
+ ...v3Wording(violation, say),
176
+ at: violation.part,
177
+ blocking: true
178
+ }));
179
+ if (inspection.coverage.method === 'sampled') {
180
+ const states = inspection.coverage.states;
181
+ findings.push({
182
+ code: 'state-range-sampled',
183
+ message: say('figure.gate.state-range-sampled.message', { states }, `The whole range of motion could not be proven, so ${states} poses were checked.`),
184
+ why: say('figure.gate.state-range-sampled.why', {}, 'Between the poses that were checked, a part may still go past the declared space.'),
185
+ how: say('figure.gate.state-range-sampled.how', {}, 'Re-author the motion that could not be proven, and the whole range can be proven.'),
186
+ /* Which operations stopped the proof — a technical list, so it goes where the panel shows a location. */
187
+ at: inspection.coverage.unprovable?.join(' · ') || undefined,
188
+ blocking: false
189
+ });
190
+ }
191
+ /*
192
+ V2 compares a release with the one before it and names the changes that break placed instances (ADR-0063
193
+ decision 3). Nothing does that for a V3 asset yet, and a V2→V3 conversion has no V3 release to compare with.
194
+ The gate says so with the finding V2 uses when it cannot compare, rather than passing in silence — a
195
+ release that was not checked against the last one is a different fact from one that was and was found safe.
196
+ */
197
+ if (releasedJson) {
198
+ findings.push({
199
+ code: 'released-unreadable',
200
+ message: say('figure.gate.v3-released-not-compared.message', {}, 'Not compared with the last release — V3 figures have no comparison between releases yet.'),
201
+ why: say('figure.gate.v3-released-not-compared.why', {}, 'Whether this release breaks the instances already placed has not been checked.'),
202
+ blocking: false
203
+ });
204
+ }
205
+ return { blocked: findings.some(finding => finding.blocking), findings };
206
+ }
207
+ /**
208
+ * What a consumer is handed for a released figure.
209
+ *
210
+ * V2 hands over a compiled blueprint; V3 hands over the asset itself, because the thing that draws a V3 asset
211
+ * — `registerFigureV3` in things-scene — takes the asset and compiles it with the kernel. The format travels
212
+ * with it so the consumer calls the right registration rather than sniffing the payload a second time.
213
+ */
214
+ function consumablePayloadOf(sourceJson) {
215
+ if (formatOf(sourceJson) === 'v2')
216
+ return { format: 'v2', blueprint: (0, figure_model_1.compile)(JSON.parse(sourceJson)) };
217
+ const asset = (0, figure_model_1.parseV3Asset)(sourceJson);
218
+ (0, figure_model_1.compileV3Asset)(asset);
219
+ return { format: 'v3', asset };
220
+ }
221
+ //# sourceMappingURL=figure-format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"figure-format.js","sourceRoot":"","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AK,CAAC,UAAU,CAAC,CAAC,EAAE,CAAA;IACtG,MAAM,KAAK,GAAG,IAAA,2BAAY,EAAC,UAAU,CAAC,CAAA;IACtC,IAAA,6BAAc,EAAC,KAAK,CAAC,CAAA;IACrB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;AAChC,CAAC","sourcesContent":["/*\n * Which format a stored source is written in, and one door per job that reads either.\n *\n * ## Why this exists\n *\n * The cutover (ADR-0087) converts assets to V3 and the `source` column holds one or the other while that\n * happens. Every server path that reads a source — saving, publishing, restoring a version, handing a\n * blueprint to a board — had exactly one implementation, the V2 one, so a V3 asset saved through\n * `saveFigureV3` could not be published, restored or drawn. Branching at each of those four places would put\n * the same question in four voices; it is asked once, here.\n *\n * ## How the format is known\n *\n * The asset says so. A V2 source carries `version: 2`; a V3 asset carries `version: 'figure-v3-asset-1'`.\n * Nothing is guessed from the shape of the object: a source that says neither is refused by name, because a\n * source the server cannot identify is one it must not save.\n *\n * ## What is not here\n *\n * No conversion. This door reads what is stored; turning a V2 asset into a V3 one is `convertV2ToV3`, run\n * deliberately against a recoverable copy (the designer's step 3), never as a side effect of a save.\n */\nimport { compile, compileV3Asset, inspectV3Asset, parseV3Asset, serializeV3Asset, v3CostOf } from '@hatiolab/figure-model'\nimport type { V3ContractError, V3Violation } from '@hatiolab/figure-model'\n\nimport type { GateFinding, Inspection } from './figure-gate.js'\nimport { inspectSource } from './figure-gate.js'\nimport { FigureSourceError, parseSource } from './figure-source.js'\nimport type { ParsedSource } from './figure-source.js'\n\nexport type FigureFormat = 'v2' | 'v3'\n\n/** The version each format stamps on its own source. */\nconst V3_ASSET_VERSION = 'figure-v3-asset-1'\n\n/**\n * Which format this source is written in, read from the `version` the asset carries.\n *\n * @throws {FigureSourceError} when the text is not JSON, or carries no version this server knows.\n */\nexport function formatOf(sourceJson: string): FigureFormat {\n let parsed: unknown\n try {\n parsed = JSON.parse(sourceJson)\n } catch (e) {\n throw new FigureSourceError([\n { code: 'source-not-json', message: `정본이 JSON 이 아니다: ${(e as Error).message}`, at: 'source' }\n ])\n }\n const version = (parsed as { version?: unknown } | null)?.version\n if (version === V3_ASSET_VERSION) return 'v3'\n if (typeof version === 'number') return 'v2'\n throw new FigureSourceError([\n {\n code: 'source-format-unknown',\n message: `정본의 판을 알 수 없다 — V2 는 숫자 version 을, V3 자산은 '${V3_ASSET_VERSION}' 을 적는다`,\n at: 'version'\n }\n ])\n}\n\n/**\n * Validates a source of either format and computes what the catalogue shows.\n *\n * A V3 asset is measured with `v3CostOf`, which charges the same per-shape estimate V2 charges, so the\n * budget columns mean one thing across the two formats. `score` is left null for V3: the V2 score is a\n * measure of V2 reuse and carrying it over would put a number in the column that nothing computed.\n *\n * @throws {FigureSourceError} when the source breaks its own format.\n */\nexport function parseAnySource(sourceJson: string): ParsedSource & { format: FigureFormat } {\n if (formatOf(sourceJson) === 'v2') return { ...parseSource(sourceJson), format: 'v2' }\n\n let asset\n try {\n asset = parseV3Asset(sourceJson)\n compileV3Asset(asset)\n } catch (e) {\n const error = e as V3ContractError & { path?: string }\n throw new FigureSourceError([\n { code: error.code ?? 'v3-asset-invalid', message: error.message ?? String(e), at: error.path }\n ])\n }\n const cost = v3CostOf(asset)\n return {\n format: 'v3',\n source: serializeV3Asset(asset),\n derived: { score: null as unknown as number, triangles: cost.triangles, groups: cost.groups },\n violations: []\n }\n}\n\n/**\n * Whether this source may be published, and why not.\n *\n * For V3 the judgement is `inspectV3Asset`: every part inside the volume the asset declares, over the whole\n * state range, and the face it says it is mounted on lying in that plane. A verdict reached by sampling is\n * reported as a finding of its own rather than hidden — an author releasing a figure the gate could only\n * sample should be told so, because nothing proved it holds between the states that were checked.\n */\n/** The request's translator. Always called with params — `t(key, undefined)` loses the locale. */\nexport type Translate = (key: string, options?: Record<string, unknown>) => string\n\n/**\n * A V3 finding in the words of the release panel.\n *\n * The gate says what it measured as a code and values (`part`, `axis`, `mm`, `degrees`) and an English `detail`\n * for logs. The sentence an author reads is made here, where the request's language is known (ADR-0054) — not in\n * figure-model, which knows no locale, and not on the screen, which would then have a second account of the same\n * refusal. The English line is the fallback when a key is missing, so a missing translation reads as English\n * rather than as the key printed raw.\n *\n * The words are the modeller's: 「공간 선언」 for the volume a figure takes up and 「장착면」 for the face it stands on\n * (`figure.text.mounting-face-explained`). The same register as the V2 blockers since 2026-09-19 — a fact, then\n * the way out — because at ADR-0087 step 5 these become the only findings an author sees.\n */\nfunction v3Wording(violation: V3Violation, say: Say): Pick<GateFinding, 'message' | 'why' | 'how'> {\n const part = violation.part ?? ''\n const axis = (violation.axis ?? '').toUpperCase()\n const mm = violation.mm ?? 0\n const degrees = violation.degrees ?? 0\n const key = (field: string) => `figure.gate.${violation.code.toLowerCase().replace(/_/g, '-')}.${field}`\n\n switch (violation.code) {\n case 'PART_OUTSIDE_OCCUPANCY':\n return {\n message: say(key('message'), { part, axis, mm }, `'${part}' goes ${mm} mm past the declared space on ${axis}.`),\n why: say(key('why'), {}, 'The declared space sets the scale a figure is placed at. What lies past it is left out of that scale, so on a board this part lands outside the place given to the figure.'),\n how: say(key('how'), { part, axis, mm }, `Use \"fit to parts\" to declare the space from the parts again, or move '${part}' ${mm} mm inward on ${axis}.`)\n }\n case 'OCCUPANCY_UNDECLARED':\n return violation.axis\n ? {\n message: say(`figure.gate.occupancy-empty-axis.message`, { axis }, `The declared space is empty on ${axis}.`),\n why: say(key('why'), {}, 'Without a declared space the scale a figure is placed at cannot be set.'),\n how: say(key('how'), {}, 'Use \"fit to parts\" to declare the space from the parts as they are now.')\n }\n : {\n message: say(key('message'), {}, 'This figure has not declared the space it takes up.'),\n why: say(key('why'), {}, 'Without a declared space the scale a figure is placed at cannot be set.'),\n how: say(key('how'), {}, 'Use \"fit to parts\" to declare the space from the parts as they are now.')\n }\n case 'PARTS_OFF_PLACEMENT_FACE':\n return {\n message: say(key('message'), { part, mm }, `The mounting face of '${part}' is ${mm} mm off the plane the figure stands on.`),\n why: say(key('why'), {}, 'The figure is declared to stand on that face. If the face does not reach the plane, the figure floats on the board by that much, and whatever is placed on it floats too.'),\n how: say(key('how'), { part, mm }, `Move '${part}' ${mm} mm on Y so the face meets the plane, or choose a different mounting face.`)\n }\n case 'PLACEMENT_FACE_TILTED':\n return {\n message: say(key('message'), { part, degrees }, `The mounting face of '${part}' is tilted ${degrees}° from the plane the figure stands on.`),\n why: say(key('why'), {}, 'A tilted face cannot lie on the plane, so how the figure stands is not settled.'),\n how: say(key('how'), { part }, `Choose a mounting face parallel to the plane, or turn '${part}' upright.`)\n }\n }\n}\n\ntype Say = (key: string, params: Record<string, string | number>, english: string) => string\n\nfunction sayerOf(t?: Translate): Say {\n return (key, params, english) => (t ? t(key, { ...params, defaultValue: english }) : english)\n}\n\nexport function inspectAnySource(sourceJson?: string | null, releasedJson?: string | null, t?: Translate): Inspection {\n if (!sourceJson) return inspectSource(sourceJson, releasedJson)\n\n let format: FigureFormat\n try {\n format = formatOf(sourceJson)\n } catch (e) {\n const findings = (e as FigureSourceError).findings ?? [{ code: 'source-unreadable', message: String(e) }]\n return { blocked: true, findings: findings.map(f => ({ ...f, blocking: true })) }\n }\n if (format === 'v2') return inspectSource(sourceJson, releasedJson)\n\n let inspection\n try {\n inspection = inspectV3Asset(parseV3Asset(sourceJson))\n } catch (e) {\n const error = e as V3ContractError & { path?: string }\n return {\n blocked: true,\n findings: [{ code: error.code ?? 'v3-asset-invalid', message: error.message ?? String(e), at: error.path, blocking: true }]\n }\n }\n\n const say = sayerOf(t)\n const findings: GateFinding[] = inspection.violations.map(violation => ({\n code: violation.code.toLowerCase().replace(/_/g, '-'),\n ...v3Wording(violation, say),\n at: violation.part,\n blocking: true\n }))\n if (inspection.coverage.method === 'sampled') {\n const states = inspection.coverage.states\n findings.push({\n code: 'state-range-sampled',\n message: say('figure.gate.state-range-sampled.message', { states }, `The whole range of motion could not be proven, so ${states} poses were checked.`),\n why: say('figure.gate.state-range-sampled.why', {}, 'Between the poses that were checked, a part may still go past the declared space.'),\n how: say('figure.gate.state-range-sampled.how', {}, 'Re-author the motion that could not be proven, and the whole range can be proven.'),\n /* Which operations stopped the proof — a technical list, so it goes where the panel shows a location. */\n at: inspection.coverage.unprovable?.join(' · ') || undefined,\n blocking: false\n })\n }\n /*\n V2 compares a release with the one before it and names the changes that break placed instances (ADR-0063\n decision 3). Nothing does that for a V3 asset yet, and a V2→V3 conversion has no V3 release to compare with.\n The gate says so with the finding V2 uses when it cannot compare, rather than passing in silence — a\n release that was not checked against the last one is a different fact from one that was and was found safe.\n */\n if (releasedJson) {\n findings.push({\n code: 'released-unreadable',\n message: say('figure.gate.v3-released-not-compared.message', {}, 'Not compared with the last release — V3 figures have no comparison between releases yet.'),\n why: say('figure.gate.v3-released-not-compared.why', {}, 'Whether this release breaks the instances already placed has not been checked.'),\n blocking: false\n })\n }\n return { blocked: findings.some(finding => finding.blocking), findings }\n}\n\n/**\n * What a consumer is handed for a released figure.\n *\n * V2 hands over a compiled blueprint; V3 hands over the asset itself, because the thing that draws a V3 asset\n * — `registerFigureV3` in things-scene — takes the asset and compiles it with the kernel. The format travels\n * with it so the consumer calls the right registration rather than sniffing the payload a second time.\n */\nexport function consumablePayloadOf(sourceJson: string): { format: FigureFormat; blueprint?: unknown; asset?: unknown } {\n if (formatOf(sourceJson) === 'v2') return { format: 'v2', blueprint: compile(JSON.parse(sourceJson)) }\n const asset = parseV3Asset(sourceJson)\n compileV3Asset(asset)\n return { format: 'v3', asset }\n}\n"]}
@@ -2,7 +2,7 @@ import { Figure } from './figure.js';
2
2
  import { FigurePatch, FigureSaveResult, NewFigure } from './figure-type.js';
3
3
  import { FigureProposal, ProposeRequest } from './figure-propose-type.js';
4
4
  export declare class FigureMutation {
5
- saveFigureV3(source: string, context: ResolverContext, id?: string, expectedSource?: string, creationId?: string): Promise<Figure>;
5
+ saveFigureV3(source: string, context: ResolverContext, id?: string, expectedSource?: string, creationId?: string, thumbnail?: string): Promise<Figure>;
6
6
  createFigure(figure: NewFigure, context: ResolverContext): Promise<FigureSaveResult>;
7
7
  updateFigure(id: string, patch: FigurePatch, context: ResolverContext): Promise<FigureSaveResult>;
8
8
  /**
@@ -8,19 +8,19 @@ const figure_js_1 = require("./figure.js");
8
8
  const figure_history_js_1 = require("./figure-history.js");
9
9
  const figure_type_js_1 = require("./figure-type.js");
10
10
  const figure_propose_type_js_1 = require("./figure-propose-type.js");
11
- const figure_gate_js_1 = require("./figure-gate.js");
11
+ const figure_format_js_1 = require("./figure-format.js");
12
12
  const figure_rename_js_1 = require("./figure-rename.js");
13
- const figure_source_js_1 = require("./figure-source.js");
13
+ const figure_format_js_2 = require("./figure-format.js");
14
14
  const figure_propose_js_1 = require("./figure-propose.js");
15
15
  const figure_v3_write_js_1 = require("./figure-v3-write.js");
16
16
  let FigureMutation = class FigureMutation {
17
- async saveFigureV3(source, context, id, expectedSource, creationId) {
17
+ async saveFigureV3(source, context, id, expectedSource, creationId, thumbnail) {
18
18
  const { domain, user, tx } = context.state;
19
19
  const repository = tx.getRepository(figure_js_1.Figure);
20
20
  if (!id) {
21
21
  if (!creationId || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(creationId))
22
22
  throw Error('새 모델 저장에는 생성 요청 식별자가 필요합니다.');
23
- const prepared = (0, figure_v3_write_js_1.prepareV3Write)(source);
23
+ const prepared = { ...(0, figure_v3_write_js_1.prepareV3Write)(source), ...(0, figure_v3_write_js_1.pictureOf)(thumbnail) };
24
24
  const previous = await repository.findOne({ where: { id: creationId, domain: { id: domain.id } } });
25
25
  if (previous) {
26
26
  if (previous.source !== prepared.source)
@@ -36,7 +36,7 @@ let FigureMutation = class FigureMutation {
36
36
  const figure = await repository.findOne({ where: { id, domain: { id: domain.id } } });
37
37
  if (!figure)
38
38
  throw Error('편집할 Figure를 찾을 수 없습니다.');
39
- const prepared = (0, figure_v3_write_js_1.prepareV3Write)(source, figure, expectedSource);
39
+ const prepared = { ...(0, figure_v3_write_js_1.prepareV3Write)(source, figure, expectedSource), ...(0, figure_v3_write_js_1.pictureOf)(thumbnail, figure) };
40
40
  // Compare-and-swap in the UPDATE itself: supported by SQLite as well as PostgreSQL.
41
41
  // A pessimistic row lock is not supported by the product's SQLite deployment.
42
42
  await (0, figure_v3_write_js_1.compareAndSwapV3)(criteria => repository.update(criteria, { ...prepared, updater: user }), id, domain.id, expectedSource);
@@ -52,7 +52,7 @@ let FigureMutation = class FigureMutation {
52
52
  throw new Error(`타입 이름 '${figure.type}' 은 이미 쓰이고 있다. 만든 뒤에는 고칠 수 없으므로 다른 이름을 고른다`);
53
53
  }
54
54
  // 형식을 어기면 여기서 던진다. 파생값은 서버가 계산한다.
55
- const { source, derived, violations } = (0, figure_source_js_1.parseSource)(figure.source);
55
+ const { source, derived, violations } = (0, figure_format_js_2.parseAnySource)(figure.source);
56
56
  const saved = await repository.save({
57
57
  ...figure,
58
58
  source,
@@ -80,7 +80,7 @@ let FigureMutation = class FigureMutation {
80
80
  let violations = [];
81
81
  let source = figure.source;
82
82
  if (patch.source !== undefined && patch.source !== figure.source) {
83
- const parsed = (0, figure_source_js_1.parseSource)(patch.source);
83
+ const parsed = (0, figure_format_js_2.parseAnySource)(patch.source);
84
84
  source = parsed.source;
85
85
  derived = parsed.derived;
86
86
  violations = parsed.violations;
@@ -202,7 +202,7 @@ let FigureMutation = class FigureMutation {
202
202
  .orderBy('history.version', 'DESC')
203
203
  .limit(1)
204
204
  .getOne();
205
- const inspection = (0, figure_gate_js_1.inspectSource)(figure.source, released?.source);
205
+ const inspection = (0, figure_format_js_1.inspectAnySource)(figure.source, released?.source, context.t);
206
206
  if (inspection.blocked) {
207
207
  const reasons = inspection.findings
208
208
  .filter(finding => finding.blocking)
@@ -262,7 +262,7 @@ let FigureMutation = class FigureMutation {
262
262
  throw new Error(`Figure '${figure.type}' 에 ${version} 판이 없다`);
263
263
  }
264
264
  /* 형식 검사도 다시 받는다 — 옛 판이 오늘의 형식을 어길 수 있고, 그것을 조용히 들이지 않는다. */
265
- const { source, derived, violations } = (0, figure_source_js_1.parseSource)(history.source);
265
+ const { source, derived, violations } = (0, figure_format_js_2.parseAnySource)(history.source);
266
266
  const saved = await repository.save({
267
267
  /*
268
268
  `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.
@@ -357,8 +357,9 @@ tslib_1.__decorate([
357
357
  tslib_1.__param(2, (0, type_graphql_1.Arg)('id', { nullable: true })),
358
358
  tslib_1.__param(3, (0, type_graphql_1.Arg)('expectedSource', { nullable: true })),
359
359
  tslib_1.__param(4, (0, type_graphql_1.Arg)('creationId', { nullable: true })),
360
+ tslib_1.__param(5, (0, type_graphql_1.Arg)('thumbnail', { nullable: true })),
360
361
  tslib_1.__metadata("design:type", Function),
361
- tslib_1.__metadata("design:paramtypes", [String, Object, String, String, String]),
362
+ tslib_1.__metadata("design:paramtypes", [String, Object, String, String, String, String]),
362
363
  tslib_1.__metadata("design:returntype", Promise)
363
364
  ], FigureMutation.prototype, "saveFigureV3", null);
364
365
  tslib_1.__decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"figure-mutation.js","sourceRoot":"","sources":["../../../server/service/figure/figure-mutation.ts"],"names":[],"mappings":";;;;AAAA,qCAA4B;AAC5B,+CAAsE;AAItE,2CAAoC;AACpC,2DAAmD;AACnD,qDAA2E;AAC3E,qEAAyE;AACzE,qDAAgD;AAChD,yDAAiE;AACjE,yDAAgD;AAChD,2DAAmE;AACnE,6DAAuE;AAGhE,IAAM,cAAc,GAApB,MAAM,cAAc;IAInB,AAAN,KAAK,CAAC,YAAY,CACD,MAAc,EACtB,OAAwB,EACA,EAAW,EACC,cAAuB,EAC3B,UAAmB;QAE1D,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,CAAA;QAC1C,MAAM,UAAU,GAAG,EAAE,CAAC,aAAa,CAAC,kBAAM,CAAC,CAAA;QAC3C,IAAI,CAAC,EAAE,EAAE,CAAC;YACR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Q/C;AAiBK;IAJL,IAAA,wBAAS,EAAC,iFAAiF,CAAC;IAC5F,IAAA,uBAAQ,EAAC,OAAO,CAAC,EAAE,CAAC,uCAAc,EAAE;QACnC,WAAW,EAAE,oFAAoF;KAClG,CAAC;IACmB,mBAAA,IAAA,kBAAG,EAAC,SAAS,CAAC,CAAA;;6CAAU,uCAAc;;mDA6C1D;yBAnaU,cAAc;IAD1B,IAAA,uBAAQ,EAAC,kBAAM,CAAC;GACJ,cAAc,CAqa1B","sourcesContent":["import { In } from 'typeorm'\nimport { Arg, Ctx, Directive, Mutation, Resolver } from 'type-graphql'\n\nimport { getRepository } from '@things-factory/shell'\n\nimport { Figure } from './figure.js'\nimport { FigureHistory } from './figure-history.js'\nimport { FigurePatch, FigureSaveResult, NewFigure } from './figure-type.js'\nimport { FigureProposal, ProposeRequest } from './figure-propose-type.js'\nimport { inspectSource } from './figure-gate.js'\nimport { renameDraftType, renameFacts } from './figure-rename.js'\nimport { parseSource } from './figure-source.js'\nimport { ProposeFailure, proposeFigure } from './figure-propose.js'\nimport { prepareV3Write, compareAndSwapV3 } from './figure-v3-write.js'\n\n@Resolver(Figure)\nexport class FigureMutation {\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Figure, { description: 'Save a V3 asset draft using an exact-source concurrency check.' })\n async saveFigureV3(\n @Arg('source') source: string,\n @Ctx() context: ResolverContext,\n @Arg('id', { nullable: true }) id?: string,\n @Arg('expectedSource', { nullable: true }) expectedSource?: string,\n @Arg('creationId', { nullable: true }) creationId?: string\n ): Promise<Figure> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n if (!id) {\n if (!creationId || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(creationId))\n throw Error('새 모델 저장에는 생성 요청 식별자가 필요합니다.')\n const prepared = prepareV3Write(source)\n const previous = await repository.findOne({ where: { id: creationId, domain: { id: domain.id } } })\n if (previous) {\n if (previous.source !== prepared.source) throw Error('이 생성 요청은 이미 다른 내용으로 저장되었습니다. 저장된 모델을 다시 열어 주세요.')\n return previous\n }\n // insert, not save: a concurrent retry must never turn into an unchecked overwrite.\n await repository.insert({ ...prepared, id: creationId, type: `FIGURE_${creationId.replace(/-/g, '').toUpperCase()}`,\n domain, creator: user, updater: user })\n return repository.findOneOrFail({ where: { id: creationId, domain: { id: domain.id } } })\n }\n // Exact tenant ownership: an inherited catalog entry is not writable in the child domain.\n const figure = await repository.findOne({ where: { id, domain: { id: domain.id } } })\n if (!figure) throw Error('편집할 Figure를 찾을 수 없습니다.')\n const prepared = prepareV3Write(source, figure, expectedSource)\n // Compare-and-swap in the UPDATE itself: supported by SQLite as well as PostgreSQL.\n // A pessimistic row lock is not supported by the product's SQLite deployment.\n await compareAndSwapV3(criteria => repository.update(criteria, { ...prepared, updater: user }),\n id, domain.id, expectedSource)\n return repository.findOneOrFail({ where: { id, domain: { id: domain.id } } })\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Creates a figure. Rejects when the source violates the format.' })\n async createFigure(\n @Arg('figure') figure: NewFigure,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n\n // 타입 이름은 도메인 안에서 유일하다. 유니크 인덱스가 있지만 여기서 먼저 본다 —\n // DB 오류 문구는 저작자에게 아무 말도 해 주지 못한다.\n const taken = await repository.findOne({ where: { domain: { id: domain.id }, type: figure.type } })\n if (taken) {\n throw new Error(`타입 이름 '${figure.type}' 은 이미 쓰이고 있다. 만든 뒤에는 고칠 수 없으므로 다른 이름을 고른다`)\n }\n\n // 형식을 어기면 여기서 던진다. 파생값은 서버가 계산한다.\n const { source, derived, violations } = parseSource(figure.source)\n\n const saved = await repository.save({\n ...figure,\n source,\n ...derived,\n state: figure.state ?? 'draft',\n thumbnailUpdatedAt: figure.thumbnail ? new Date() : undefined,\n domain,\n creator: user,\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Updates a figure. The `type` field cannot be changed.' })\n async updateFigure(\n @Arg('id') id: string,\n @Arg('patch') patch: FigurePatch,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n\n const figure = await repository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n // 정본이 바뀌면 파생값도 다시 계산한다. 안 바뀌었으면 손대지 않는다 —\n // 이름만 고쳤는데 점수가 흔들리면 읽는 사람이 원인을 못 찾는다.\n let derived: { score: number; triangles: number; groups: number } | undefined\n let violations = []\n let source = figure.source\n\n if (patch.source !== undefined && patch.source !== figure.source) {\n const parsed = parseSource(patch.source)\n source = parsed.source\n derived = parsed.derived\n violations = parsed.violations\n }\n\n /*\n **타입은 발행 전에만 바뀐다** — ADR-0063 결정 4.\n\n 발행된 뒤에는 이미 배치된 도면이 이 이름을 가리키고, 바꾸면 그 도면이 아무 오류 없이\n 빈 자리가 된다. 발행된 적 없는 도형은 가리키는 도면이 있을 수 없다 — 도면은 최신\n 발행판을 그리므로 그려질 자리가 없다.\n\n 행과 정본 둘 다 고친다. 정본 안에도 `type` 이 있어서 한쪽만 고치면 저장된 JSON 과\n 행이 다른 이름을 말하고, 발행할 때 어느 쪽이 도면에 적히는지가 갈린다.\n */\n let renamed: string | undefined\n if (patch.type !== undefined && patch.type !== figure.type) {\n const change = await this.renameType(figure, domain, patch.type, source, tx)\n renamed = change.type\n source = change.source\n }\n\n /*\n **판 번호는 여기서 손대지 않는다.** 저장은 저작이고, 판은 발행에서 생긴다(`releaseFigure`).\n board 의 `updateBoard` 도 같다 — 저장 경로에는 version 이 없다.\n */\n const saved = await repository.save({\n /*\n `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.\n\n 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은\n 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은\n 자리에서 domain 을 함께 넣는다.\n */\n domain,\n ...figure,\n ...patch,\n /* 앞뒤 공백을 떼고 겹침까지 본 이름. `patch.type` 을 그대로 두면 다듬기 전 값이 들어간다. */\n ...(renamed !== undefined ? { type: renamed } : {}),\n source,\n /*\n **고치면 발행이 풀린다.**\n\n 발행은 「이 판을 써도 된다」는 약속이고, 그 뒤에 정본이 바뀌면 약속한 것과 배포된 것이\n 달라진다. 그래서 저장은 언제나 초안으로 되돌리고, 다시 내보내려면 발행을 한 번 더 한다\n (판 번호가 하나 오르고 판본이 하나 더 남는다). board 의 `updateBoard` 가 같은 한 줄을 쓴다.\n */\n state: 'draft',\n ...(derived ?? {}),\n // 썸네일이 **썸네일로서** 바뀐 때만 시각을 갱신한다. 이름·설명 변경에는 안 건드린다.\n thumbnailUpdatedAt:\n patch.thumbnail !== undefined && patch.thumbnail !== figure.thumbnail\n ? new Date()\n : figure.thumbnailUpdatedAt,\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n /**\n * 초안의 타입을 고친다 — 규칙은 `figure-rename.ts`, 여기서는 그 규칙이 볼 **사실만** 읽는다.\n *\n * 겹침은 DB 인덱스(`ix_figure_1`)도 잡지만 먼저 읽어 본다. 인덱스가 던지는 말은 저작자가\n * 읽을 것이 못 되고, 어느 이름이 이미 쓰였는지도 안 알려 준다.\n */\n private async renameType(\n figure: Figure,\n domain: { id: string },\n wanted: string,\n source: string,\n tx: { getRepository: <T>(target: new () => T) => any }\n ): Promise<{ type: string; source: string }> {\n /* 읽어 온 엔티티에는 관계가 안 실려 있다 — 도메인은 문맥에서 온 것을 쓴다. */\n const facts = await renameFacts(\n { figures: tx.getRepository(Figure), histories: tx.getRepository(FigureHistory) },\n figure,\n domain,\n wanted\n )\n\n return renameDraftType({ type: figure.type, source }, wanted, facts)\n }\n\n /**\n * 발행한다 — **판이 생기는 유일한 자리.**\n *\n * ## 무엇이 일어나나\n *\n * `state` 가 `released` 가 되고, 판 번호가 하나 오르고, 그 순간의 도형이 판본으로 남는다\n * (`FigureHistory` — 스냅샷은 구독자가 뜬다). 저작 중 저장은 이 셋 중 아무것도 하지 않는다.\n *\n * ## 왜 이미 발행된 것을 거절하나\n *\n * 발행은 소비처에게 하는 약속이다. 같은 판을 두 번 발행하면 무엇이 약속인지 흐려진다. 고쳐서\n * 다시 내려면 초안으로 되돌린 뒤 발행한다 — board 가 같은 규칙이다.\n *\n * ## 번호는 판본에서 센다\n *\n * 도형의 현재 번호가 아니라 **판본의 최대 번호 + 1** 이다. 되돌리기로 옛 판이 현재가 되어도\n * 다음 발행이 이미 쓴 번호를 다시 쓰지 않는다.\n *\n * ## 게이트를 통과해야 한다\n *\n * 크기를 바꿨을 때 조각이 갈라지는 도형은 발행되지 않는다(`figure-gate.ts`). 소비처는 형상을\n * 늘려 쓰므로 — 그것이 이 형식의 값이다 — 늘려도 견디는지가 약속의 일부다. 화면은 같은 판정을\n * `inspectFigure` 로 미리 물어 이유를 보여 준다.\n */\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Figure, { description: 'Releases a figure — raises its version and keeps the released state as history.' })\n async releaseFigure(\n @Arg('id') id: string,\n @Arg('comment', { nullable: true }) comment: string,\n @Ctx() context: ResolverContext\n ): Promise<Figure> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n const historyRepository = tx.getRepository(FigureHistory)\n\n const figure = await repository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n if (figure.state === 'released') {\n throw new Error(`Figure '${figure.type}' 은 이미 발행되어 있다. 고쳐서 다시 내려면 초안으로 되돌린 뒤 발행한다`)\n }\n\n /*\n ── 게이트는 여기 있어야 한다 ────────────────────────────────────────────\n 화면도 같은 판정을 미리 물어(`inspectFigure`) 이유를 보여 주지만, **막는 자리는 이곳뿐이다.**\n 물어본 뒤 정본이 바뀌었을 수 있고, 화면을 거치지 않는 부름도 있다.\n\n 막는 이유는 사유와 함께 낸다. 「발행할 수 없습니다」로 뭉치면 무엇을 고쳐야 하는지 모른다.\n */\n /*\n 직전 발행판을 먼저 꺼낸다. 판 번호를 세는 데도 쓰고, **약속을 깨는 발행인가**를 견주는 데도\n 쓴다(ADR-0063 결정 3) — 도면은 type 만 적고 늘 최신 발행판을 그리므로, 다시 발행하는 것은\n 그 type 을 놓아 둔 모든 도면에게 같은 약속을 다시 하는 일이다.\n */\n const released = await historyRepository\n .createQueryBuilder('history')\n .where('history.originalId = :id', { id: figure.id })\n .orderBy('history.version', 'DESC')\n .limit(1)\n .getOne()\n\n const inspection = inspectSource(figure.source, released?.source)\n if (inspection.blocked) {\n const reasons = inspection.findings\n .filter(finding => finding.blocking)\n .map(finding => (finding.at ? `${finding.message} (${finding.at})` : finding.message))\n\n throw new Error(`Figure '${figure.type}' 은 아직 발행할 수 없다 — ${reasons.join(' · ')}`)\n }\n\n const nextVersion = released?.version ? Number(released.version) + 1 : 1\n\n return await repository.save({\n /*\n `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.\n\n 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은\n 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은\n 자리에서 domain 을 함께 넣는다.\n */\n domain,\n ...figure,\n version: nextVersion,\n state: 'released',\n updater: user,\n /* 판본 구독자가 이것을 판본의 comment 로 옮긴다. Figure 의 칸이 아니다. */\n __releaseComment: comment ?? null\n } as any)\n }\n\n /**\n * 옛 판으로 되돌린다.\n *\n * ## 무엇이 돌아오나\n *\n * 그 판의 **정본과 속성 정의, 그리고 그림**이다. 이름·설명·분류는 그대로 둔다 — 그것들은 언제든\n * 바꿔도 안전한 카탈로그의 말이고, 되돌리기가 개명까지 되돌리면 사람이 시키지 않은 일을 한다.\n *\n * ## 되돌려도 발행은 아니다\n *\n * 초안으로 돌아온다. 다시 내보내려면 발행을 한 번 더 하고, 그때 판 번호는 **이미 쓴 번호 다음**을\n * 받는다 — 3판을 되살렸다고 다시 3판이 되지 않는다. board 도 같다.\n *\n * ## 비용은 다시 잰다\n *\n * 판본이 든 점수·삼각형은 **그때의 형식**으로 잰 값이다. 지금 이 도형이 그 내용이 되었으므로\n * 오늘 기준으로 다시 계산한다. 옛 값은 판본에 그대로 남아 있다.\n */\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Reverts a figure to one of its released versions. It comes back as a draft.' })\n async revertFigureVersion(\n @Arg('id') id: string,\n @Arg('version') version: number,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n const historyRepository = tx.getRepository(FigureHistory)\n\n const figure = await repository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n const history = await historyRepository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, originalId: id, version }\n })\n if (!history) {\n throw new Error(`Figure '${figure.type}' 에 ${version} 판이 없다`)\n }\n\n /* 형식 검사도 다시 받는다 — 옛 판이 오늘의 형식을 어길 수 있고, 그것을 조용히 들이지 않는다. */\n const { source, derived, violations } = parseSource(history.source)\n\n const saved = await repository.save({\n /*\n `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.\n\n 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은\n 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은\n 자리에서 domain 을 함께 넣는다.\n */\n domain,\n ...figure,\n source,\n ...derived,\n properties: history.properties,\n thumbnail: history.thumbnail,\n thumbnailUpdatedAt: history.thumbnail === figure.thumbnail ? figure.thumbnailUpdatedAt : new Date(),\n state: 'draft',\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Boolean, { description: 'Soft-deletes a figure.' })\n async deleteFigure(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<boolean> {\n const { domain, tx } = context.state\n\n // 소프트 삭제다 — 이미 배치된 도면이 이 타입을 참조할 수 있으므로 행을 지우지\n // 않는다. 되살릴 길을 남긴다.\n await tx.getRepository(Figure).softDelete({ domain: { id: domain.id }, id })\n\n return true\n }\n\n /**\n * 저작 보조에게 후보를 시킨다.\n *\n * **저장하지 않는다.** 후보를 돌려줄 뿐이고, 정본이 되는 것은 저작자가 보고 받은\n * 뒤다. AI 가 정본에 직접 쓰면 저작자가 무엇이 자기 것이고 무엇이 기계 것인지\n * 모르게 된다.\n *\n * 형식을 어긴 후보는 여기까지 오지 않는다 — `proposeFigure` 가 사유를 모델에\n * 돌려주고 다시 시킨다. 끝내 못 만들면 **사유와 함께 던진다.** 반쯤 만든 것을\n * 돌려주지 않는다.\n */\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureProposal, {\n description: 'Asks the authoring assistant for a figure. Returns a candidate — nothing is saved.'\n })\n async proposeFigure(@Arg('request') request: ProposeRequest): Promise<FigureProposal> {\n // 그림은 메모리로 받는다. 참고용이라 저장하지 않는다 — 남기면 지울 사람이 없다.\n let image\n if (request.image) {\n const file = await request.image\n const chunks: Buffer[] = []\n for await (const chunk of file.createReadStream()) {\n chunks.push(chunk as Buffer)\n }\n image = { data: Buffer.concat(chunks), mediaType: file.mimetype as never }\n }\n\n try {\n const result = await proposeFigure({\n prompt: request.prompt,\n base: request.base ? JSON.parse(request.base) : undefined,\n type: request.type,\n palette: request.palette,\n refine: request.refine,\n feedback: request.feedback,\n image\n })\n\n return {\n source: JSON.stringify(result.source),\n score: Math.round(result.score.score),\n grade: result.score.grade,\n triangles: result.cost.triangles,\n groups: result.cost.groups,\n quality: {\n ...result.quality,\n visualRegions: result.quality.visual.regions,\n visualCoverage: result.quality.visual.coverage,\n visualReadability: result.quality.visual.readability\n },\n violations: result.violations,\n attempts: result.attempts\n }\n } catch (e) {\n if (e instanceof ProposeFailure) {\n // 사유를 삼키지 않는다. 저작자가 무엇이 막혔는지 알아야 말을 고쳐 다시 시킨다.\n throw new Error([e.message, ...e.reasons].join('\\n'))\n }\n throw e\n }\n }\n\n}\n"]}
1
+ {"version":3,"file":"figure-mutation.js","sourceRoot":"","sources":["../../../server/service/figure/figure-mutation.ts"],"names":[],"mappings":";;;;AAAA,qCAA4B;AAC5B,+CAAsE;AAItE,2CAAoC;AACpC,2DAAmD;AACnD,qDAA2E;AAC3E,qEAAyE;AACzE,yDAAqD;AACrD,yDAAiE;AACjE,yDAAmD;AACnD,2DAAmE;AACnE,6DAAkF;AAG3E,IAAM,cAAc,GAApB,MAAM,cAAc;IAInB,AAAN,KAAK,CAAC,YAAY,CACD,MAAc,EACtB,OAAwB,EACA,EAAW,EACC,cAAuB,EAC3B,UAAmB,EACpB,SAAkB;QAExD,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,CAAA;QAC1C,MAAM,UAAU,GAAG,EAAE,CAAC,aAAa,CAAC,kBAAM,CAAC,CAAA;QAC3C,IAAI,CAAC,EAAE,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A,wBAAS,EAAC,cAAc,CAAC;IACzB,IAAA,wBAAS,EAAC,iFAAiF,CAAC;IAC5F,IAAA,uBAAQ,EAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,WAAW,EAAE,wBAAwB,EAAE,CAAC;IACpD,mBAAA,IAAA,kBAAG,EAAC,IAAI,CAAC,CAAA;IAAc,mBAAA,IAAA,kBAAG,GAAE,CAAA;;;;kDAQ/C;AAiBK;IAJL,IAAA,wBAAS,EAAC,iFAAiF,CAAC;IAC5F,IAAA,uBAAQ,EAAC,OAAO,CAAC,EAAE,CAAC,uCAAc,EAAE;QACnC,WAAW,EAAE,oFAAoF;KAClG,CAAC;IACmB,mBAAA,IAAA,kBAAG,EAAC,SAAS,CAAC,CAAA;;6CAAU,uCAAc;;mDA6C1D;yBApaU,cAAc;IAD1B,IAAA,uBAAQ,EAAC,kBAAM,CAAC;GACJ,cAAc,CAsa1B","sourcesContent":["import { In } from 'typeorm'\nimport { Arg, Ctx, Directive, Mutation, Resolver } from 'type-graphql'\n\nimport { getRepository } from '@things-factory/shell'\n\nimport { Figure } from './figure.js'\nimport { FigureHistory } from './figure-history.js'\nimport { FigurePatch, FigureSaveResult, NewFigure } from './figure-type.js'\nimport { FigureProposal, ProposeRequest } from './figure-propose-type.js'\nimport { inspectAnySource } from './figure-format.js'\nimport { renameDraftType, renameFacts } from './figure-rename.js'\nimport { parseAnySource } from './figure-format.js'\nimport { ProposeFailure, proposeFigure } from './figure-propose.js'\nimport { prepareV3Write, compareAndSwapV3, pictureOf } from './figure-v3-write.js'\n\n@Resolver(Figure)\nexport class FigureMutation {\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Figure, { description: 'Save a V3 asset draft using an exact-source concurrency check.' })\n async saveFigureV3(\n @Arg('source') source: string,\n @Ctx() context: ResolverContext,\n @Arg('id', { nullable: true }) id?: string,\n @Arg('expectedSource', { nullable: true }) expectedSource?: string,\n @Arg('creationId', { nullable: true }) creationId?: string,\n @Arg('thumbnail', { nullable: true }) thumbnail?: string\n ): Promise<Figure> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n if (!id) {\n if (!creationId || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(creationId))\n throw Error('새 모델 저장에는 생성 요청 식별자가 필요합니다.')\n const prepared = { ...prepareV3Write(source), ...pictureOf(thumbnail) }\n const previous = await repository.findOne({ where: { id: creationId, domain: { id: domain.id } } })\n if (previous) {\n if (previous.source !== prepared.source) throw Error('이 생성 요청은 이미 다른 내용으로 저장되었습니다. 저장된 모델을 다시 열어 주세요.')\n return previous\n }\n // insert, not save: a concurrent retry must never turn into an unchecked overwrite.\n await repository.insert({ ...prepared, id: creationId, type: `FIGURE_${creationId.replace(/-/g, '').toUpperCase()}`,\n domain, creator: user, updater: user })\n return repository.findOneOrFail({ where: { id: creationId, domain: { id: domain.id } } })\n }\n // Exact tenant ownership: an inherited catalog entry is not writable in the child domain.\n const figure = await repository.findOne({ where: { id, domain: { id: domain.id } } })\n if (!figure) throw Error('편집할 Figure를 찾을 수 없습니다.')\n const prepared = { ...prepareV3Write(source, figure, expectedSource), ...pictureOf(thumbnail, figure) }\n // Compare-and-swap in the UPDATE itself: supported by SQLite as well as PostgreSQL.\n // A pessimistic row lock is not supported by the product's SQLite deployment.\n await compareAndSwapV3(criteria => repository.update(criteria, { ...prepared, updater: user }),\n id, domain.id, expectedSource)\n return repository.findOneOrFail({ where: { id, domain: { id: domain.id } } })\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Creates a figure. Rejects when the source violates the format.' })\n async createFigure(\n @Arg('figure') figure: NewFigure,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n\n // 타입 이름은 도메인 안에서 유일하다. 유니크 인덱스가 있지만 여기서 먼저 본다 —\n // DB 오류 문구는 저작자에게 아무 말도 해 주지 못한다.\n const taken = await repository.findOne({ where: { domain: { id: domain.id }, type: figure.type } })\n if (taken) {\n throw new Error(`타입 이름 '${figure.type}' 은 이미 쓰이고 있다. 만든 뒤에는 고칠 수 없으므로 다른 이름을 고른다`)\n }\n\n // 형식을 어기면 여기서 던진다. 파생값은 서버가 계산한다.\n const { source, derived, violations } = parseAnySource(figure.source)\n\n const saved = await repository.save({\n ...figure,\n source,\n ...derived,\n state: figure.state ?? 'draft',\n thumbnailUpdatedAt: figure.thumbnail ? new Date() : undefined,\n domain,\n creator: user,\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Updates a figure. The `type` field cannot be changed.' })\n async updateFigure(\n @Arg('id') id: string,\n @Arg('patch') patch: FigurePatch,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n\n const figure = await repository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n // 정본이 바뀌면 파생값도 다시 계산한다. 안 바뀌었으면 손대지 않는다 —\n // 이름만 고쳤는데 점수가 흔들리면 읽는 사람이 원인을 못 찾는다.\n let derived: { score: number; triangles: number; groups: number } | undefined\n let violations = []\n let source = figure.source\n\n if (patch.source !== undefined && patch.source !== figure.source) {\n const parsed = parseAnySource(patch.source)\n source = parsed.source\n derived = parsed.derived\n violations = parsed.violations\n }\n\n /*\n **타입은 발행 전에만 바뀐다** — ADR-0063 결정 4.\n\n 발행된 뒤에는 이미 배치된 도면이 이 이름을 가리키고, 바꾸면 그 도면이 아무 오류 없이\n 빈 자리가 된다. 발행된 적 없는 도형은 가리키는 도면이 있을 수 없다 — 도면은 최신\n 발행판을 그리므로 그려질 자리가 없다.\n\n 행과 정본 둘 다 고친다. 정본 안에도 `type` 이 있어서 한쪽만 고치면 저장된 JSON 과\n 행이 다른 이름을 말하고, 발행할 때 어느 쪽이 도면에 적히는지가 갈린다.\n */\n let renamed: string | undefined\n if (patch.type !== undefined && patch.type !== figure.type) {\n const change = await this.renameType(figure, domain, patch.type, source, tx)\n renamed = change.type\n source = change.source\n }\n\n /*\n **판 번호는 여기서 손대지 않는다.** 저장은 저작이고, 판은 발행에서 생긴다(`releaseFigure`).\n board 의 `updateBoard` 도 같다 — 저장 경로에는 version 이 없다.\n */\n const saved = await repository.save({\n /*\n `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.\n\n 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은\n 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은\n 자리에서 domain 을 함께 넣는다.\n */\n domain,\n ...figure,\n ...patch,\n /* 앞뒤 공백을 떼고 겹침까지 본 이름. `patch.type` 을 그대로 두면 다듬기 전 값이 들어간다. */\n ...(renamed !== undefined ? { type: renamed } : {}),\n source,\n /*\n **고치면 발행이 풀린다.**\n\n 발행은 「이 판을 써도 된다」는 약속이고, 그 뒤에 정본이 바뀌면 약속한 것과 배포된 것이\n 달라진다. 그래서 저장은 언제나 초안으로 되돌리고, 다시 내보내려면 발행을 한 번 더 한다\n (판 번호가 하나 오르고 판본이 하나 더 남는다). board 의 `updateBoard` 가 같은 한 줄을 쓴다.\n */\n state: 'draft',\n ...(derived ?? {}),\n // 썸네일이 **썸네일로서** 바뀐 때만 시각을 갱신한다. 이름·설명 변경에는 안 건드린다.\n thumbnailUpdatedAt:\n patch.thumbnail !== undefined && patch.thumbnail !== figure.thumbnail\n ? new Date()\n : figure.thumbnailUpdatedAt,\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n /**\n * 초안의 타입을 고친다 — 규칙은 `figure-rename.ts`, 여기서는 그 규칙이 볼 **사실만** 읽는다.\n *\n * 겹침은 DB 인덱스(`ix_figure_1`)도 잡지만 먼저 읽어 본다. 인덱스가 던지는 말은 저작자가\n * 읽을 것이 못 되고, 어느 이름이 이미 쓰였는지도 안 알려 준다.\n */\n private async renameType(\n figure: Figure,\n domain: { id: string },\n wanted: string,\n source: string,\n tx: { getRepository: <T>(target: new () => T) => any }\n ): Promise<{ type: string; source: string }> {\n /* 읽어 온 엔티티에는 관계가 안 실려 있다 — 도메인은 문맥에서 온 것을 쓴다. */\n const facts = await renameFacts(\n { figures: tx.getRepository(Figure), histories: tx.getRepository(FigureHistory) },\n figure,\n domain,\n wanted\n )\n\n return renameDraftType({ type: figure.type, source }, wanted, facts)\n }\n\n /**\n * 발행한다 — **판이 생기는 유일한 자리.**\n *\n * ## 무엇이 일어나나\n *\n * `state` 가 `released` 가 되고, 판 번호가 하나 오르고, 그 순간의 도형이 판본으로 남는다\n * (`FigureHistory` — 스냅샷은 구독자가 뜬다). 저작 중 저장은 이 셋 중 아무것도 하지 않는다.\n *\n * ## 왜 이미 발행된 것을 거절하나\n *\n * 발행은 소비처에게 하는 약속이다. 같은 판을 두 번 발행하면 무엇이 약속인지 흐려진다. 고쳐서\n * 다시 내려면 초안으로 되돌린 뒤 발행한다 — board 가 같은 규칙이다.\n *\n * ## 번호는 판본에서 센다\n *\n * 도형의 현재 번호가 아니라 **판본의 최대 번호 + 1** 이다. 되돌리기로 옛 판이 현재가 되어도\n * 다음 발행이 이미 쓴 번호를 다시 쓰지 않는다.\n *\n * ## 게이트를 통과해야 한다\n *\n * 크기를 바꿨을 때 조각이 갈라지는 도형은 발행되지 않는다(`figure-gate.ts`). 소비처는 형상을\n * 늘려 쓰므로 — 그것이 이 형식의 값이다 — 늘려도 견디는지가 약속의 일부다. 화면은 같은 판정을\n * `inspectFigure` 로 미리 물어 이유를 보여 준다.\n */\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Figure, { description: 'Releases a figure — raises its version and keeps the released state as history.' })\n async releaseFigure(\n @Arg('id') id: string,\n @Arg('comment', { nullable: true }) comment: string,\n @Ctx() context: ResolverContext\n ): Promise<Figure> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n const historyRepository = tx.getRepository(FigureHistory)\n\n const figure = await repository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n if (figure.state === 'released') {\n throw new Error(`Figure '${figure.type}' 은 이미 발행되어 있다. 고쳐서 다시 내려면 초안으로 되돌린 뒤 발행한다`)\n }\n\n /*\n ── 게이트는 여기 있어야 한다 ────────────────────────────────────────────\n 화면도 같은 판정을 미리 물어(`inspectFigure`) 이유를 보여 주지만, **막는 자리는 이곳뿐이다.**\n 물어본 뒤 정본이 바뀌었을 수 있고, 화면을 거치지 않는 부름도 있다.\n\n 막는 이유는 사유와 함께 낸다. 「발행할 수 없습니다」로 뭉치면 무엇을 고쳐야 하는지 모른다.\n */\n /*\n 직전 발행판을 먼저 꺼낸다. 판 번호를 세는 데도 쓰고, **약속을 깨는 발행인가**를 견주는 데도\n 쓴다(ADR-0063 결정 3) — 도면은 type 만 적고 늘 최신 발행판을 그리므로, 다시 발행하는 것은\n 그 type 을 놓아 둔 모든 도면에게 같은 약속을 다시 하는 일이다.\n */\n const released = await historyRepository\n .createQueryBuilder('history')\n .where('history.originalId = :id', { id: figure.id })\n .orderBy('history.version', 'DESC')\n .limit(1)\n .getOne()\n\n const inspection = inspectAnySource(figure.source, released?.source, context.t)\n if (inspection.blocked) {\n const reasons = inspection.findings\n .filter(finding => finding.blocking)\n .map(finding => (finding.at ? `${finding.message} (${finding.at})` : finding.message))\n\n throw new Error(`Figure '${figure.type}' 은 아직 발행할 수 없다 — ${reasons.join(' · ')}`)\n }\n\n const nextVersion = released?.version ? Number(released.version) + 1 : 1\n\n return await repository.save({\n /*\n `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.\n\n 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은\n 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은\n 자리에서 domain 을 함께 넣는다.\n */\n domain,\n ...figure,\n version: nextVersion,\n state: 'released',\n updater: user,\n /* 판본 구독자가 이것을 판본의 comment 로 옮긴다. Figure 의 칸이 아니다. */\n __releaseComment: comment ?? null\n } as any)\n }\n\n /**\n * 옛 판으로 되돌린다.\n *\n * ## 무엇이 돌아오나\n *\n * 그 판의 **정본과 속성 정의, 그리고 그림**이다. 이름·설명·분류는 그대로 둔다 — 그것들은 언제든\n * 바꿔도 안전한 카탈로그의 말이고, 되돌리기가 개명까지 되돌리면 사람이 시키지 않은 일을 한다.\n *\n * ## 되돌려도 발행은 아니다\n *\n * 초안으로 돌아온다. 다시 내보내려면 발행을 한 번 더 하고, 그때 판 번호는 **이미 쓴 번호 다음**을\n * 받는다 — 3판을 되살렸다고 다시 3판이 되지 않는다. board 도 같다.\n *\n * ## 비용은 다시 잰다\n *\n * 판본이 든 점수·삼각형은 **그때의 형식**으로 잰 값이다. 지금 이 도형이 그 내용이 되었으므로\n * 오늘 기준으로 다시 계산한다. 옛 값은 판본에 그대로 남아 있다.\n */\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Reverts a figure to one of its released versions. It comes back as a draft.' })\n async revertFigureVersion(\n @Arg('id') id: string,\n @Arg('version') version: number,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n const historyRepository = tx.getRepository(FigureHistory)\n\n const figure = await repository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n const history = await historyRepository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, originalId: id, version }\n })\n if (!history) {\n throw new Error(`Figure '${figure.type}' 에 ${version} 판이 없다`)\n }\n\n /* 형식 검사도 다시 받는다 — 옛 판이 오늘의 형식을 어길 수 있고, 그것을 조용히 들이지 않는다. */\n const { source, derived, violations } = parseAnySource(history.source)\n\n const saved = await repository.save({\n /*\n `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.\n\n 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은\n 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은\n 자리에서 domain 을 함께 넣는다.\n */\n domain,\n ...figure,\n source,\n ...derived,\n properties: history.properties,\n thumbnail: history.thumbnail,\n thumbnailUpdatedAt: history.thumbnail === figure.thumbnail ? figure.thumbnailUpdatedAt : new Date(),\n state: 'draft',\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Boolean, { description: 'Soft-deletes a figure.' })\n async deleteFigure(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<boolean> {\n const { domain, tx } = context.state\n\n // 소프트 삭제다 — 이미 배치된 도면이 이 타입을 참조할 수 있으므로 행을 지우지\n // 않는다. 되살릴 길을 남긴다.\n await tx.getRepository(Figure).softDelete({ domain: { id: domain.id }, id })\n\n return true\n }\n\n /**\n * 저작 보조에게 후보를 시킨다.\n *\n * **저장하지 않는다.** 후보를 돌려줄 뿐이고, 정본이 되는 것은 저작자가 보고 받은\n * 뒤다. AI 가 정본에 직접 쓰면 저작자가 무엇이 자기 것이고 무엇이 기계 것인지\n * 모르게 된다.\n *\n * 형식을 어긴 후보는 여기까지 오지 않는다 — `proposeFigure` 가 사유를 모델에\n * 돌려주고 다시 시킨다. 끝내 못 만들면 **사유와 함께 던진다.** 반쯤 만든 것을\n * 돌려주지 않는다.\n */\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureProposal, {\n description: 'Asks the authoring assistant for a figure. Returns a candidate — nothing is saved.'\n })\n async proposeFigure(@Arg('request') request: ProposeRequest): Promise<FigureProposal> {\n // 그림은 메모리로 받는다. 참고용이라 저장하지 않는다 — 남기면 지울 사람이 없다.\n let image\n if (request.image) {\n const file = await request.image\n const chunks: Buffer[] = []\n for await (const chunk of file.createReadStream()) {\n chunks.push(chunk as Buffer)\n }\n image = { data: Buffer.concat(chunks), mediaType: file.mimetype as never }\n }\n\n try {\n const result = await proposeFigure({\n prompt: request.prompt,\n base: request.base ? JSON.parse(request.base) : undefined,\n type: request.type,\n palette: request.palette,\n refine: request.refine,\n feedback: request.feedback,\n image\n })\n\n return {\n source: JSON.stringify(result.source),\n score: Math.round(result.score.score),\n grade: result.score.grade,\n triangles: result.cost.triangles,\n groups: result.cost.groups,\n quality: {\n ...result.quality,\n visualRegions: result.quality.visual.regions,\n visualCoverage: result.quality.visual.coverage,\n visualReadability: result.quality.visual.readability\n },\n violations: result.violations,\n attempts: result.attempts\n }\n } catch (e) {\n if (e instanceof ProposeFailure) {\n // 사유를 삼키지 않는다. 저작자가 무엇이 막혔는지 알아야 말을 고쳐 다시 시킨다.\n throw new Error([e.message, ...e.reasons].join('\\n'))\n }\n throw e\n }\n }\n\n}\n"]}
@@ -5,11 +5,10 @@ const tslib_1 = require("tslib");
5
5
  const typeorm_1 = require("typeorm");
6
6
  const type_graphql_1 = require("type-graphql");
7
7
  const graphql_scalars_1 = require("graphql-scalars");
8
- const figure_model_1 = require("@hatiolab/figure-model");
9
8
  const shell_1 = require("@things-factory/shell");
10
9
  const figure_js_1 = require("./figure.js");
11
10
  const figure_history_js_1 = require("./figure-history.js");
12
- const figure_gate_js_1 = require("./figure-gate.js");
11
+ const figure_format_js_1 = require("./figure-format.js");
13
12
  const figure_type_js_1 = require("./figure-type.js");
14
13
  let FigureQuery = class FigureQuery {
15
14
  async figure(id, context) {
@@ -100,7 +99,7 @@ let FigureQuery = class FigureQuery {
100
99
  .orderBy('history.version', 'DESC')
101
100
  .limit(1)
102
101
  .getOne();
103
- return (0, figure_gate_js_1.inspectSource)(figure.source, released?.source);
102
+ return (0, figure_format_js_1.inspectAnySource)(figure.source, released?.source, context.t);
104
103
  }
105
104
  async figureTypeNames(context) {
106
105
  const { domain } = context.state;
@@ -154,8 +153,15 @@ let FigureQuery = class FigureQuery {
154
153
  }
155
154
  const { figure, source: sourceToCompile, version } = found;
156
155
  try {
157
- const parsed = typeof sourceToCompile === 'string' ? JSON.parse(sourceToCompile) : sourceToCompile;
158
- return (0, figure_model_1.compile)(parsed);
156
+ /*
157
+ A V2 figure hands over its compiled blueprint, as it always did. A V3 asset hands over the asset
158
+ itself under a `format` tag, because the thing that draws it — `registerFigureV3` — takes the asset
159
+ and compiles it with the kernel. A V2 blueprint carries no `format`, so a consumer that has not been
160
+ taught about V3 keeps working and a V3 payload is recognised rather than guessed at (ADR-0087).
161
+ */
162
+ const text = typeof sourceToCompile === 'string' ? sourceToCompile : JSON.stringify(sourceToCompile);
163
+ const payload = (0, figure_format_js_1.consumablePayloadOf)(text);
164
+ return payload.format === 'v3' ? { format: 'v3', type, asset: payload.asset } : payload.blueprint;
159
165
  }
160
166
  catch (err) {
161
167
  console.error(`[figureBlueprint] 타입 '${type}' (figure id: ${figure.id}) 청사진 컴파일 실패:`, err);