Files
core/test/editor-vscode/flows.test.cjs
T
2026-11-27 06:03:56 +00:00

459 lines
44 KiB
JavaScript

const assert = require('node:assert/strict');
const test = require('node:test');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const Module = require('node:module');
const { pathToFileURL } = require('node:url');
const { promisify } = require('node:util');
const run = promisify(require('node:child_process').execFile);
test('generated flowcharts render offline and source clicks retain the actual location', async () => {
assert.ok(process.env.DEVER_TEST_BIN);
assert.ok(process.env.DEVER_BROWSER_TOOLS, 'directory containing existing playwright-core and @sparticuz/chromium');
const tools = Module.createRequire(path.join(process.env.DEVER_BROWSER_TOOLS, '..', 'package.json'));
const { chromium: playwright } = tools('playwright-core');
const { default: chromium } = tools('@sparticuz/chromium');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'dever flow browser '));
const extension = path.resolve(__dirname, '../../editor/vscode');
const project = path.join(root, 'project');
const subscriptions = [];
let browser;
const originalLoad = Module._load;
try {
const domain = path.join(project, 'module/shop/order');
await fs.mkdir(path.join(domain, 'flow'), { recursive: true });
await fs.writeFile(path.join(domain, 'flow/order.dv'), 'guarded(value: Int) (n: Int) { check value >= 1 else Invalid\nn = value }\nrule choose(flag: Bool, value: Int) (out: Int)\n| flag | value | out |\n| true | - | guarded(value) |\n| false | - | 0 |\nflow quote(flag: Bool, value: Int) (out: Int)\n| step | kind | do |\n| out | rule | choose(flag, value) |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nidentity(value: Int) (out: Int) { out = value }\ndouble(value: Int) (out: Int) { out = value * 2 }\napply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int) { out = transform(value) }\nhandlerStart(value: Int) (out: Int) { out = apply(value, identity) + apply(value, double) }\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nloop totals(values: List<Int>) (first: Int?, total: Int, items: List<Int>)\n| each value in values | value | sort | take | result |\n| first | >= 1 | - | - | first guarded(value) |\n| total | - | - | - | sum guarded(value) |\n| items | - | [value.desc] | 1 | list value |\nflow summary(values: List<Int>) (total: Int)\n| step | kind | do |\n| results | loop | totals(values) |\n| total | calc | results.total |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nloop grouped(values: List<Int>) (out: Map<Int, List<Int>>)\n| each value in values | result |\n| out | group guarded(value) |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nloop indexed(values: List<Int>) (out: Map<Int, Int>)\n| each value in values | result |\n| out | index value |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nupdate(value: Int, previous: Int) (acc: Int, stop: Bool) { acc = previous + guarded(value)\nstop = acc >= 10 }\nloop folded(values: List<Int>) (out: Int, total: Int)\n| each value in values | result |\n| out | foldUntil(acc = 0, update(value, acc)) |\n| total | sum value |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nrule next(state: Int) (out: Walk<Int, Int>)\n| state | out |\n| > 0 | Next(state, state - 1) |\n| <= 0 | Done |\nloop walking(seed: Int) (out: Int)\n| each value in walk(seed, next) | result |\n| out | sum value |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nloop byteTotal(data: Bytes) (out: Int)\n| each byte in data | result |\n| out | sum byte |\nbyteText(text: Text) (out: Int) { out = byteTotal(dever.bytes.fromText(text)) }\n');
await fs.writeFile(path.join(domain, 'api.dever'), 'cmd quote = app.quote\ncmd summary = app.summary');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\ntype JsonInput { name: Text, count: Int >= 1 }\ntype JsonRead { Ready(value: JsonInput), error Failed(reason: dever.json.JsonResult) }\nflow jsonRead(value: Json) (out: JsonInput)\n| step | kind | do |\n| out | calc | dever.json.decode(value) |\njsonCaptured(value: Json) (out: JsonRead) { out = result(dever.json.decode(value)) }\njsonEncoded(value: JsonInput) (out: Json) { out = dever.json.encode(value) }\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nflow cleanNumber(value: Text) (out: Int?)\n| step | kind | do |\n| cleaned | calc | text.trim(value) |\n| out | calc | int.parse(cleaned) |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nrule uuidValue(value: Uuid?) (out: Uuid)\n| value | out |\n| null | fail(Invalid) |\n| other | value |\nflow readUuid(value: Text) (out: Uuid)\n| step | kind | do |\n| parsed | calc | uuid.parse(value) |\n| out | rule | uuidValue(parsed) |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nflow normalizeTime(value: Text) (out: Text)\n| step | kind | do |\n| parsed | calc | dever.time.parseDatetime(value) |\n| out | calc | dever.time.formatDatetime(parsed) |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nsetting capacity: Int >= 1\nflow configured() (out: Int >= 1)\n| step | kind | do |\n| out | calc | capacity |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nsetting signing_key: Secret\nflow signed(value: Text) (out: Bytes)\n| step | kind | do |\n| bytes | calc | dever.bytes.fromText(value) |\n| out | calc | dever.crypto.hmacSha256(signing_key, bytes) |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nflow paused(value: Int) (out: Int)\n| step | kind | do |\n| - | flow | dever.time.sleep(value) |\n| out | calc | value |\nloop pausedAll(values: List<Int>) (out: List<Int>)\n| each value in values | result |\n| out | list paused(value) |\n');
const paused = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.paused', '--depth', '0'])).stdout).flows[0];
assert.ok(paused.nodes.some(node => node.target === 'dever.time.app.sleep' && node.label.includes('挂起') && node.site));
const timerDomain = path.join(project, 'module/shop/timer');
await fs.mkdir(path.join(timerDomain, 'flow'), { recursive: true });
await fs.copyFile(path.resolve(__dirname, '../rust/native/tasks.dever'), path.join(timerDomain, 'flow/timer.dv'));
const parallelDomain = path.join(project, 'module/shop/parallel');
await fs.mkdir(path.join(parallelDomain, 'flow'), { recursive: true });
const parallelFixture = await fs.readFile(path.resolve(__dirname, '../rust/native/parallel.dever'), 'utf8');
await fs.writeFile(path.join(parallelDomain, 'flow/parallel.dv'), parallelFixture.replace('cmd together = app.together\n', ''));
await fs.writeFile(path.join(parallelDomain, 'api.dever'), 'cmd together = app.together\n');
const parallel = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.parallel.app.together', '--depth', '0'])).stdout).flows[0];
for (const label of ['并发组 read', '等待本组全部步骤成功', '取消其余步骤,等待资源释放']) {
assert.ok(parallel.nodes.some(node => node.label === label && node.site), label);
}
assert.equal(parallel.edges.filter(edge => edge.label === '并发推进').length, 2);
const taskDomain = path.join(project, 'module/shop/task');
const tlsDomain = path.join(project, 'module/secure/config');
await fs.mkdir(path.join(tlsDomain, 'flow'), { recursive: true });
await fs.copyFile(path.resolve(__dirname, '../rust/native/tls.dever'), path.join(tlsDomain, 'flow/config.dv'));
const tls = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'secure.config.app.clientTls', '--depth', '1'])).stdout).flows[0];
assert.ok(tls.nodes.some(node => node.target === 'dever.tls.app.client' && node.site));
const httpDomain = path.join(project, 'module/shop/http_client');
await fs.mkdir(path.join(httpDomain, 'flow'), { recursive: true });
await fs.copyFile(path.resolve(__dirname, '../rust/native/http.dever'), path.join(httpDomain, 'flow/http_client.dv'));
const http = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.http_client.app.fetch', '--depth', '1'])).stdout).flows.find(flow => flow.nodes[0].label === 'shop.http_client.app.fetch');
assert.ok(http.nodes.some(node => node.target === 'dever.http.app.send' && node.site && node.label.includes('挂起')));
const serverDomain = path.join(project, 'module/shop/http_server');
const poolDomain = path.join(project, 'module/shop/http_pool');
await fs.mkdir(path.join(poolDomain, 'flow'), { recursive: true });
await fs.copyFile(path.resolve(__dirname, '../rust/native/http_pool.dever'), path.join(poolDomain, 'flow/http_pool.dv'));
const pool = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.http_pool.app.fetch', '--depth', '1'])).stdout).flows;
assert.ok(pool.some(flow => flow.nodes.some(node => node.target === 'dever.http.app.request' && node.site && node.label.includes('挂起'))));
const download = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.http_pool.app.download', '--depth', '1'])).stdout).flows;
assert.ok(download.some(flow => flow.nodes.some(node => node.target === 'dever.http.app.open' && node.site && node.label.includes('挂起'))));
await fs.mkdir(path.join(serverDomain, 'flow'), { recursive: true });
await fs.copyFile(path.resolve(__dirname, '../rust/native/http_server.dever'), path.join(serverDomain, 'flow/http_server.dv'));
const server = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.http_server.app.startTasks', '--depth', '2'])).stdout).flows;
assert.ok(server.some(flow => flow.nodes.some(node => node.label.includes('请求处理') && node.target === 'shop.http_server.app.scheduledRoute' && node.site)));
assert.ok(server.some(flow => flow.edges.some(edge => edge.label === '监听器关闭')));
const networkDomain = path.join(project, 'module/shop/network');
await fs.mkdir(path.join(networkDomain, 'flow'), { recursive: true });
await fs.copyFile(path.resolve(__dirname, '../rust/native/net.dever'), path.join(networkDomain, 'flow/network.dv'));
const network = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.network.app.roundTrip', '--depth', '0'])).stdout).flows[0];
assert.ok(network.nodes.some(node => node.target === 'dever.net.app.connect' && node.site && node.label.includes('挂起')));
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nflow verifyPassword(password: Secret, hash: Text) (valid: Bool)\n| step | kind | do |\n| valid | calc | blocking(dever.crypto.passwordVerify(password, hash)) |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nflow mailbox(value: Int) (out: Int?)\n| step | kind | do |\n| channel | calc | channel<Int>(1) |\n| - | calc | send(channel, value) |\n| - | calc | close(channel) |\n| out | calc | receive(channel) |\n');
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nloop streamFirst(values: AsyncStream<Int>) (out: Int?)\n| each value in values | result |\n| out | first value |\nflow firstTick() (out: Int?)\n| step | kind | do |\n| values | flow | dever.task.ticks(1) |\n| out | loop | streamFirst(values) |\n');
const streamFlow = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.streamFirst', '--depth', '0'])).stdout).flows[0];
assert.ok(streamFlow.nodes.some(node => node.label.includes('挂起拉取流的下一元素') && node.site));
assert.ok(streamFlow.nodes.some(node => node.label.includes('关闭来源流,保留外部资源') && node.site));
assert.ok(streamFlow.edges.some(edge => edge.label === '取消或运行故障'));
const mailbox = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.mailbox', '--depth', '0'])).stdout).flows[0];
for (const label of ['创建共享有界通道', '等待空位,移交消息', '关闭通道并唤醒等待者', '关闭后排空缓冲']) {
assert.ok(mailbox.nodes.some(node => node.label.includes(label) && node.site));
}
await fs.appendFile(path.join(domain, 'flow/order.dv'), [
'', 'flow createToken(size: Int) (out: Secret)',
'| step | kind | do |', '| out | flow | dever.crypto.token(size) |',
'flow saveFile(path: Text, bytes: Bytes) ()', '| step | kind | do |',
'| file | flow | dever.io.create(path) |', '| - | flow | dever.io.write(file, bytes) |',
'| - | flow | dever.io.close(file) |',
'flow readFileOffload(file: dever.system.File, size: Int) (out: dever.io.ReadState)',
'| step | kind | do |', '| out | calc | blocking(dever.io.read(file, size)) |', '',
'flow outputLine(text: Text) ()', '| step | kind | do |',
'| - | flow | dever.io.println(text) |', '',
'flow commandArguments() (out: List<Text>)', '| step | kind | do |',
'| out | flow | dever.process.arguments() |', ''
].join(String.fromCharCode(10)));
const token = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.createToken', '--depth', '0'])).stdout).flows[0];
assert.ok(token.nodes.some(node => node.label.includes('效果') && node.site && node.target === 'dever.crypto.app.token'));
const file = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.saveFile', '--depth', '0'])).stdout).flows[0];
const outputLine = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.outputLine', '--depth', '0'])).stdout).flows[0];
assert.ok(outputLine.nodes.some(node => node.target === 'dever.io.app.println' && node.site && node.label.includes('效果')));
const argumentsFlow = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.commandArguments', '--depth', '0'])).stdout).flows[0];
assert.ok(argumentsFlow.nodes.some(node => node.target === 'dever.process.app.arguments' && node.site && node.label.includes('效果')));
for (const name of ['create', 'write', 'close']) {
assert.ok(file.nodes.some(node => node.target === 'dever.io.app.' + name && node.site));
}
const blocking = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.verifyPassword', '--depth', '0'])).stdout).flows[0];
assert.ok(blocking.nodes.some(node => node.label.includes('线程池执行同步阻塞调用') && node.site && node.target === 'dever.crypto.app.passwordVerify'));
await fs.appendFile(path.join(domain, 'flow/order.dv'), '\nflow cpuPair(value: Int) (out: Int)\n| step | kind | parallel | do |\n| a | calc | compute | parallel(identity(value)) |\n| b | calc | compute | parallel(double(value)) |\n| out | calc | - | a + b |\n');
const cpu = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.cpuPair', '--depth', '0'])).stdout).flows[0];
assert.equal(cpu.nodes.filter(node => node.label.includes('线程池执行纯计算') && node.site && node.target).length, 2);
assert.equal(cpu.edges.filter(edge => edge.label === '并发推进').length, 2);
await fs.mkdir(path.join(taskDomain, 'flow'), { recursive: true });
const combinationsDomain = path.join(project, 'module/task/combinations');
await fs.mkdir(path.join(combinationsDomain, 'flow'), { recursive: true });
await fs.copyFile(path.resolve(__dirname, '../rust/native/combinations.dever'), path.join(combinationsDomain, 'flow/combinations.dv'));
const taskFixture = await fs.readFile(path.resolve(__dirname, '../rust/native/spawn.dever'), 'utf8');
await fs.writeFile(path.join(taskDomain, 'flow/task.dv'), taskFixture.split('\n').filter(line => !line.startsWith('cmd ')).join('\n'));
const tasks = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.task.app.main', '--depth', '0'])).stdout).flows[0];
assert.ok(tasks.nodes.some(node => node.label.includes('派生任务') && node.target === 'shop.task.app.child' && node.site));
assert.ok(tasks.nodes.some(node => node.label.includes('消费任务') && node.site));
const fileDomain = path.join(project, 'module/shop/files');
await fs.mkdir(path.join(fileDomain, 'flow'), { recursive: true });
await fs.copyFile(path.resolve(__dirname, '../rust/native/sync_stream.dever'), path.join(fileDomain, 'flow/files.dv'));
const concurrentDomain = path.join(project, 'module/shop/concurrent');
await fs.mkdir(path.join(concurrentDomain, 'flow'), { recursive: true });
await fs.copyFile(path.resolve(__dirname, '../rust/native/concurrent.dever'), path.join(concurrentDomain, 'flow/concurrent.dv'));
const concurrent = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.concurrent.app.ordered', '--depth', '0'])).stdout).flows[0];
for (const label of ['在途工作与待交付结果共用容量', '同一元素内逐行执行', '保留首个观察错误', '按输入顺序交付剩余结果']) {
assert.ok(concurrent.nodes.some(node => node.label.includes(label)));
}
const fileStream = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.files.app.first', '--depth', '0'])).stdout).flows[0];
for (const label of ['同步拉取文件流的下一元素', '关闭来源流,保留外部文件']) {
assert.ok(fileStream.nodes.some(node => node.label.includes(label) && node.site));
}
const articleDomain = path.join(project, 'module/shop/article');
await fs.mkdir(path.join(articleDomain, 'flow'), { recursive: true });
await fs.mkdir(path.join(articleDomain, 'data'), { recursive: true });
await fs.writeFile(path.join(articleDomain, 'data/article.dv'), 'type Article {title:Text(1,120) unique}');
await fs.writeFile(path.join(articleDomain, 'flow/article.dv'), 'transaction flow publish(title:Text, allowed:Bool) ()\n| step | kind | do |\n| - | data | data.create({title = title}) |\n| - | check | allowed else Conflict |\nflow page() (out:data.Page)\n| step | kind | do |\n| out | data | data.page() |\n');
const transaction = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect',project,'--json','--symbol','shop.article.app.publish','--depth','0'])).stdout).flows[0];
assert.ok(transaction.nodes.some(node => node.kind === 'data' && node.label.includes('data.create') && node.site));
for (const label of ['外层回滚','外层检查并提交','清理故障']) {
assert.ok(transaction.nodes.some(node => node.label.includes(label) && node.site),label);
}
for (const label of ['取消,释放事务连接','提交或收尾失败']) {
assert.ok(transaction.edges.some(edge => edge.label === label),label);
}
await fs.mkdir(path.join(articleDomain, 'api/front'), { recursive: true });
await fs.writeFile(path.join(articleDomain, 'api/front/main.dever'), 'post publish = app.publish\nget page = app.page\npost submit = app.submit\njob save(input:app.Payload) retry(1) timeout(1000) = app.save\n');
await fs.appendFile(path.join(articleDomain, 'flow/article.dv'), 'type Payload {title:Text}\ntype Title {title:Text}\nflow save(input:Payload) ()\n| step | kind | do |\n| - | data | data.create({title=input.title}) |\nflow submit(title:Text) (out:Id)\n| step | kind | do |\n| out | calc | enqueue(job.save,Payload {title=title},title) |\nflow lookup(title:Text) (out:Title?)\n| step | kind | do |\n| out | data | data.lookup(title) |\n');
await fs.appendFile(path.join(articleDomain, 'data/article.dv'), '\nsql lookup(title:Text) (row:app.Title?) {sqlite="SELECT title FROM shop_article WHERE title=?1",postgres="SELECT title FROM shop_article WHERE title=$1"}\n');
const httpEntry = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'POST /shop/article/front/main/publish', '--depth', '0'])).stdout).flows[0];
for (const label of ['项目 verify', '物理租户库', '当前角色', '提交整体事务', '回滚并保留业务原错']) {
assert.ok(httpEntry.nodes.some(node => node.label.includes(label) && node.site), label);
}
assert.ok(httpEntry.nodes.some(node => node.target === 'shop.article.app.publish'));
assert.ok(httpEntry.edges.some(edge => edge.label === '失败'));
const articleIndex = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json'])).stdout);
for (const kind of ['http','job','sql']) assert.ok(articleIndex.symbols.some(symbol => symbol.kind === kind), kind);
for (const kind of ['enqueue','sql']) assert.ok(articleIndex.calls.some(edge => edge.kind === kind && edge.site), kind);
const jobEntry = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.article.job.save', '--depth', '0'])).stdout).flows[0];
for (const label of ['User:重跑项目 verify', 'blocked', '失去租约', '业务与完成确认一起提交']) assert.ok(jobEntry.nodes.some(node => node.label.includes(label) && node.site), label);
for (const label of ['System','User','允许重试','次数耗尽']) assert.ok(jobEntry.edges.some(edge => edge.label === label), label);
await fs.appendFile(path.join(articleDomain, 'flow/article.dv'), 'flow currentIdentity() (value:Text)\n| step | kind | do |\n| value | calc | dever.auth.id() |\nflow roles() (values:List<dever.auth.Role>)\n| step | kind | do |\n| values | calc | dever.auth.roles() |\nflow saveRole() ()\n| step | kind | do |\n| - | calc | dever.auth.saveRole("reader","Reader",false,[]) |\nflow login() ()\n| step | kind | do |\n| - | calc | dever.auth.issueCookie("alice","session",null) |\nflow clearCookie() ()\n| step | kind | do |\n| - | calc | dever.auth.clearCookie() |\n');
await fs.appendFile(path.join(articleDomain, 'api/front/main.dever'), 'public post login = app.login\n');
for (const [symbol,label] of [['currentIdentity','读取可信身份'],['roles','读取实时授权'],['saveRole','在入口事务中修改授权'],['login','暂存 Cookie'],['clearCookie','不自动撤销业务会话']]) {
const graph = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect',project,'--json','--symbol','shop.article.app.'+symbol,'--depth','0'])).stdout).flows[0];
assert.ok(graph.nodes.some(node => node.label.includes(label) && node.site),symbol);
if(symbol !== 'currentIdentity') assert.ok(graph.edges.some(edge => edge.label === '失败'),symbol);
}
const loginEntry = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect',project,'--json','--symbol','POST /shop/article/front/main/login','--depth','0'])).stdout).flows[0];
for (const label of ['校验 Cookie Origin','失败不发送']) assert.ok(loginEntry.nodes.some(node => node.label.includes(label) && node.site),label);
await fs.appendFile(path.join(articleDomain, 'flow/article.dv'), 'flow requestPath() (out:Text)\n| step | kind | do |\n| out | calc | dever.api.request.path() |\n| - | calc | dever.api.request.setHeader("x-result","ok") |\n');
await fs.appendFile(path.join(articleDomain, 'api/front/main.dever'), 'public get requestPath = app.requestPath\n');
const requestGraph = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect',project,'--json','--symbol','shop.article.app.requestPath','--depth','0'])).stdout).flows[0];
for (const label of ['读取真实 HTTP 请求元数据','暂存响应头']) assert.ok(requestGraph.nodes.some(node => node.label.includes(label) && node.site));
const requestEntry = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect',project,'--json','--symbol','GET /shop/article/front/main/requestPath','--depth','0'])).stdout).flows[0];
assert.ok(requestEntry.nodes.some(node => node.label.includes('失败不发送') && node.site));
const restDomain = path.join(project, 'module/shop/notes');
await fs.mkdir(path.join(restDomain, 'flow'), { recursive: true });
await fs.mkdir(path.join(restDomain, 'api/front'), { recursive: true });
await fs.mkdir(path.join(restDomain, 'data'), { recursive: true });
await fs.writeFile(path.join(restDomain, 'data/user.dever'), 'global type User {name:Text}');
await fs.writeFile(path.join(restDomain, 'data/tenant.dever'), 'global type Tenant {name:Text}');
await fs.writeFile(path.join(restDomain, 'data/note.dever'), 'type Note {private owner user_id:data.user.id = dever.auth.userId(), title:Text index create = text.trim(input) replace = text.trim(input) search = text.trim(input)}');
await fs.writeFile(path.join(restDomain, 'flow/notes.dv'), 'type Identity {id:Text,user_id:data.user.id?,tenant_id:data.tenant.id?}\nflow verify(claims:dever.auth.Claims) (identity:Identity)\n| step | kind | do |\n| user | data | data.user.first(name == claims.subject) |\n| - | check | user != null else Unauthorized |\n| identity | calc | Identity {id=claims.subject,user_id=user.id,tenant_id=null} |\n');
await fs.writeFile(path.join(restDomain, 'api/front/main.dever'), 'rest data.note');
for (const [method, detail] of [['GET',false],['GET',true],['POST',false],['PUT',true],['DELETE',true]]) {
const symbol = method + ' /shop/notes/front/main' + (detail ? '/{id}' : '');
const graph = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect',project,'--json','--symbol',symbol,'--depth','0'])).stdout).flows[0];
assert.ok(graph, symbol);
assert.ok(graph.nodes.some(node => node.label.includes('owner') && node.site),symbol);
assert.ok(graph.nodes.some(node => node.label.includes('不输出 private') && node.site),symbol);
if (method === 'GET' && !detail) {
for (const label of ['已提供','未提供']) assert.ok(graph.edges.some(edge => edge.label === label),label);
assert.ok(graph.nodes.some(node => node.label.includes('规范化搜索值') && node.target));
}
if (['POST','PUT','DELETE'].includes(method)) {
assert.ok(graph.nodes.findIndex(node => node.label === '提交整体事务') < graph.nodes.findIndex(node => node.label.includes('不输出 private')));
}
}
await fs.writeFile(path.join(restDomain, 'data/category.dever'), 'type Category {name:Text}\nrelation notes=data.note.category_id');
await fs.appendFile(path.join(restDomain, 'data/note.dever'), '\nrelation children=data.child.note_id');
await fs.writeFile(path.join(restDomain, 'data/child.dever'), 'type Child {note_id:data.note.id,title:Text}');
const noteFile = path.join(restDomain, 'data/note.dever');
await fs.writeFile(noteFile, (await fs.readFile(noteFile, 'utf8')).replace('title:Text index', 'category_id:data.category.id?, title:Text index'));
await fs.appendFile(path.join(restDomain, 'flow/notes.dv'), 'flow related() (out:data.note.Page)\n| step | kind | do |\n| out | data | data.note.page(with = [category,children]) |\n');
const relatedIndex = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect',project,'--json'])).stdout);
assert.deepEqual(relatedIndex.diagnostics, []);
const relatedGraph = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect',project,'--json','--symbol','shop.notes.app.related','--depth','0'])).stdout).flows[0];
for (const name of ['category','children']) {
assert.ok(relatedGraph.nodes.some(node => node.label.includes('批量读取 '+name) && node.site));
assert.ok(relatedGraph.nodes.some(node => node.label.includes(name+' → Loaded;子关系保持 Unloaded') && node.site));
}
const portDomain = path.join(project, 'module/shop/message');
await fs.mkdir(path.join(portDomain, 'flow'), { recursive: true });
await fs.mkdir(path.join(portDomain, 'adapter'), { recursive: true });
await fs.writeFile(path.join(portDomain, 'port.dever'), 'read() (out:Text)');
await fs.writeFile(path.join(portDomain, 'flow/message.dv'), 'flow load() (out:Text)\n| step | kind | do |\n| out | port | port.read() |');
for (const implementation of ['local','remote']) {
await fs.writeFile(path.join(portDomain, 'adapter', implementation+'.dever'),
'setting {message:Text}\nport.read() (out:Text) {out=setting.message}');
}
const portIndex = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect',project,'--json','--symbol','shop.message.port.read','--depth','1'])).stdout);
const portSymbol = portIndex.symbols.find(symbol => symbol.name === 'shop.message.port.read');
assert.equal(portIndex.calls.filter(edge => edge.caller === portSymbol.id && edge.kind === 'implementation').length, 2);
const portGraph = portIndex.flows.find(flow => flow.symbol === portSymbol.id);
assert.ok(portGraph.nodes.some(node => node.label === '按启动配置选择实现' && node.site));
for (const implementation of ['local','remote']) {
assert.ok(portGraph.nodes.some(node => node.label === implementation && node.site));
assert.ok(portGraph.nodes.some(node => node.target === 'shop.message.adapter.'+implementation+'.port.read' && node.site));
}
const workerDomain = path.join(project, 'module/shop/external');
await fs.mkdir(path.join(workerDomain, 'flow'), { recursive: true });
await fs.writeFile(path.join(workerDomain, 'port.dever'), 'read(value:Int) (out:Int)');
await fs.writeFile(path.join(workerDomain, 'adapter.dever'), 'external exec "bin/worker" {allow network}');
await fs.writeFile(path.join(workerDomain, 'flow/external.dv'), 'flow load(value:Int) (out:Int)\n| step | kind | do |\n| out | port | port.read(value) |');
const workerIndex = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect',project,'--json','--symbol','shop.external.adapter.port.read','--depth','0'])).stdout);
const workerGraph = workerIndex.flows[0];
for (const label of ['握手后复用会话','响应按 Port 解码','协议故障回收进程组']) {
assert.ok(workerGraph.nodes.some(node => node.label.includes(label) && node.site), label);
}
assert.equal(workerIndex.worker_contracts.length, 1);
assert.deepEqual(workerIndex.worker_contracts[0].operations, ['read']);
await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--links']);
const indexed = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.indexed'])).stdout).flows[0];
assert.ok(indexed.nodes.some(node => node.label === 'dever.collection.Error.DuplicateKey' && node.site));
assert.ok(indexed.edges.some(edge => edge.label === '首次出现,插入'));
assert.ok(indexed.edges.some(edge => edge.label === '重复'));
const folded = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.folded', '--depth', '0'])).stdout).flows[0];
for (const label of ['初始化 acc: 0', '采用新的累积状态', 'stop 是否为 true']) {
assert.ok(folded.nodes.some(node => node.label === label && node.site), label + ': ' + JSON.stringify(folded.nodes));
}
for (const label of ['只求值一次', '随后判断停止', '是,标记本行完成', '否,本行继续累积', '已完成,跳过', '继续']) {
assert.ok(folded.edges.some(edge => edge.label === label), label);
}
const uri = filename => ({ fsPath: filename, toString: () => pathToFileURL(filename).toString() });
const walking = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.walking', '--depth', '0'])).stdout).flows[0];
for (const label of ['推进 walk 状态', 'Walk 步进结果', '保存 next_state,处理 item']) {
assert.ok(walking.nodes.some(node => node.label === label && node.site), label);
}
assert.ok(walking.nodes.some(node => node.target === 'shop.order.app.next'));
const byteText = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.byteText', '--depth', '0'])).stdout).flows[0];
assert.ok(byteText.nodes.some(node => node.target === 'dever.bytes.app.fromText'));
const cleanNumber = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.cleanNumber', '--depth', '0'])).stdout).flows[0];
for (const target of ['dever.text.app.trim', 'dever.int.app.parse']) {
assert.ok(cleanNumber.nodes.some(node => node.target === target && node.site));
}
const jsonRead = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.jsonRead', '--depth', '0'])).stdout).flows[0];
assert.ok(jsonRead.nodes.some(node => node.label === 'dever.json.decode(value)' && node.site));
assert.ok(jsonRead.edges.some(edge => edge.label === '失败'));
const jsonCaptured = JSON.parse((await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', 'shop.order.app.jsonCaptured', '--depth', '0'])).stdout).flows[0];
assert.ok(jsonCaptured.nodes.some(node => node.label === '将成功或业务错误交给显式 choice'));
assert.ok(!jsonCaptured.edges.some(edge => edge.label === '失败'));
for (const label of ['Next', 'Done', '全部行完成', '继续']) assert.ok(walking.edges.some(edge => edge.label === label), label);
const panels = [];
const vscode = {
Uri: { joinPath: (base, ...parts) => uri(path.join(base.fsPath, ...parts)) },
ViewColumn: { Beside: 2 },
window: { createWebviewPanel() {
const panel = { dispose() {}, onDidDispose() {}, webview: {
cspSource: 'https://dever-preview.test',
asWebviewUri: uri => `https://dever-preview.test/${path.basename(uri.fsPath)}`,
onDidReceiveMessage(callback) { panel.message = callback; return { dispose() {} }; }
} };
panels.push(panel);
return panel;
} }
};
Module._load = function(request, ...rest) { return request === 'vscode' ? vscode : originalLoad.call(this, request, ...rest); };
const { openFlowPreview } = require('../../editor/vscode/dist/flow-preview.cjs');
const { expandIndex } = require('../../editor/vscode/inspection.cjs');
Module._load = originalLoad;
browser = await playwright.launch({ executablePath: await chromium.executablePath(), args: chromium.args, headless: true });
const page = await browser.newPage();
page.on('pageerror', error => console.error('Browser error:', error.message));
page.on('console', message => { if (message.type() === 'error') console.error('Browser console:', message.text()); });
const scripts = new Map(await Promise.all(['flow-browser.js', 'mermaid.js'].map(async name => [`https://dever-preview.test/${name}`, await fs.readFile(path.join(extension, 'dist', name), 'utf8')])));
const messages = [];
await page.exposeFunction('deverMessage', message => messages.push(message));
await page.route('**/*', route => scripts.has(route.request().url())
? route.fulfill({ body: scripts.get(route.request().url()), contentType: 'text/javascript' }) : route.abort());
const projects = [project];
if (process.env.DEVER_FLOW_PROJECT) projects.push(process.env.DEVER_FLOW_PROJECT);
const targets = [];
for (const owner of projects) {
for await (const filename of fs.glob('module/*/*/link.md', { cwd: owner })) targets.push({ filename: path.join(owner, filename), owner });
}
let count = 0;
for (const { filename, owner } of targets) {
console.log(`Rendering ${filename}`);
await openFlowPreview({ subscriptions, extensionUri: uri(extension) }, uri(filename), owner);
const html = panels.at(-1).webview.html;
const expected = (html.match(/class="language-mermaid"/g) || []).length;
const nonce = /nonce="([^"]+)"/.exec(html)[1];
const bridge = `<script nonce="${nonce}">window.acquireVsCodeApi = () => ({postMessage: message => window.deverMessage(message)});</script>`;
await page.goto('about:blank');
await page.setContent(html.replace('<body ', `${bridge}<body `));
assert.equal(await page.evaluate(() => typeof globalThis.mermaid?.render), 'function');
await page.waitForSelector('body[data-rendered="true"]', { timeout: 60000 });
assert.deepEqual(await page.locator('.dever-flow-error').allTextContents(), [], filename);
assert.equal(await page.locator('.dever-flow > svg').count(), expected, filename);
assert.ok(expected > 0, filename);
count += expected;
const source = page.locator('.dever-flow a').first();
const href = await source.getAttribute('href') || await source.getAttribute('xlink:href');
await source.click();
await page.waitForTimeout(20);
assert.deepEqual(messages.at(-1), { type: 'open', href });
assert.match(href, /\.(?:dv|dever)(?:\.md)?#L\d+,\d+$/);
if (process.env.DEVER_FLOW_SCREENSHOT && path.basename(path.dirname(filename)) === 'audit') {
await page.screenshot({ path: process.env.DEVER_FLOW_SCREENSHOT, fullPage: true });
}
}
const { workflow } = require('../../editor/vscode/workflow.cjs');
const read = async name => {
const { stdout } = await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--json', '--symbol', name, '--depth', '0']);
return workflow(expandIndex(JSON.parse(stdout)), project).diagram;
};
await openFlowPreview({ subscriptions, extensionUri: uri(extension) }, uri(path.join(project, 'calls.md')), project, {
name: 'shop.order.app.quote', read, verify: async () => {}, changed: { event: () => ({ dispose() {} }) }
});
const panel = panels.at(-1);
const html = panel.webview.html;
const nonce = /nonce="([^"]+)"/.exec(html)[1];
await page.goto('about:blank');
const bridge = '<script nonce="' + nonce + '">window.acquireVsCodeApi = () => ({postMessage: message => window.deverMessage(message)});</script>';
await page.setContent(html.replace('<body ', bridge + '<body '));
await page.waitForSelector('body[data-rendered="true"]');
await page.getByRole('link', { name: '展开 shop.order.app.choose', exact: true }).click();
await page.waitForFunction(() => document.querySelector('details[open]'));
panel.webview.postMessage = message => page.evaluate(message => window.dispatchEvent(new MessageEvent('message', { data: message })), message);
const expansion = messages.at(-1);
assert.equal(expansion.type, 'expand');
await panel.message(expansion);
await page.waitForFunction(() => document.querySelectorAll('details .dever-flow svg').length === 1);
assert.equal(await page.locator('.dever-flow > svg').count(), 2);
assert.equal(await page.locator('details').count(), 1);
assert.deepEqual(await page.locator('.dever-flow-error').allTextContents(), []);
assert.ok(await page.locator('details').innerText().then(text => text.includes('flag: true') && text.includes('flag: false')));
await page.locator('details > summary').click();
assert.equal(await page.locator('details[open]').count(), 0);
await openFlowPreview({ subscriptions, extensionUri: uri(extension) }, uri(path.join(project, 'loops.md')), project, {
name: 'shop.order.app.summary', read, verify: async () => {}, changed: { event: () => ({ dispose() {} }) }
});
const loopPanel = panels.at(-1);
const loopHtml = loopPanel.webview.html;
const loopNonce = /nonce="([^"]+)"/.exec(loopHtml)[1];
const loopBridge = '<script nonce="' + loopNonce + '">window.acquireVsCodeApi = () => ({postMessage: message => window.deverMessage(message)});</script>';
await page.goto('about:blank');
await page.setContent(loopHtml.replace('<body ', loopBridge + '<body '));
await page.waitForSelector('body[data-rendered="true"]');
loopPanel.webview.postMessage = message => page.evaluate(message => window.dispatchEvent(new MessageEvent('message', { data: message })), message);
await page.getByRole('link', { name: '展开 shop.order.app.totals', exact: true }).click();
await page.waitForFunction(() => document.querySelector('details[open]'));
await loopPanel.message(messages.at(-1));
await page.waitForFunction(() => document.querySelectorAll('details .dever-flow svg').length === 1);
const loopText = await page.locator('details').innerText();
for (const label of ['拉取下一元素', '本行是否已完成', '已完成,跳过', '继续', '来源耗尽或全部完成', '不匹配,跳过本行', '初始化 take: 1', '稳定排序', '排序键: value desc']) assert.ok(loopText.includes(label), label);
const loopSource = page.locator('details .dever-flow a').filter({ hasText: '| total | - | - | - | sum guarded(value) |' });
await loopSource.click();
assert.equal(messages.at(-1).type, 'open');
const appSource = await fs.readFile(path.join(domain, 'flow/order.dv'), 'utf8');
assert.ok(messages.at(-1).href.includes('#L' + (appSource.split('\n').findIndex(line => line === '| total | - | - | - | sum guarded(value) |') + 1) + ','));
assert.deepEqual(await page.locator('.dever-flow-error').allTextContents(), []);
await openFlowPreview({ subscriptions, extensionUri: uri(extension) }, uri(path.join(project, 'handlers.md')), project, {
name: 'shop.order.app.handlerStart', read, verify: async () => {}, changed: { event: () => ({ dispose() {} }) }
});
const handlerPanel = panels.at(-1);
const handlerHtml = handlerPanel.webview.html;
const handlerNonce = /nonce="([^"]+)"/.exec(handlerHtml)[1];
const handlerBridge = '<script nonce="' + handlerNonce + '">window.acquireVsCodeApi = () => ({postMessage: message => window.deverMessage(message)});</script>';
await page.goto('about:blank');
await page.setContent(handlerHtml.replace('<body ', handlerBridge + '<body '));
await page.waitForSelector('body[data-rendered="true"]');
handlerPanel.webview.postMessage = message => page.evaluate(message => window.dispatchEvent(new MessageEvent('message', { data: message })), message);
for (const target of ['identity', 'double']) {
const binding = 'shop.order.app.apply [transform = shop.order.app.' + target + ']';
await page.getByRole('link', { name: '展开 ' + binding, exact: true }).click();
await page.waitForFunction(() => document.querySelector('details[open]'));
const message = messages.at(-1);
assert.equal(message.type, 'expand');
assert.equal(JSON.parse(decodeURIComponent(new URL(message.href).search.slice(1)))[1], binding);
await handlerPanel.message(message);
await page.getByRole('link', { name: '展开 shop.order.app.' + target, exact: true }).waitFor();
}
assert.equal(await page.locator('details').count(), 2);
assert.deepEqual(await page.locator('.dever-flow-error').allTextContents(), []);
await openFlowPreview({ subscriptions, extensionUri: uri(extension) }, uri(path.join(project, 'parallel.md')), project, {
name: 'shop.parallel.app.together', read, verify: async () => {}, changed: { event: () => ({ dispose() {} }) }
});
const parallelPanel = panels.at(-1);
const parallelHtml = parallelPanel.webview.html;
const parallelNonce = /nonce="([^"]+)"/.exec(parallelHtml)[1];
const parallelBridge = '<script nonce="' + parallelNonce + '">window.acquireVsCodeApi = () => ({postMessage: message => window.deverMessage(message)});</script>';
await page.goto('about:blank');
await page.setContent(parallelHtml.replace('<body ', parallelBridge + '<body '));
await page.waitForSelector('body[data-rendered="true"]');
parallelPanel.webview.postMessage = message => page.evaluate(message => window.dispatchEvent(new MessageEvent('message', { data: message })), message);
await page.getByRole('link', { name: '展开 shop.parallel.app.delayed', exact: true }).first().click();
await page.waitForFunction(() => document.querySelector('details[open]'));
await parallelPanel.message(messages.at(-1));
await page.waitForFunction(() => document.querySelectorAll('details .dever-flow svg').length === 1);
assert.ok((await page.locator('details').innerText()).includes('dever.time.sleep'));
await page.locator('.dever-flow a').filter({ hasText: '取消其余步骤,等待资源释放' }).click();
assert.equal(messages.at(-1).type, 'open');
const parallelSource = await fs.readFile(path.join(parallelDomain, 'flow/parallel.dv'), 'utf8');
assert.ok(messages.at(-1).href.includes('#L' + (parallelSource.split('\n').findIndex(line => line === '| left | flow | read | delayed(11, 5) |') + 1) + ','));
assert.deepEqual(await page.locator('.dever-flow-error').allTextContents(), []);
console.log(`Rendered ${count} real generated diagrams in ${targets.length} pages without network dependencies`);
} finally {
Module._load = originalLoad;
await browser?.close();
for (const subscription of subscriptions) subscription.dispose();
await fs.rm(root, { recursive: true });
}
});