@things-factory/figure-service 10.1.278 → 10.1.279
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +23 -8
- package/coverage/clover.xml +0 -6
- package/coverage/coverage-final.json +0 -1
- package/coverage/lcov-report/base.css +0 -224
- package/coverage/lcov-report/block-navigation.js +0 -87
- package/coverage/lcov-report/favicon.png +0 -0
- package/coverage/lcov-report/index.html +0 -101
- package/coverage/lcov-report/prettify.css +0 -1
- package/coverage/lcov-report/prettify.js +0 -2
- package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/coverage/lcov-report/sorter.js +0 -210
- package/coverage/lcov.info +0 -0
- package/dist-server/index.js.map +0 -1
- package/dist-server/migrations/index.js.map +0 -1
- package/dist-server/routers/figure-mesh-router.js.map +0 -1
- package/dist-server/routers/figure-package-router.js.map +0 -1
- package/dist-server/routers/figure-thumbnail-router.js.map +0 -1
- package/dist-server/routes.js.map +0 -1
- package/dist-server/service/figure/event-subscriber.js.map +0 -1
- package/dist-server/service/figure/figure-ai-scenarios-run.js.map +0 -1
- package/dist-server/service/figure/figure-ai-scenarios.js.map +0 -1
- package/dist-server/service/figure/figure-categories.js.map +0 -1
- package/dist-server/service/figure/figure-context.js.map +0 -1
- package/dist-server/service/figure/figure-format.js.map +0 -1
- package/dist-server/service/figure/figure-glb.js.map +0 -1
- package/dist-server/service/figure/figure-history.js.map +0 -1
- package/dist-server/service/figure/figure-llm-provider.js.map +0 -1
- package/dist-server/service/figure/figure-mesh-store.js.map +0 -1
- package/dist-server/service/figure/figure-mutation.js.map +0 -1
- package/dist-server/service/figure/figure-namespace-entity.js.map +0 -1
- package/dist-server/service/figure/figure-namespace-resolver.js.map +0 -1
- package/dist-server/service/figure/figure-namespace.js.map +0 -1
- package/dist-server/service/figure/figure-package-export.js.map +0 -1
- package/dist-server/service/figure/figure-proposal-record.js.map +0 -1
- package/dist-server/service/figure/figure-proposal.js.map +0 -1
- package/dist-server/service/figure/figure-propose-steps.js.map +0 -1
- package/dist-server/service/figure/figure-propose-type.js.map +0 -1
- package/dist-server/service/figure/figure-public.js.map +0 -1
- package/dist-server/service/figure/figure-query.js.map +0 -1
- package/dist-server/service/figure/figure-rename.js.map +0 -1
- package/dist-server/service/figure/figure-replaced-draft.js.map +0 -1
- package/dist-server/service/figure/figure-revert.js.map +0 -1
- package/dist-server/service/figure/figure-subject.js.map +0 -1
- package/dist-server/service/figure/figure-thumbnail-reader.js.map +0 -1
- package/dist-server/service/figure/figure-thumbnail-store.js.map +0 -1
- package/dist-server/service/figure/figure-thumbnail-upgrade.js.map +0 -1
- package/dist-server/service/figure/figure-tools.js.map +0 -1
- package/dist-server/service/figure/figure-type.js.map +0 -1
- package/dist-server/service/figure/figure-write.js.map +0 -1
- package/dist-server/service/figure/figure.js.map +0 -1
- package/dist-server/service/figure/index.js.map +0 -1
- package/dist-server/service/figure-recipe/figure-recipe-resolver.js.map +0 -1
- package/dist-server/service/figure-recipe/figure-recipe-templates.js.map +0 -1
- package/dist-server/service/figure-recipe/figure-recipe-type.js.map +0 -1
- package/dist-server/service/figure-recipe/index.js.map +0 -1
- package/dist-server/service/index.js.map +0 -1
- package/dist-server/tsconfig.tsbuildinfo +0 -1
- package/logs/.08636eb59927f12972f6774f5947c8507b3564c2-audit.json +0 -15
- package/logs/application-2026-09-14-23.log +0 -0
- package/logs/figure-ai-scenarios/2026-11-03T09-31-35-151Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -1167
- package/logs/figure-ai-scenarios/2026-11-03T09-39-05-265Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -904
- package/logs/figure-ai-scenarios/2026-11-03T09-41-49-107Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -1629
- package/logs/figure-ai-scenarios/2026-11-03T09-58-26-681Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -4412
- package/logs/figure-ai-scenarios/2026-11-03T10-16-46-212Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -4513
- package/logs/figure-ai-scenarios/2026-11-03T10-21-07-872Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -4202
- package/logs/figure-ai-scenarios/2026-11-03T10-25-21-721Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -1665
- package/logs/figure-ai-scenarios/2026-11-09T01-28-51-664Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -4484
- package/scripts/build-templates.mts +0 -64
- package/scripts/figure-ai-scenarios-agent.cjs +0 -98
- package/scripts/rename-figures-to-full-names.mjs +0 -211
- package/scripts/templates.test.mts +0 -112
- package/server/index.ts +0 -46
- package/server/migrations/index.ts +0 -9
- package/server/routers/figure-mesh-router.ts +0 -63
- package/server/routers/figure-package-router.ts +0 -53
- package/server/routers/figure-thumbnail-router.ts +0 -159
- package/server/routes.ts +0 -30
- package/server/service/figure/catalog-db.test.ts +0 -162
- package/server/service/figure/event-subscriber.ts +0 -66
- package/server/service/figure/figure-ai-scenarios-run.ts +0 -127
- package/server/service/figure/figure-ai-scenarios.live.test.ts +0 -59
- package/server/service/figure/figure-ai-scenarios.test.ts +0 -109
- package/server/service/figure/figure-ai-scenarios.ts +0 -798
- package/server/service/figure/figure-blueprint-query.test.ts +0 -536
- package/server/service/figure/figure-catalog-seen-db.test.ts +0 -153
- package/server/service/figure/figure-categories.ts +0 -50
- package/server/service/figure/figure-category-db.test.ts +0 -127
- package/server/service/figure/figure-context.test.ts +0 -402
- package/server/service/figure/figure-context.ts +0 -510
- package/server/service/figure/figure-deprecation-db.test.ts +0 -218
- package/server/service/figure/figure-format.test.ts +0 -423
- package/server/service/figure/figure-format.ts +0 -783
- package/server/service/figure/figure-glb.test.ts +0 -112
- package/server/service/figure/figure-glb.ts +0 -251
- package/server/service/figure/figure-history.ts +0 -192
- package/server/service/figure/figure-inspect-db.test.ts +0 -131
- package/server/service/figure/figure-llm-provider.ts +0 -20
- package/server/service/figure/figure-llm-smoke.test.ts +0 -95
- package/server/service/figure/figure-mesh-db.test.ts +0 -246
- package/server/service/figure/figure-mesh-store.ts +0 -91
- package/server/service/figure/figure-mutation.ts +0 -656
- package/server/service/figure/figure-namespace-db.test.ts +0 -315
- package/server/service/figure/figure-namespace-entity.ts +0 -67
- package/server/service/figure/figure-namespace-resolver.ts +0 -54
- package/server/service/figure/figure-namespace.ts +0 -156
- package/server/service/figure/figure-package-export.ts +0 -136
- package/server/service/figure/figure-proposal-db.test.ts +0 -117
- package/server/service/figure/figure-proposal-record.ts +0 -38
- package/server/service/figure/figure-proposal.ts +0 -41
- package/server/service/figure/figure-propose-clips.test.ts +0 -69
- package/server/service/figure/figure-propose-steps.test.ts +0 -324
- package/server/service/figure/figure-propose-steps.ts +0 -354
- package/server/service/figure/figure-propose-type.ts +0 -46
- package/server/service/figure/figure-public-db.test.ts +0 -288
- package/server/service/figure/figure-public.ts +0 -60
- package/server/service/figure/figure-query.ts +0 -511
- package/server/service/figure/figure-release-check.test.ts +0 -63
- package/server/service/figure/figure-release-record-db.test.ts +0 -153
- package/server/service/figure/figure-release-size-db.test.ts +0 -156
- package/server/service/figure/figure-rename-db.test.ts +0 -237
- package/server/service/figure/figure-rename.test.ts +0 -117
- package/server/service/figure/figure-rename.ts +0 -143
- package/server/service/figure/figure-replaced-draft.ts +0 -99
- package/server/service/figure/figure-revert-db.test.ts +0 -163
- package/server/service/figure/figure-revert-race.pg.test.ts +0 -168
- package/server/service/figure/figure-revert.ts +0 -186
- package/server/service/figure/figure-subject.test.ts +0 -41
- package/server/service/figure/figure-subject.ts +0 -21
- package/server/service/figure/figure-thumbnail-db.test.ts +0 -279
- package/server/service/figure/figure-thumbnail-reader.ts +0 -20
- package/server/service/figure/figure-thumbnail-store.ts +0 -111
- package/server/service/figure/figure-thumbnail-upgrade.pg.test.ts +0 -93
- package/server/service/figure/figure-thumbnail-upgrade.ts +0 -70
- package/server/service/figure/figure-tool-doors.test.ts +0 -127
- package/server/service/figure/figure-tools-door-db.test.ts +0 -227
- package/server/service/figure/figure-tools.test.ts +0 -817
- package/server/service/figure/figure-tools.ts +0 -611
- package/server/service/figure/figure-type.ts +0 -241
- package/server/service/figure/figure-write.test.ts +0 -15
- package/server/service/figure/figure-write.ts +0 -131
- package/server/service/figure/figure.ts +0 -241
- package/server/service/figure/index.ts +0 -13
- package/server/service/figure-recipe/figure-recipe-resolver.ts +0 -38
- package/server/service/figure-recipe/figure-recipe-templates.test.ts +0 -47
- package/server/service/figure-recipe/figure-recipe-templates.ts +0 -70
- package/server/service/figure-recipe/figure-recipe-type.ts +0 -31
- package/server/service/figure-recipe/index.ts +0 -3
- package/server/service/index.ts +0 -34
- package/tsconfig.json +0 -14
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* Builds the recipe templates from their models (ADR-0095 amended: model first, verified, then the recipe).
|
|
3
|
-
*
|
|
4
|
-
* node scripts/build-templates.mts [name …]
|
|
5
|
-
*
|
|
6
|
-
* For each recipes/<name>/ with build.mts and spec.json: builds a model for every combination of the template's
|
|
7
|
-
* choices (models/<choices>.json, and models/default.json at its defaults) -- figures the modeller opens as they are --
|
|
8
|
-
* then merges them into recipe.json (figure-model `buildFigureRecipe`). The tests check the models and that recipe.json is
|
|
9
|
-
* what they build; `figure-ui/scripts/template-thumbnails.mjs` draws thumbnail.png from models/default.json.
|
|
10
|
-
*/
|
|
11
|
-
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
12
|
-
import { join, resolve } from 'node:path'
|
|
13
|
-
import { pathToFileURL } from 'node:url'
|
|
14
|
-
|
|
15
|
-
import { buildFigureRecipe, serializeFigureAsset } from '@hatiolab/figure-model'
|
|
16
|
-
import type { FigureRecipeSpec } from '@hatiolab/figure-model'
|
|
17
|
-
|
|
18
|
-
export const RECIPES = resolve(import.meta.dirname, '..', 'recipes')
|
|
19
|
-
|
|
20
|
-
type Values = Record<string, number | string | boolean>
|
|
21
|
-
|
|
22
|
-
/** Every combination of a spec's choices and flags, the defaults first. */
|
|
23
|
-
export function combinationsOf(spec: FigureRecipeSpec): Values[] {
|
|
24
|
-
let combos: Values[] = [{}]
|
|
25
|
-
for (const p of spec.params.filter(p => p.kind === 'choice' || p.kind === 'flag')) {
|
|
26
|
-
const values = p.kind === 'flag' ? [true, false] : [...(p.options ?? [])]
|
|
27
|
-
combos = combos.flatMap(c => values.map(v => ({ ...c, [p.name]: v })))
|
|
28
|
-
}
|
|
29
|
-
const defaults = Object.fromEntries(spec.params.map(p => [p.name, p.default]))
|
|
30
|
-
const isDefault = (c: Values) => Object.entries(c).every(([k, v]) => defaults[k] === v)
|
|
31
|
-
return [...combos.filter(isDefault), ...combos.filter(c => !isDefault(c))]
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export const modelFileOf = (values: Values) => (Object.keys(values).length ? Object.entries(values).map(([k, v]) => `${k}=${v}`).join(',') : 'default') + '.json'
|
|
35
|
-
|
|
36
|
-
/** One template built: its models and its recipe, as the files hold them. */
|
|
37
|
-
export async function buildTemplate(name: string) {
|
|
38
|
-
const dir = join(RECIPES, name)
|
|
39
|
-
const spec = JSON.parse(readFileSync(join(dir, 'spec.json'), 'utf-8')) as FigureRecipeSpec
|
|
40
|
-
const build = (await import(pathToFileURL(join(dir, 'build.mts')).href)).default as (values: Values) => unknown
|
|
41
|
-
const combos = combinationsOf(spec)
|
|
42
|
-
const models = combos.map(values => ({ values, asset: build(values) as never }))
|
|
43
|
-
const recipe = buildFigureRecipe(spec, models)
|
|
44
|
-
return { spec, models, recipe, combos }
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
async function main() {
|
|
48
|
-
const only = process.argv.slice(2)
|
|
49
|
-
for (const name of readdirSync(RECIPES).filter(n => !n.startsWith('_') && existsSync(join(RECIPES, n, 'build.mts'))).filter(n => !only.length || only.includes(n)).sort()) {
|
|
50
|
-
const { models, recipe } = await buildTemplate(name)
|
|
51
|
-
const out = join(RECIPES, name, 'models')
|
|
52
|
-
rmSync(out, { recursive: true, force: true })
|
|
53
|
-
mkdirSync(out)
|
|
54
|
-
models.forEach(({ values, asset }, i) => {
|
|
55
|
-
const text = serializeFigureAsset(asset)
|
|
56
|
-
writeFileSync(join(out, modelFileOf(values)), text)
|
|
57
|
-
if (i === 0) writeFileSync(join(out, 'default.json'), text)
|
|
58
|
-
})
|
|
59
|
-
writeFileSync(join(RECIPES, name, 'recipe.json'), JSON.stringify(recipe, null, 2) + '\n')
|
|
60
|
-
console.log(`${name}: ${models.length} model(s), ${recipe.steps.length} steps`)
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) await main()
|
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* AI 모델링 시나리오를 도메인의 AI 에이전트로 돌린다 (2026-11-03, 사용자 「에이전트 키로」).
|
|
4
|
-
*
|
|
5
|
-
* 앱 폴더에서 실행한다. 그 앱의 설정(데이터 암호 키·DB)을 읽고, 그 DB 의 도메인에 설정된 AI 에이전트를 사람이 쓰는 것과
|
|
6
|
-
* 같은 문(`aiClientFor`)으로 받아, figure-ai-scenarios.ts 의 요청마다 피규어를 만들거나 고치게 한다. 키는 셸에도 저장소에도
|
|
7
|
-
* 두지 않고, 사용량은 그 도메인의 AI 사용 기록에 남는다.
|
|
8
|
-
*
|
|
9
|
-
* cd <앱 폴더, 예 operato-application/packages/operato-office>
|
|
10
|
-
* NODE_ENV=development node <things-factory>/packages/figure-service/scripts/figure-ai-scenarios-agent.cjs --domain hatiolab
|
|
11
|
-
*
|
|
12
|
-
* 선택: --agent <에이전트 id> (없으면 도메인 기본) · --scenarios pipeline-run,hopper · --repeat 3 · --reports <폴더>
|
|
13
|
-
*
|
|
14
|
-
* DB 는 그대로 쓴다: 표를 만들거나 고치지 않는다(synchronize·migration 을 끈다). sqlite 가 아닌 DB 는 --allow-database 를
|
|
15
|
-
* 줄 때만 붙는다 -- 개발 설정이 운영 DB 로 가는 앱(:3300 의 figure)이 있기 때문이다. 운영 모드(NODE_ENV=production)는 받지
|
|
16
|
-
* 않는다. 먼저 figure-service 를 빌드한다: yarn workspace @things-factory/figure-service build:server
|
|
17
|
-
*/
|
|
18
|
-
'use strict'
|
|
19
|
-
|
|
20
|
-
const path = require('path')
|
|
21
|
-
const { createRequire } = require('module')
|
|
22
|
-
|
|
23
|
-
/* things-factory's own packages, whatever the app folder has installed: the entities and the door are the ones built here. */
|
|
24
|
-
const here = createRequire(path.join(__dirname, '..', 'package.json'))
|
|
25
|
-
|
|
26
|
-
function argsOf(argv) {
|
|
27
|
-
const out = { scenarios: [], repeat: 1 }
|
|
28
|
-
for (let i = 0; i < argv.length; i++) {
|
|
29
|
-
const [key, next] = [argv[i], argv[i + 1]]
|
|
30
|
-
if (key === '--domain') (out.domain = next), i++
|
|
31
|
-
else if (key === '--agent') (out.agent = next), i++
|
|
32
|
-
else if (key === '--scenarios') (out.scenarios = next.split(',').map(s => s.trim()).filter(Boolean)), i++
|
|
33
|
-
else if (key === '--repeat') (out.repeat = Math.max(1, Number(next) || 1)), i++
|
|
34
|
-
else if (key === '--reports') (out.reports = path.resolve(next)), i++
|
|
35
|
-
else if (key === '--allow-database') out.allowDatabase = true
|
|
36
|
-
else throw new Error(`unknown argument: ${key}`)
|
|
37
|
-
}
|
|
38
|
-
if (!out.domain) throw new Error('--domain <subdomain> is required: the domain whose AI agent answers')
|
|
39
|
-
return out
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
async function main() {
|
|
43
|
-
const args = argsOf(process.argv.slice(2))
|
|
44
|
-
if (process.env.NODE_ENV === 'production') throw new Error('not in production mode: run it against a development database')
|
|
45
|
-
|
|
46
|
-
const { config } = here('@things-factory/env')
|
|
47
|
-
const { DataSource } = here('typeorm')
|
|
48
|
-
const shell = here('@things-factory/shell')
|
|
49
|
-
const ai = here('@things-factory/ai-client-base')
|
|
50
|
-
const entities = [...shell.entities, ...here('@things-factory/auth-base').entities, ...here('@things-factory/setting-base').entities, ...ai.entities]
|
|
51
|
-
|
|
52
|
-
/* The app's database as its configuration names it; the package default is sqlite db.sqlite in the app folder. */
|
|
53
|
-
const configured = config.get('ormconfig', {}) || {}
|
|
54
|
-
const database = { type: 'sqlite', database: 'db.sqlite', ...configured }
|
|
55
|
-
if (database.type !== 'sqlite' && !args.allowDatabase)
|
|
56
|
-
throw new Error(`the app's database is ${database.type}${database.host ? ` at ${database.host}:${database.port}` : ''}: pass --allow-database to use it`)
|
|
57
|
-
const source = new DataSource({
|
|
58
|
-
...database,
|
|
59
|
-
...(database.type === 'sqlite' ? { database: path.resolve(database.database) } : {}),
|
|
60
|
-
entities,
|
|
61
|
-
migrations: [],
|
|
62
|
-
subscribers: [],
|
|
63
|
-
synchronize: false,
|
|
64
|
-
migrationsRun: false,
|
|
65
|
-
logging: false,
|
|
66
|
-
namingStrategy: new (here('@things-factory/shell/dist-server/initializers/naming-strategy.js').NamingStrategy)()
|
|
67
|
-
})
|
|
68
|
-
await source.initialize()
|
|
69
|
-
shell.addDataSource('default', source)
|
|
70
|
-
try {
|
|
71
|
-
const domain = await source.getRepository(shell.Domain).findOne({ where: { subdomain: args.domain } })
|
|
72
|
-
if (!domain) throw new Error(`no domain ${args.domain} in ${database.database ?? database.host}`)
|
|
73
|
-
const client = await ai.aiClientFor({ domain, agentId: args.agent ?? null })
|
|
74
|
-
|
|
75
|
-
const run = here('./dist-server/service/figure/figure-ai-scenarios-run.js')
|
|
76
|
-
const scenarios = run.scenariosNamed(args.scenarios)
|
|
77
|
-
const runs = []
|
|
78
|
-
for (const scenario of scenarios)
|
|
79
|
-
for (let round = 1; round <= args.repeat; round++) {
|
|
80
|
-
const one = await run.runFigureAIScenario(client, scenario, round)
|
|
81
|
-
runs.push(one)
|
|
82
|
-
console.log(`${one.passed ? '✔' : '✖'} ${scenario.id}${args.repeat > 1 ? ` #${round}` : ''} (${one.seconds.toFixed(1)}s)${one.passed ? '' : ` — ${one.misses.slice(0, 2).join('; ')}`}`)
|
|
83
|
-
}
|
|
84
|
-
const folder = args.reports ?? path.join(__dirname, '..', 'logs', 'figure-ai-scenarios')
|
|
85
|
-
const { lines, report } = run.writeFigureAIScenarioReport(folder, { by: `agent:${args.domain}/${client.agent.name}`, model: `${client.agent.provider}-${client.agent.model}` }, scenarios, runs, args.repeat)
|
|
86
|
-
console.log(lines.join('\n'))
|
|
87
|
-
process.exitCode = report.passed === report.total ? 0 : 1
|
|
88
|
-
} finally {
|
|
89
|
-
/* The last calls' usage rows are written after their answers: closed before them, they would be lost. */
|
|
90
|
-
await ai.aiUsageRecorded()
|
|
91
|
-
await source.destroy()
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
main().catch(e => {
|
|
96
|
-
console.error(e instanceof Error ? e.message : String(e))
|
|
97
|
-
process.exit(2)
|
|
98
|
-
})
|
|
@@ -1,211 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/*
|
|
3
|
-
* One-off: moves a development database to full figure names (ADR-0114, design figure-library.md §11 · P4).
|
|
4
|
-
*
|
|
5
|
-
* type ROBOT_ARM → robot-arm figures · figure_histories · figures.superseded_by
|
|
6
|
-
* namespace → the given one figures · figure_histories (column added when missing)
|
|
7
|
-
* setting figure-namespace = the given one, for the domain that holds the figures
|
|
8
|
-
* board nodes ROBOT_ARM → {namespace}/robot-arm boards.model · board_histories.model
|
|
9
|
-
*
|
|
10
|
-
* Dry run by default: it prints the plan, the checks and the counts and changes nothing. `--apply` runs it in one
|
|
11
|
-
* transaction and refuses, changing nothing, when a check fails. Not a migration file -- it is run once by hand.
|
|
12
|
-
*
|
|
13
|
-
* node scripts/rename-figures-to-full-names.mjs --db <path/to/db.sqlite> --namespace system [--apply]
|
|
14
|
-
*/
|
|
15
|
-
import { createRequire } from 'node:module'
|
|
16
|
-
import { randomUUID } from 'node:crypto'
|
|
17
|
-
|
|
18
|
-
const require = createRequire(import.meta.url)
|
|
19
|
-
const Database = require('better-sqlite3')
|
|
20
|
-
const { isFigureNamespace, isFigureType } = await import(require.resolve('@hatiolab/figure-model'))
|
|
21
|
-
|
|
22
|
-
const args = process.argv.slice(2)
|
|
23
|
-
const option = name => {
|
|
24
|
-
const i = args.indexOf(`--${name}`)
|
|
25
|
-
return i >= 0 ? args[i + 1] : undefined
|
|
26
|
-
}
|
|
27
|
-
const dbPath = option('db')
|
|
28
|
-
const namespace = option('namespace')
|
|
29
|
-
const apply = args.includes('--apply')
|
|
30
|
-
|
|
31
|
-
if (!dbPath || !namespace) {
|
|
32
|
-
console.error('usage: --db <path> --namespace <namespace> [--apply]')
|
|
33
|
-
process.exit(2)
|
|
34
|
-
}
|
|
35
|
-
if (!isFigureNamespace(namespace)) {
|
|
36
|
-
console.error(`'${namespace}' is not a namespace (lower-case domain-name form, 63 characters at most)`)
|
|
37
|
-
process.exit(2)
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
const db = new Database(dbPath, { readonly: !apply, fileMustExist: true })
|
|
41
|
-
const hasTable = name => !!db.prepare(`select 1 from sqlite_master where type='table' and name=?`).get(name)
|
|
42
|
-
const hasColumn = (table, column) => !!db.prepare(`select 1 from pragma_table_info(?) where name=?`).get(table, column)
|
|
43
|
-
|
|
44
|
-
/** An old type in the shape boards used: capitals, digits and underscores. */
|
|
45
|
-
const OLD_TYPE = /^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$/
|
|
46
|
-
const kebab = type => type.toLowerCase().replace(/_+/g, '-')
|
|
47
|
-
|
|
48
|
-
/* ── what is there ─────────────────────────────────────────────────────────────────────────────────────────── */
|
|
49
|
-
|
|
50
|
-
function counts() {
|
|
51
|
-
const one = sql => db.prepare(sql).pluck().get()
|
|
52
|
-
const ns = (table) => (hasColumn(table, 'namespace') ? one(`select count(*) from ${table} where namespace is null`) : one(`select count(*) from ${table}`))
|
|
53
|
-
return {
|
|
54
|
-
figures: one('select count(*) from figures'),
|
|
55
|
-
figuresLive: one('select count(*) from figures where deleted_at is null'),
|
|
56
|
-
histories: one('select count(*) from figure_histories'),
|
|
57
|
-
figuresOldType: db.prepare('select type from figures').pluck().all().filter(t => OLD_TYPE.test(t)).length,
|
|
58
|
-
historiesOldType: db.prepare('select type from figure_histories').pluck().all().filter(t => t && OLD_TYPE.test(t)).length,
|
|
59
|
-
figuresWithoutNamespace: ns('figures'),
|
|
60
|
-
historiesWithoutNamespace: ns('figure_histories'),
|
|
61
|
-
namespaceSettings: one(`select count(*) from settings where name='figure-namespace'`),
|
|
62
|
-
boardNodesOldType: boardNodes().old,
|
|
63
|
-
boardNodesFullName: boardNodes().full
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** Board model nodes naming a figure type of this database, in the old shape or already full. */
|
|
68
|
-
function boardNodes(map = typeMap) {
|
|
69
|
-
let old = 0
|
|
70
|
-
let full = 0
|
|
71
|
-
for (const table of ['boards', 'board_histories']) {
|
|
72
|
-
if (!hasTable(table)) continue
|
|
73
|
-
for (const { model } of db.prepare(`select model from ${table}`).all()) {
|
|
74
|
-
walkTypes(model, type => {
|
|
75
|
-
if (map.has(type)) old++
|
|
76
|
-
else if (type.includes('/') && [...map.values()].some(t => type === `${namespace}/${t}`)) full++
|
|
77
|
-
})
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return { old, full }
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function walkTypes(text, visit) {
|
|
84
|
-
let model
|
|
85
|
-
try {
|
|
86
|
-
model = JSON.parse(text || '{}')
|
|
87
|
-
} catch {
|
|
88
|
-
return
|
|
89
|
-
}
|
|
90
|
-
const walk = node => {
|
|
91
|
-
for (const child of Array.isArray(node?.components) ? node.components : []) {
|
|
92
|
-
if (typeof child?.type === 'string') visit(child.type, child)
|
|
93
|
-
walk(child)
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
walk(model)
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/* ── the plan and its checks ───────────────────────────────────────────────────────────────────────────────── */
|
|
100
|
-
|
|
101
|
-
const domains = db.prepare('select distinct domain_id as id from figures').pluck().all()
|
|
102
|
-
const problems = []
|
|
103
|
-
if (domains.length !== 1) problems.push(`figures are in ${domains.length} domains; this script moves one domain`)
|
|
104
|
-
const domainId = domains[0]
|
|
105
|
-
|
|
106
|
-
const rows = db.prepare('select id, type, deleted_at as deletedAt from figures where domain_id = ?').all(domainId)
|
|
107
|
-
const historyTypes = db.prepare('select distinct type from figure_histories where domain_id = ? and type is not null').pluck().all(domainId)
|
|
108
|
-
const typeMap = new Map()
|
|
109
|
-
for (const type of new Set([...rows.map(r => r.type), ...historyTypes])) {
|
|
110
|
-
if (!OLD_TYPE.test(type)) continue
|
|
111
|
-
typeMap.set(type, kebab(type))
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/* Every new name must be a type, and two old names must never land on one new name among the live figures. */
|
|
115
|
-
for (const [from, to] of typeMap) if (!isFigureType(to)) problems.push(`${from} → ${to} is not a figure type`)
|
|
116
|
-
const liveByNew = new Map()
|
|
117
|
-
for (const row of rows.filter(r => !r.deletedAt)) {
|
|
118
|
-
const to = typeMap.get(row.type) ?? row.type
|
|
119
|
-
if (liveByNew.has(to)) problems.push(`${liveByNew.get(to)} and ${row.type} would both become ${to}`)
|
|
120
|
-
else liveByNew.set(to, row.type)
|
|
121
|
-
}
|
|
122
|
-
const deletedClashes = rows.filter(r => r.deletedAt && liveByNew.has(typeMap.get(r.type) ?? r.type) && liveByNew.get(typeMap.get(r.type) ?? r.type) !== r.type)
|
|
123
|
-
|
|
124
|
-
const setting = db.prepare(`select value from settings where name='figure-namespace' and domain_id = ?`).get(domainId)
|
|
125
|
-
if (setting && setting.value !== namespace) problems.push(`the domain setting figure-namespace is already ${setting.value}`)
|
|
126
|
-
if (hasColumn('figures', 'namespace')) {
|
|
127
|
-
const others = db.prepare('select distinct namespace from figures where domain_id = ? and namespace is not null and namespace != ?').pluck().all(domainId, namespace)
|
|
128
|
-
if (others.length) problems.push(`figures already carry another namespace: ${others.join(', ')}`)
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
const before = counts()
|
|
132
|
-
console.log(`database ${dbPath}`)
|
|
133
|
-
console.log(`domain ${db.prepare('select name from domains where id = ?').pluck().get(domainId) ?? domainId}`)
|
|
134
|
-
console.log(`namespace ${namespace}`)
|
|
135
|
-
console.log(`renames ${typeMap.size}`)
|
|
136
|
-
for (const [from, to] of [...typeMap].sort()) console.log(` ${from.padEnd(28)} → ${to}`)
|
|
137
|
-
if (deletedClashes.length) console.log(`note: deleted figures sharing a new name with a live one (kept, outside the unique index): ${deletedClashes.map(r => r.type).join(', ')}`)
|
|
138
|
-
console.log('before', before)
|
|
139
|
-
|
|
140
|
-
if (problems.length) {
|
|
141
|
-
console.error('\nrefused, nothing changed:')
|
|
142
|
-
for (const problem of problems) console.error(` - ${problem}`)
|
|
143
|
-
process.exit(1)
|
|
144
|
-
}
|
|
145
|
-
if (!apply) {
|
|
146
|
-
console.log('\ndry run: nothing changed. run again with --apply.')
|
|
147
|
-
process.exit(0)
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/* ── apply, in one transaction ─────────────────────────────────────────────────────────────────────────────── */
|
|
151
|
-
|
|
152
|
-
db.transaction(() => {
|
|
153
|
-
for (const table of ['figures', 'figure_histories']) {
|
|
154
|
-
if (!hasColumn(table, 'namespace')) db.exec(`alter table ${table} add column namespace varchar`)
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
const now = new Date().toISOString().replace('T', ' ').slice(0, 19)
|
|
158
|
-
if (!setting) {
|
|
159
|
-
db.prepare(`insert into settings (id, name, description, category, value, created_at, updated_at, domain_id) values (?, 'figure-namespace', 'namespace of the figures made here (ADR-0114)', 'figure', ?, ?, ?, ?)`)
|
|
160
|
-
.run(randomUUID(), namespace, now, now, domainId)
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
const renameFigure = db.prepare('update figures set type = ? where domain_id = ? and type = ?')
|
|
164
|
-
const renameHistory = db.prepare('update figure_histories set type = ? where domain_id = ? and type = ?')
|
|
165
|
-
const renameSuperseded = db.prepare('update figures set superseded_by = ? where domain_id = ? and superseded_by = ?')
|
|
166
|
-
for (const [from, to] of typeMap) {
|
|
167
|
-
renameFigure.run(to, domainId, from)
|
|
168
|
-
renameHistory.run(to, domainId, from)
|
|
169
|
-
renameSuperseded.run(to, domainId, from)
|
|
170
|
-
}
|
|
171
|
-
db.prepare('update figures set namespace = ? where domain_id = ? and namespace is null').run(namespace, domainId)
|
|
172
|
-
db.prepare('update figure_histories set namespace = ? where domain_id = ? and namespace is null').run(namespace, domainId)
|
|
173
|
-
|
|
174
|
-
for (const table of ['boards', 'board_histories']) {
|
|
175
|
-
if (!hasTable(table)) continue
|
|
176
|
-
const update = db.prepare(`update ${table} set model = ? where id = ?`)
|
|
177
|
-
for (const { id, model } of db.prepare(`select id, model from ${table} where domain_id = ?`).all(domainId)) {
|
|
178
|
-
let changed = false
|
|
179
|
-
let parsed
|
|
180
|
-
try {
|
|
181
|
-
parsed = JSON.parse(model || '{}')
|
|
182
|
-
} catch {
|
|
183
|
-
continue
|
|
184
|
-
}
|
|
185
|
-
const walk = node => {
|
|
186
|
-
for (const child of Array.isArray(node?.components) ? node.components : []) {
|
|
187
|
-
if (typeof child?.type === 'string' && typeMap.has(child.type)) {
|
|
188
|
-
child.type = `${namespace}/${typeMap.get(child.type)}`
|
|
189
|
-
changed = true
|
|
190
|
-
}
|
|
191
|
-
walk(child)
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
walk(parsed)
|
|
195
|
-
if (changed) update.run(JSON.stringify(parsed), id)
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
const after = counts()
|
|
200
|
-
const wrong = []
|
|
201
|
-
if (after.figures !== before.figures) wrong.push('figure count changed')
|
|
202
|
-
if (after.histories !== before.histories) wrong.push('history count changed')
|
|
203
|
-
if (after.figuresOldType || after.historiesOldType) wrong.push('old type names remain')
|
|
204
|
-
if (after.figuresWithoutNamespace || after.historiesWithoutNamespace) wrong.push('rows without a namespace remain')
|
|
205
|
-
if (after.namespaceSettings < 1) wrong.push('the namespace setting is missing')
|
|
206
|
-
if (after.boardNodesOldType) wrong.push('board nodes with old names remain')
|
|
207
|
-
console.log('after ', after)
|
|
208
|
-
if (wrong.length) throw new Error(`checks after the change failed, rolled back: ${wrong.join(', ')}`)
|
|
209
|
-
})()
|
|
210
|
-
|
|
211
|
-
console.log('\napplied.')
|
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* Every recipe template, verified (ADR-0095 amended: model first, verified, then the recipe).
|
|
3
|
-
*
|
|
4
|
-
* node --test scripts/templates.test.mts
|
|
5
|
-
*
|
|
6
|
-
* For each template: its files are what its models build; each model passes the release gate, holds at half and twice
|
|
7
|
-
* its host, and moves through every control's range; the recipe put into a new host shows exactly each model; and the
|
|
8
|
-
* words and the picture are there.
|
|
9
|
-
*/
|
|
10
|
-
import { test } from 'node:test'
|
|
11
|
-
import assert from 'node:assert/strict'
|
|
12
|
-
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
|
13
|
-
import { join } from 'node:path'
|
|
14
|
-
|
|
15
|
-
import { applyFigureRecipe, checkFigureRecipe, compileFigureAsset, compileFigureDocument, inspectFigureAsset, serializeFigureAsset } from '@hatiolab/figure-model'
|
|
16
|
-
import type { FigureAsset } from '@hatiolab/figure-model'
|
|
17
|
-
|
|
18
|
-
import { buildTemplate, modelFileOf, RECIPES } from './build-templates.mts'
|
|
19
|
-
import { host } from '../recipes/_lib/model.mts'
|
|
20
|
-
|
|
21
|
-
const names = readdirSync(RECIPES).filter(n => !n.startsWith('_') && existsSync(join(RECIPES, n, 'build.mts'))).sort()
|
|
22
|
-
|
|
23
|
-
/** The bodies of a figure, rounded: what a person sees, to compare two figures by. */
|
|
24
|
-
const bodies = (asset: FigureAsset, state: Record<string, number> = {}) =>
|
|
25
|
-
(compileFigureAsset(asset).evaluate(state).geometry as unknown as Array<{ id: string; visible?: boolean; pose: { t: number[] }; shape: { dimensions: Record<string, number> } }>)
|
|
26
|
-
.map(g => ({ id: g.id, shown: g.visible !== false, t: g.pose.t.map(v => Math.round(v)), d: Object.fromEntries(Object.entries(g.shape.dimensions).map(([k, v]) => [k, Math.round(v)])) }))
|
|
27
|
-
.sort((a, b) => a.id.localeCompare(b.id))
|
|
28
|
-
/** A model's parts named as a recipe names them, so the two can be laid side by side. */
|
|
29
|
-
const renamed = (list: ReturnType<typeof bodies>, id: string, parts: string[]) =>
|
|
30
|
-
list
|
|
31
|
-
.map(b => ({ ...b, id: parts.reduce((text, p) => text.replace(new RegExp(`(^|[^\\w-])${p.replace(/[-]/g, '\\-')}(?=[^\\w-]|$)`, 'g'), `$1${id}-${p}`), b.id) }))
|
|
32
|
-
.sort((a, b) => a.id.localeCompare(b.id))
|
|
33
|
-
const partsOf = (asset: FigureAsset) => asset.appearance.map(a => a.target).filter(t => t !== 'host')
|
|
34
|
-
/** How high the model's host stands off the floor: the new host stands the same. */
|
|
35
|
-
const hostGap = (asset: FigureAsset) => {
|
|
36
|
-
const gap = asset.joints?.find(j => j.body1.part === 'host')?.origin?.gap
|
|
37
|
-
return typeof gap === 'number' ? gap : 0
|
|
38
|
-
}
|
|
39
|
-
const hostSize = (asset: FigureAsset) => ({ x: asset.designInputs['host.size.x']!, y: asset.designInputs['host.size.y']!, z: asset.designInputs['host.size.z']! })
|
|
40
|
-
const withHost = (asset: FigureAsset, k: number) => ({ ...asset, designInputs: { ...asset.designInputs, ...Object.fromEntries(['x', 'y', 'z'].map(a => [`host.size.${a}`, asset.designInputs[`host.size.${a}`]! * k])) } })
|
|
41
|
-
|
|
42
|
-
for (const name of names) {
|
|
43
|
-
test(`${name}: the files are what the models build`, async () => {
|
|
44
|
-
const { models, recipe } = await buildTemplate(name)
|
|
45
|
-
assert.deepEqual(JSON.parse(readFileSync(join(RECIPES, name, 'recipe.json'), 'utf-8')), JSON.parse(JSON.stringify(recipe)), 'recipe.json is up to date -- run scripts/build-templates.mts')
|
|
46
|
-
for (const { values, asset } of models) assert.equal(readFileSync(join(RECIPES, name, 'models', modelFileOf(values)), 'utf-8'), serializeFigureAsset(asset), `models/${modelFileOf(values)} is up to date`)
|
|
47
|
-
})
|
|
48
|
-
|
|
49
|
-
test(`${name}: each model passes the gate, holds at half and twice its host, and moves through its controls`, async () => {
|
|
50
|
-
const { models } = await buildTemplate(name)
|
|
51
|
-
for (const { values, asset } of models) {
|
|
52
|
-
const at = JSON.stringify(values)
|
|
53
|
-
assert.deepEqual(inspectFigureAsset(asset).violations, [], `${at}: the release gate`)
|
|
54
|
-
for (const k of [0.5, 2]) assert.doesNotThrow(() => compileFigureAsset(withHost(asset, k)).evaluate(), `${at}: host × ${k}`)
|
|
55
|
-
for (const input of asset.document.model.inputs.filter(i => i.role === 'state'))
|
|
56
|
-
for (const v of [input.min!, input.max!]) assert.doesNotThrow(() => compileFigureAsset(asset).evaluate({ [input.id]: v }), `${at}: ${input.id} at ${v}`)
|
|
57
|
-
}
|
|
58
|
-
})
|
|
59
|
-
|
|
60
|
-
test(`${name}: the recipe put into a new host shows each model, shut and at every control's end`, async () => {
|
|
61
|
-
const { models, recipe } = await buildTemplate(name)
|
|
62
|
-
assert.doesNotThrow(() => checkFigureRecipe(structuredClone(recipe)))
|
|
63
|
-
for (const { values, asset } of models) {
|
|
64
|
-
const put = applyFigureRecipe(host(hostSize(asset), 'Template check', hostGap(asset)), recipe, { target: 'host', values })
|
|
65
|
-
assert.deepEqual(bodies(put.asset), renamed(bodies(asset), put.id, partsOf(asset)), `${JSON.stringify(values)}: as the model`)
|
|
66
|
-
for (const input of asset.document.model.inputs.filter(i => i.role === 'state'))
|
|
67
|
-
assert.deepEqual(bodies(put.asset, { [`${put.id}-${input.id}`]: input.max! }), renamed(bodies(asset, { [input.id]: input.max! }), put.id, partsOf(asset)), `${JSON.stringify(values)}: ${input.id} at its end`)
|
|
68
|
-
}
|
|
69
|
-
})
|
|
70
|
-
|
|
71
|
-
test(`${name}: an instance's evaluator gives what a whole evaluation gives, through its controls and its host's sizes`, async () => {
|
|
72
|
-
/* The per-instance evaluator runs again only what changed (2026-09-26); it must answer as a whole evaluation does. */
|
|
73
|
-
const { models } = await buildTemplate(name)
|
|
74
|
-
for (const { values, asset } of models) {
|
|
75
|
-
const plan = compileFigureDocument(asset.document)
|
|
76
|
-
const own = plan.evaluator()
|
|
77
|
-
const base = { ...asset.designInputs, ...asset.stateDefaults }
|
|
78
|
-
const states = asset.document.model.inputs.filter(i => i.role === 'state')
|
|
79
|
-
const steps: Array<Record<string, number>> = [base]
|
|
80
|
-
for (const k of [0.5, 2, 1]) steps.push({ ...withHost(asset, k).designInputs, ...asset.stateDefaults })
|
|
81
|
-
for (const input of states) for (const v of [input.min!, input.max!, (input.min! + input.max!) / 2]) steps.push({ ...base, [input.id]: v })
|
|
82
|
-
for (const inputs of steps) {
|
|
83
|
-
let whole: unknown, refused = false
|
|
84
|
-
try {
|
|
85
|
-
whole = plan.evaluate(inputs)
|
|
86
|
-
} catch {
|
|
87
|
-
refused = true
|
|
88
|
-
}
|
|
89
|
-
if (refused) assert.throws(() => own.evaluate(inputs), `${JSON.stringify(values)}: refused as the whole is`)
|
|
90
|
-
else assert.equal(JSON.stringify(own.evaluate(inputs)), JSON.stringify(whole), `${JSON.stringify(values)}: ${JSON.stringify(inputs).slice(0, 120)}`)
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
})
|
|
94
|
-
|
|
95
|
-
test(`${name}: the words and the picture are there`, () => {
|
|
96
|
-
for (const file of ['guide.ko.md', 'guide.en.md', 'facts.md', 'thumbnail.png']) assert.ok(existsSync(join(RECIPES, name, file)), `${file}`)
|
|
97
|
-
})
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/* The palette is the figure's, shared by every template put into it: one colour name, one colour, across all of them. */
|
|
101
|
-
test('no two templates give one colour name two colours', async () => {
|
|
102
|
-
const seen = new Map<string, { value: string; by: string }>()
|
|
103
|
-
for (const name of names) {
|
|
104
|
-
const { recipe } = await buildTemplate(name)
|
|
105
|
-
for (const step of recipe.steps.filter(s => s.kind === 'set-material'))
|
|
106
|
-
for (const [token, value] of Object.entries((step.palette ?? {}) as Record<string, string>)) {
|
|
107
|
-
const before = seen.get(token)
|
|
108
|
-
assert.ok(!before || before.value === value, `${token}: ${before?.by} says ${before?.value}, ${name} says ${value}`)
|
|
109
|
-
seen.set(token, { value, by: name })
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
})
|
package/server/index.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import './routes.js'
|
|
2
|
-
|
|
3
|
-
/*
|
|
4
|
-
* 저작 도구를 어시스턴트 레지스트리에 등록한다.
|
|
5
|
-
*
|
|
6
|
-
* 이 패키지가 적재되면 대화면(도크)이 저작 중인 Figure 의 정본·비용·발행 판정을 읽고 후보를
|
|
7
|
-
* 요청할 수 있다. 능력을 복제하지 않고 figure-service 가 이미 가진 진입점을 투영한다 —
|
|
8
|
-
* 노출 범위는 대화면이 `toolCategories` 로 고른다(twin-ai · board-import 와 같은 방식).
|
|
9
|
-
*/
|
|
10
|
-
import { registerFigureToolCategories } from './service/figure/figure-tools.js'
|
|
11
|
-
registerFigureToolCategories()
|
|
12
|
-
/* The figure the modeller has open, said to the AI each turn (design/ai/screen-pattern.md §2-1). */
|
|
13
|
-
import './service/figure/figure-subject.js'
|
|
14
|
-
|
|
15
|
-
/*
|
|
16
|
-
* The recipe templates are read once at start (ADR-0095, amended): what was served, and any file whose form is wrong,
|
|
17
|
-
* said here rather than found by a person as a missing template.
|
|
18
|
-
*/
|
|
19
|
-
import { recipeTemplates } from './service/figure-recipe/figure-recipe-templates.js'
|
|
20
|
-
process.on('bootstrap-module-start' as any, () => {
|
|
21
|
-
const { templates, refused } = recipeTemplates()
|
|
22
|
-
console.log(`[figure-service:bootstrap] recipe templates ${templates.length}${refused.length ? `, left out: ${refused.join(' | ')}` : ''}`)
|
|
23
|
-
})
|
|
24
|
-
|
|
25
|
-
/*
|
|
26
|
-
* The pictures an install kept as base64 move into attachment-base by their content, once, at start (ADR-0104 decision
|
|
27
|
-
* 6). In the boot's one line: it writes, and sqlite holds one runner. A failure is said and the server goes on.
|
|
28
|
-
*/
|
|
29
|
-
import { getDataSource, inBootTurn } from '@things-factory/shell'
|
|
30
|
-
import { moveBase64Thumbnails } from './service/figure/figure-thumbnail-upgrade.js'
|
|
31
|
-
/* Who may read a figure picture by its attachment path (ADR-0106): registered with attachment-base at load. */
|
|
32
|
-
import './service/figure/figure-thumbnail-reader.js'
|
|
33
|
-
process.on('bootstrap-module-start' as any, () => {
|
|
34
|
-
inBootTurn(() => moveBase64Thumbnails(getDataSource()))
|
|
35
|
-
.then(moved => {
|
|
36
|
-
const any = moved.filter(m => m.moved || m.kept)
|
|
37
|
-
if (any.length) console.log(`[figure-service:bootstrap] thumbnails moved: ${any.map(m => `${m.table} ${m.moved}${m.kept ? ` (kept as base64: ${m.kept})` : ''}`).join(', ')}`)
|
|
38
|
-
})
|
|
39
|
-
.catch(error => console.error(`[figure-service] 썸네일을 옮기지 못했다 — ${error?.message ?? error}`))
|
|
40
|
-
})
|
|
41
|
-
|
|
42
|
-
export * from './service/index.js'
|
|
43
|
-
export * from './migrations/index.js'
|
|
44
|
-
export { registerFigureToolCategories } from './service/figure/figure-tools.js'
|
|
45
|
-
export { registerFigureCategories, figureCategories } from './service/figure/figure-categories.js'
|
|
46
|
-
export { registerFigureReleaseCheck, type FigureReleaseCheck, type FigureReleaseCheckInput, type GateFinding } from './service/figure/figure-format.js'
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
const glob = require('glob')
|
|
2
|
-
const path = require('path')
|
|
3
|
-
|
|
4
|
-
export var migrations = []
|
|
5
|
-
|
|
6
|
-
glob.sync(path.resolve(__dirname, '.', '**', '*.js')).forEach(function(file) {
|
|
7
|
-
if (file.indexOf('index.js') !== -1) return
|
|
8
|
-
migrations = migrations.concat(Object.values(require(path.resolve(file))) || [])
|
|
9
|
-
})
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import Router from 'koa-router'
|
|
2
|
-
|
|
3
|
-
import { checkPermission } from '@things-factory/auth-base'
|
|
4
|
-
import { getRepository } from '@things-factory/shell'
|
|
5
|
-
|
|
6
|
-
import { meshAttachmentOf } from '../service/figure/figure-mesh-store.js'
|
|
7
|
-
import { GLB_MIMETYPE } from '../service/figure/figure-glb.js'
|
|
8
|
-
import { thumbnailFiles, type ThumbnailFiles } from '../service/figure/figure-thumbnail-store.js'
|
|
9
|
-
import { publicDomainsOfFile } from '../service/figure/figure-public.js'
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* A mesh part's file, by its hash (ADR-0129 decision 8): what the modeller and a board draw a mesh part from, on the
|
|
13
|
-
* server that authored it. A board server serves its own copy at `/figure-library-file/:hash`.
|
|
14
|
-
*
|
|
15
|
-
* The same door as a figure query, and the same scope: this domain's files and its parent's, whose figures it reads.
|
|
16
|
-
* The content is its hash, so it never changes: cached privately for as long as a browser keeps anything.
|
|
17
|
-
*/
|
|
18
|
-
export const figureMeshRouter = new Router()
|
|
19
|
-
|
|
20
|
-
figureMeshRouter.get('/figure-mesh/:hash', async (context, next) => {
|
|
21
|
-
const { domain, user, unsafeIP, prohibitedPrivileges } = context.state
|
|
22
|
-
const allowed = await checkPermission({ category: 'figure', privilege: 'query', owner: true }, user, domain, unsafeIP, prohibitedPrivileges)
|
|
23
|
-
if (!allowed) {
|
|
24
|
-
context.status = 403
|
|
25
|
-
return
|
|
26
|
-
}
|
|
27
|
-
await sendFigureMesh(context, next, context.params.hash, domain)
|
|
28
|
-
})
|
|
29
|
-
|
|
30
|
-
/** The file of a mesh part the caller may read. Exported for tests, which give their own `files`. */
|
|
31
|
-
export async function sendFigureMesh(
|
|
32
|
-
context: any,
|
|
33
|
-
next: () => Promise<any>,
|
|
34
|
-
hash: string,
|
|
35
|
-
domain: { id: string; parentId?: string },
|
|
36
|
-
files: ThumbnailFiles = thumbnailFiles()
|
|
37
|
-
): Promise<void> {
|
|
38
|
-
if (!/^[0-9a-f]{64}$/.test(hash)) {
|
|
39
|
-
context.status = 404
|
|
40
|
-
return
|
|
41
|
-
}
|
|
42
|
-
/* Its own or its parent's, or kept by a domain whose public figure's releases draw from it (G2). */
|
|
43
|
-
const kept =
|
|
44
|
-
(await meshAttachmentOf({ getRepository }, [domain.id, domain.parentId].filter(Boolean) as string[], hash)) ??
|
|
45
|
-
(await meshAttachmentOf({ getRepository }, await publicDomainsOfFile(hash, domain), hash))
|
|
46
|
-
if (!kept) {
|
|
47
|
-
context.status = 404
|
|
48
|
-
return
|
|
49
|
-
}
|
|
50
|
-
const ours = () => {
|
|
51
|
-
context.type = GLB_MIMETYPE
|
|
52
|
-
context.set('Cache-Control', 'private, max-age=31536000, immutable')
|
|
53
|
-
context.set('ETag', `"${hash}"`)
|
|
54
|
-
}
|
|
55
|
-
ours()
|
|
56
|
-
context.status = 200
|
|
57
|
-
if (context.fresh) {
|
|
58
|
-
context.status = 304
|
|
59
|
-
return
|
|
60
|
-
}
|
|
61
|
-
await files.send(context, kept.path!, next)
|
|
62
|
-
ours()
|
|
63
|
-
}
|
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
import Router from 'koa-router'
|
|
2
|
-
|
|
3
|
-
import { checkPermission } from '@things-factory/auth-base'
|
|
4
|
-
import { config } from '@things-factory/env'
|
|
5
|
-
import { Refusal, speakRefusal } from '@things-factory/shell'
|
|
6
|
-
|
|
7
|
-
import { figurePackageOf } from '../service/figure/figure-package-export.js'
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Released figures as a package file to download (ADR-0114 결정 3): `GET /figure-package?refs=ns/type@v,...`.
|
|
11
|
-
*
|
|
12
|
-
* The same door as `figureBlueprint` (`figure-published`, domain owners included). The manifest names where the
|
|
13
|
-
* releases can be had again: `figure.publicUrl` in the server config, or this request's origin.
|
|
14
|
-
*/
|
|
15
|
-
export const figurePackageRouter = new Router()
|
|
16
|
-
|
|
17
|
-
figurePackageRouter.get('/figure-package', async context => {
|
|
18
|
-
const { domain, user, unsafeIP, prohibitedPrivileges } = context.state
|
|
19
|
-
const allowed = await checkPermission(
|
|
20
|
-
{ category: 'figure-published', privilege: 'query', owner: true },
|
|
21
|
-
user,
|
|
22
|
-
domain,
|
|
23
|
-
unsafeIP,
|
|
24
|
-
prohibitedPrivileges
|
|
25
|
-
)
|
|
26
|
-
if (!allowed) {
|
|
27
|
-
context.status = 403
|
|
28
|
-
return
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const refs = String(context.query.refs ?? '')
|
|
32
|
-
.split(',')
|
|
33
|
-
.map(ref => ref.trim())
|
|
34
|
-
.filter(Boolean)
|
|
35
|
-
|
|
36
|
-
try {
|
|
37
|
-
const { name, bytes } = await figurePackageOf({
|
|
38
|
-
refs,
|
|
39
|
-
domain,
|
|
40
|
-
exportedBy: user?.email ?? user?.name ?? null,
|
|
41
|
-
sourceUrl: config.get('figure.publicUrl', context.origin)
|
|
42
|
-
})
|
|
43
|
-
context.set('Content-Disposition', `attachment; filename="${name}"`)
|
|
44
|
-
context.set('Cache-Control', 'private, no-store')
|
|
45
|
-
context.type = 'application/zip'
|
|
46
|
-
context.body = bytes
|
|
47
|
-
} catch (error) {
|
|
48
|
-
if (!(error instanceof Refusal)) throw error
|
|
49
|
-
const spoken = speakRefusal(error, { t: (context as any).t })
|
|
50
|
-
context.status = 400
|
|
51
|
-
context.body = { code: error.code, params: error.params, message: spoken.message }
|
|
52
|
-
}
|
|
53
|
-
})
|