Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,458 @@
|
||||
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 });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,312 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createRequire } = require('node:module');
|
||||
const test = require('node:test');
|
||||
|
||||
const root = path.resolve(__dirname, '../..');
|
||||
const extension = path.join(root, 'editor/vscode');
|
||||
const extensionRequire = createRequire(path.join(extension, 'package.json'));
|
||||
const textmate = extensionRequire('vscode-textmate');
|
||||
const oniguruma = extensionRequire('vscode-oniguruma');
|
||||
const cliArguments = process.argv.slice(2);
|
||||
assert.equal(cliArguments.length, 2, 'pass --markdown-grammar followed by the real VS Code grammar path');
|
||||
assert.equal(cliArguments[0], '--markdown-grammar');
|
||||
const markdownPath = path.resolve(cliArguments[1]);
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(extension, 'package.json'), 'utf8'));
|
||||
const configuration = JSON.parse(fs.readFileSync(path.join(extension, 'language-configuration.json'), 'utf8'));
|
||||
|
||||
async function loadGrammars() {
|
||||
const wasm = fs.readFileSync(extensionRequire.resolve('vscode-oniguruma/release/onig.wasm'));
|
||||
await oniguruma.loadWASM(wasm.buffer.slice(wasm.byteOffset, wasm.byteOffset + wasm.byteLength));
|
||||
const catalog = new Map();
|
||||
for (const contribution of manifest.contributes.grammars) {
|
||||
const filename = path.join(extension, contribution.path);
|
||||
catalog.set(contribution.scopeName, textmate.parseRawGrammar(fs.readFileSync(filename, 'utf8'), filename));
|
||||
}
|
||||
const markdown = textmate.parseRawGrammar(fs.readFileSync(markdownPath, 'utf8'), markdownPath);
|
||||
assert.equal(markdown.scopeName, 'text.html.markdown');
|
||||
catalog.set(markdown.scopeName, markdown);
|
||||
const registry = new textmate.Registry({
|
||||
onigLib: Promise.resolve({
|
||||
createOnigScanner: patterns => new oniguruma.OnigScanner(patterns),
|
||||
createOnigString: value => new oniguruma.OnigString(value)
|
||||
}),
|
||||
loadGrammar: scope => catalog.get(scope) || null,
|
||||
getInjections: scope => manifest.contributes.grammars
|
||||
.filter(contribution => contribution.injectTo?.includes(scope))
|
||||
.map(contribution => contribution.scopeName)
|
||||
});
|
||||
return {
|
||||
source: await registry.loadGrammarWithConfiguration('source.dever', 1, {}),
|
||||
markdown: await registry.loadGrammarWithConfiguration('text.html.markdown', 2, {
|
||||
embeddedLanguages: { 'meta.embedded.block.dever': 1 },
|
||||
tokenTypes: { 'meta.embedded.block.dever': 0 }
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
const grammars = loadGrammars();
|
||||
|
||||
function tokenize(grammar, document) {
|
||||
let state = textmate.INITIAL;
|
||||
return document.split(/\r\n|\r|\n/).map(line => {
|
||||
const encoded = grammar.tokenizeLine2(line, state);
|
||||
const result = grammar.tokenizeLine(line, state);
|
||||
state = result.ruleStack;
|
||||
return { line, tokens: result.tokens, encoded: encoded.tokens };
|
||||
});
|
||||
}
|
||||
|
||||
function tokenAt(rows, line, fragment) {
|
||||
const row = rows[line];
|
||||
const offset = row.line.indexOf(fragment);
|
||||
assert.ok(offset >= 0, `line ${line + 1} does not contain ${fragment}`);
|
||||
const token = row.tokens.find(candidate => candidate.startIndex <= offset && candidate.endIndex > offset);
|
||||
assert.ok(token, `no token for ${fragment} on line ${line + 1}`);
|
||||
return token;
|
||||
}
|
||||
|
||||
function hasScope(rows, line, fragment, scope) {
|
||||
const actual = tokenAt(rows, line, fragment).scopes;
|
||||
assert.ok(actual.includes(scope), `${fragment}: expected ${scope}, received ${actual.join(' ')}`);
|
||||
}
|
||||
|
||||
function sourceFiles(directory, suffix) {
|
||||
return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
|
||||
const filename = path.join(directory, entry.name);
|
||||
return entry.isDirectory() ? sourceFiles(filename, suffix) : filename.endsWith(suffix) ? [filename] : [];
|
||||
});
|
||||
}
|
||||
|
||||
test('types, fields and named function inputs/outputs receive Dever scopes', async () => {
|
||||
const rows = tokenize((await grammars).source, [
|
||||
'type Profile {',
|
||||
' id: Int?',
|
||||
' name: Text',
|
||||
'}',
|
||||
'greet(name: Text) (message: Text) {',
|
||||
' message = app.format(name)',
|
||||
'}'
|
||||
].join('\n'));
|
||||
hasScope(rows, 0, 'type', 'storage.type.dever');
|
||||
hasScope(rows, 0, 'Profile', 'entity.name.type.dever');
|
||||
hasScope(rows, 1, 'id', 'variable.other.member.dever');
|
||||
hasScope(rows, 1, 'Int', 'support.type.dever');
|
||||
hasScope(rows, 4, 'greet', 'entity.name.function.dever');
|
||||
hasScope(rows, 4, 'name', 'variable.other.member.dever');
|
||||
hasScope(rows, 4, 'message', 'variable.other.member.dever');
|
||||
hasScope(rows, 5, 'app', 'entity.name.namespace.dever');
|
||||
hasScope(rows, 5, 'format', 'entity.name.function.dever');
|
||||
});
|
||||
|
||||
test('typed local declarations and direct JSON capture retain ordinary scopes', async () => {
|
||||
const rows = tokenize((await grammars).source, [
|
||||
'read(payload: Json) (value: Text) {',
|
||||
' input: CreateInput = dever.json.decode(payload)',
|
||||
' decoded: DecodeResult = result(dever.json.decode(payload))',
|
||||
' value = input.name',
|
||||
'}'
|
||||
].join('\n'));
|
||||
hasScope(rows, 1, 'input', 'variable.other.member.dever');
|
||||
hasScope(rows, 1, 'CreateInput', 'entity.name.type.dever');
|
||||
hasScope(rows, 1, 'decode', 'entity.name.function.dever');
|
||||
hasScope(rows, 2, 'DecodeResult', 'entity.name.type.dever');
|
||||
hasScope(rows, 2, 'result', 'entity.name.function.dever');
|
||||
});
|
||||
|
||||
test('API, Model, Job and external Adapter declarations are covered', async () => {
|
||||
const source = (await grammars).source;
|
||||
for (const method of ['get', 'post', 'put', 'delete', 'cmd', 'rest']) {
|
||||
const rows = tokenize(source, `${method} profile = app.profile`);
|
||||
hasScope(rows, 0, method, 'keyword.control.api.dever');
|
||||
}
|
||||
const rows = tokenize(source, [
|
||||
'public get profile = app.profile',
|
||||
' private owner user_id: user.account.data.id = dever.auth.userId()',
|
||||
'index(user_id, created_at)',
|
||||
'sql ownedArticles(id: Int) (articles: List<Article>) {',
|
||||
'job send(message: Text) () fails app.Error {',
|
||||
'schedule send_every_minute {',
|
||||
'external npm "worker.js" { file "helper.mjs" }',
|
||||
'flow save(file: Upload) (key: Uuid)'
|
||||
].join('\n'));
|
||||
hasScope(rows, 0, 'public', 'storage.modifier.dever');
|
||||
hasScope(rows, 1, 'owner', 'storage.modifier.dever');
|
||||
hasScope(rows, 2, 'index', 'keyword.other.declaration.dever');
|
||||
hasScope(rows, 3, 'sql', 'keyword.other.declaration.dever');
|
||||
hasScope(rows, 4, 'job', 'storage.modifier.dever');
|
||||
hasScope(rows, 4, 'fails', 'storage.modifier.dever');
|
||||
hasScope(rows, 5, 'schedule', 'keyword.other.declaration.dever');
|
||||
hasScope(rows, 6, 'npm', 'keyword.other.external.dever');
|
||||
hasScope(rows, 6, 'file', 'keyword.other.adapter.dever');
|
||||
hasScope(rows, 7, 'Upload', 'support.type.dever');
|
||||
});
|
||||
|
||||
test('quoted text and escapes do not leak into subsequent lines', async () => {
|
||||
const rows = tokenize((await grammars).source, [
|
||||
'# type Fake and return',
|
||||
String.raw`message = "中文 # and type \n \u{4E2D} \""`,
|
||||
String.raw`invalid = "\q"`,
|
||||
'broken = "unfinished',
|
||||
'type Next { value: Text }'
|
||||
].join('\n'));
|
||||
hasScope(rows, 0, 'type', 'comment.line.number-sign.dever');
|
||||
hasScope(rows, 1, '#', 'string.quoted.double.dever');
|
||||
hasScope(rows, 1, '\\n', 'constant.character.escape.dever');
|
||||
hasScope(rows, 1, '\\u{4E2D}', 'constant.character.escape.dever');
|
||||
hasScope(rows, 2, '\\q', 'invalid.illegal.escape.dever');
|
||||
hasScope(rows, 4, 'type', 'storage.type.dever');
|
||||
assert.ok(!tokenAt(rows, 4, 'type').scopes.includes('string.quoted.double.dever'));
|
||||
});
|
||||
|
||||
test('block comments span lines, preserve strings and end before the next token', async () => {
|
||||
const rows = tokenize((await grammars).source, 'count = /* 备注\n# false | }\n*/ 12 // 3 # 取整\nmessage = "/* 普通文本 */"');
|
||||
hasScope(rows, 0, '备注', 'comment.block.dever');
|
||||
hasScope(rows, 1, 'false', 'comment.block.dever');
|
||||
hasScope(rows, 2, '12', 'constant.numeric.dever');
|
||||
hasScope(rows, 2, '//', 'keyword.operator.dever');
|
||||
hasScope(rows, 2, '取整', 'comment.line.number-sign.dever');
|
||||
hasScope(rows, 3, '/*', 'string.quoted.double.dever');
|
||||
});
|
||||
|
||||
test('integer division is an operator, not a JavaScript line comment', async () => {
|
||||
const rows = tokenize((await grammars).source, 'count = 12 // 3\namount = 1.25e-2\nvalid = true and not false');
|
||||
hasScope(rows, 0, '//', 'keyword.operator.dever');
|
||||
hasScope(rows, 0, '3', 'constant.numeric.dever');
|
||||
assert.ok(!tokenAt(rows, 0, '3').scopes.some(scope => scope.startsWith('comment.')));
|
||||
hasScope(rows, 1, '1.25e-2', 'constant.numeric.dever');
|
||||
hasScope(rows, 2, 'true', 'constant.language.dever');
|
||||
hasScope(rows, 2, 'and', 'keyword.operator.logical.dever');
|
||||
});
|
||||
|
||||
test('excluded control-flow syntax is not presented as a valid function', async () => {
|
||||
const rows = tokenize((await grammars).source, 'if(value)\nreturn value\nimport other\npackage main');
|
||||
for (const [line, keyword] of ['if', 'return', 'import', 'package'].entries()) {
|
||||
hasScope(rows, line, keyword, 'invalid.illegal.keyword.dever');
|
||||
}
|
||||
});
|
||||
|
||||
test('Markdown fences reuse source.dever while prose keeps Markdown scopes', async () => {
|
||||
for (const marker of ['```', '~~~']) {
|
||||
for (const language of ['dever']) {
|
||||
const rows = tokenize((await grammars).markdown, [
|
||||
'# 文档', '', '## 类型', `${marker}${language}`,
|
||||
'type Profile { name: Text }', marker, '', '正文 type Profile'
|
||||
].join('\n'));
|
||||
hasScope(rows, 4, 'type', 'storage.type.dever');
|
||||
hasScope(rows, 4, 'Text', 'support.type.dever');
|
||||
hasScope(rows, 4, 'Profile', 'meta.embedded.block.dever');
|
||||
assert.ok(!tokenAt(rows, 7, 'type').scopes.includes('source.dever'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('embedded tokens carry the Dever language ID and are not string tokens', async () => {
|
||||
const rows = tokenize((await grammars).markdown, '```dever\ntype Profile {}\n```');
|
||||
const metadata = rows[1].encoded[1];
|
||||
assert.equal(metadata & 0xff, 1);
|
||||
assert.equal((metadata >>> 8) & 3, 0);
|
||||
});
|
||||
|
||||
test('fence closing honors its character and minimum opening length', async () => {
|
||||
const rows = tokenize((await grammars).markdown, [
|
||||
'````dever', 'type First {}', '```', 'type Second {}',
|
||||
'~~~~', 'type Third {}', '`````', '正文 type Outside'
|
||||
].join('\n'));
|
||||
for (const line of [1, 3, 5]) hasScope(rows, line, 'type', 'storage.type.dever');
|
||||
assert.ok(!tokenAt(rows, 7, 'type').scopes.includes('source.dever'));
|
||||
const waves = tokenize((await grammars).markdown, '~~~dever\ntype Inside {}\n~~~~\n正文 type Outside');
|
||||
assert.ok(!tokenAt(waves, 3, 'type').scopes.includes('source.dever'));
|
||||
});
|
||||
|
||||
test('valid indentation and CRLF work without taking over other language fences', async () => {
|
||||
const rows = tokenize((await grammars).markdown, ' ```dever\r\ntype Profile {}\r\n ```\r\n正文');
|
||||
hasScope(rows, 1, 'type', 'storage.type.dever');
|
||||
for (const language of ['typescript', 'javascript', 'dever extra', 'typescript dever']) {
|
||||
const other = tokenize((await grammars).markdown, `\`\`\`${language}\ntype Profile {}\n\`\`\``);
|
||||
assert.ok(!tokenAt(other, 1, 'type').scopes.includes('source.dever'), language);
|
||||
}
|
||||
});
|
||||
|
||||
test('quotes, lists, showcase fences, indented code and comments retain Markdown scopes', async () => {
|
||||
for (const [document, line] of [
|
||||
['> ```dever\n> type Quoted {}\n> ```', 1],
|
||||
['- 示例\n\n ```dever\n type Nested {}\n ```', 3],
|
||||
['````markdown\n```dever\ntype Showcase {}\n```\n````', 2],
|
||||
[' ```dever\n type Indented {}\n ```', 1],
|
||||
['<!--\n```dever\ntype Comment {}\n```\n-->', 2]
|
||||
]) {
|
||||
const rows = tokenize((await grammars).markdown, document);
|
||||
assert.ok(!tokenAt(rows, line, 'type').scopes.includes('source.dever'), document);
|
||||
}
|
||||
});
|
||||
|
||||
test('language configuration enables line and block comments and retains indentation', () => {
|
||||
assert.deepEqual(configuration.comments, { lineComment: '#', blockComment: ['/*', '*/'] });
|
||||
assert.deepEqual(configuration.brackets, [['{', '}'], ['[', ']'], ['(', ')']]);
|
||||
const increase = new RegExp(configuration.indentationRules.increaseIndentPattern);
|
||||
const decrease = new RegExp(configuration.indentationRules.decreaseIndentPattern);
|
||||
for (const line of ['greet(name: Text) (message: Text) {', ' values = [', 'type Profile {']) {
|
||||
assert.ok(increase.test(line), line);
|
||||
}
|
||||
for (const line of ['message = "literal {"']) {
|
||||
assert.ok(!increase.test(line), line);
|
||||
}
|
||||
assert.ok(decrease.test(' }'));
|
||||
assert.ok(decrease.test(' ]'));
|
||||
assert.ok(configuration.autoClosingPairs.every(pair => pair.notIn.includes('string')));
|
||||
assert.deepEqual(manifest.contributes.languages[0].extensions, ['.dv', '.dever']);
|
||||
const injection = manifest.contributes.grammars.find(contribution => contribution.injectTo?.includes('text.html.markdown'));
|
||||
assert.deepEqual(injection.embeddedLanguages, { 'meta.embedded.block.dever': 'dever' });
|
||||
assert.deepEqual(injection.tokenTypes, { 'meta.embedded.block.dever': 'other' });
|
||||
assert.equal(manifest.main, './extension.cjs');
|
||||
assert.equal(manifest.dependencies, undefined);
|
||||
});
|
||||
|
||||
test('maintained plain and Markdown CMS files tokenize without illegal tokens', async () => {
|
||||
const loaded = await grammars;
|
||||
for (const [directory, suffix, grammar] of [
|
||||
['examples/next/cms', '.dv', loaded.source]
|
||||
]) {
|
||||
const files = sourceFiles(path.join(root, directory), suffix);
|
||||
assert.ok(files.length > 0, directory);
|
||||
let highlighted = 0;
|
||||
for (const filename of files) {
|
||||
const rows = tokenize(grammar, fs.readFileSync(filename, 'utf8'));
|
||||
let fileHighlighted = 0;
|
||||
for (const row of rows) {
|
||||
for (const token of row.tokens) {
|
||||
assert.ok(!token.scopes.some(scope => scope.startsWith('invalid.illegal.')), `${filename}: ${row.line}`);
|
||||
if (token.scopes.includes('source.dever')) fileHighlighted += 1;
|
||||
}
|
||||
}
|
||||
assert.ok(fileHighlighted > 0, `${filename} must actually enter the Dever grammar`);
|
||||
highlighted += fileHighlighted;
|
||||
}
|
||||
assert.ok(highlighted > files.length, `${directory} must actually enter the Dever grammar`);
|
||||
process.stdout.write(`CMS ${directory}: ${files.length} files, ${highlighted} Dever tokens\n`);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test('table definitions, guards and separators remain distinct from string content', async () => {
|
||||
const rows = tokenize((await grammars).source, [
|
||||
'rule choose(flag: Bool) (out: Text)',
|
||||
'| flag | out |',
|
||||
'| true | "a | b" |',
|
||||
'| false | "c" |',
|
||||
'flow work() ()',
|
||||
'| step | kind | do |',
|
||||
'| - | check | value >= 1_000 else Invalid |',
|
||||
'loop collect(values: List<Int>) (out: List<Int>)',
|
||||
'| each value in values | result |',
|
||||
'| out | list value |'
|
||||
].join('\n'));
|
||||
for (const [line, word] of [[0, 'rule'], [4, 'flow'], [6, 'check'], [6, 'else'], [7, 'loop'], [8, 'each'], [8, 'in']]) {
|
||||
hasScope(rows, line, word, 'keyword.control.dever');
|
||||
}
|
||||
hasScope(rows, 1, '|', 'punctuation.separator.table.dever');
|
||||
hasScope(rows, 2, 'a | b', 'string.quoted.double.dever');
|
||||
hasScope(rows, 6, '1_000', 'constant.numeric.dever');
|
||||
});
|
||||
@@ -0,0 +1,323 @@
|
||||
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, fileURLToPath } = require('node:url');
|
||||
|
||||
// VS Code 是外部边界;源码关系由真实候选编译器生成,不在测试中伪造索引。
|
||||
class Uri {
|
||||
constructor(url) { this.url = url; }
|
||||
static file(value) { return new Uri(pathToFileURL(value)); }
|
||||
static parse(value) { return new Uri(new URL(value)); }
|
||||
static joinPath(base, ...segments) { return Uri.file(path.join(base.fsPath, ...segments)); }
|
||||
static from(value) {
|
||||
const url = new URL(`${value.scheme}:/`);
|
||||
url.pathname = value.path;
|
||||
if (value.query) url.search = value.query;
|
||||
return new Uri(url);
|
||||
}
|
||||
get scheme() { return this.url.protocol.slice(0, -1); }
|
||||
get fsPath() { return this.scheme === 'file' ? fileURLToPath(this.url) : this.url.pathname; }
|
||||
get query() { return decodeURIComponent(this.url.search.slice(1)); }
|
||||
with(value) { const url = new URL(this.url); if (value.fragment !== undefined) url.hash = value.fragment; if (value.query !== undefined) url.search = value.query; return new Uri(url); }
|
||||
toString() { return this.url.toString(); }
|
||||
}
|
||||
class Range {
|
||||
constructor(first, second, third, fourth) {
|
||||
this.start = typeof first === 'number' ? { line: first, character: second } : first;
|
||||
this.end = typeof first === 'number' ? { line: third, character: fourth } : second;
|
||||
}
|
||||
}
|
||||
class EventEmitter {
|
||||
callbacks = new Set();
|
||||
event = callback => { this.callbacks.add(callback); return { dispose: () => this.callbacks.delete(callback) }; };
|
||||
fire(value) { for (const callback of this.callbacks) callback(value); }
|
||||
dispose() { this.callbacks.clear(); }
|
||||
}
|
||||
|
||||
test('real compiler powers navigation, documentation hover and saved-source refresh', async () => {
|
||||
assert.ok(process.env.DEVER_TEST_BIN, 'set DEVER_TEST_BIN to the built candidate compiler');
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'dever editor '));
|
||||
const sourcePath = path.join(root, 'main.dever');
|
||||
const code = 'label(name: Text) (text: Text) {\n text = name\n}\nflow first(name: Text) (text: Text)\n| step | kind | do |\n| text | calc | "😀" + label(name) + label("另") |\nsecond(name: Text) (text: Text) {\n text = label(name)\n}\n';
|
||||
const source = code + 'const suffix = "😀"\nsuffixSize() (size: Int) { size = length(suffix) }\ndecodeBytes(value: Text) (out: Text) { out = dever.bytes.toText(dever.bytes.fromText(value)) }\n' + [
|
||||
'identity(value: Int) (out: Int) { out = value }',
|
||||
'double(value: Int) (out: Int) { out = value * 2 }',
|
||||
'apply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int) { out = transform(value) }',
|
||||
'bound(value: Int) (out: Int) { out = apply(value, identity) + apply(value, double) }',
|
||||
'flow applyFlow(value: Int, transform: handler(value: Int) (out: Int)) (out: Int)',
|
||||
'| step | kind | do |', '| out | calc | transform(value) |',
|
||||
'rule applyRule(value: Int, transform: handler(value: Int) (out: Int)) (out: Int)',
|
||||
'| value | transform | out |', '| - | - | transform(value) |',
|
||||
'loop applyLoop(values: List<Int>, transform: handler(value: Int) (out: Int)) (out: Int)',
|
||||
'| each value in values | result |', '| out | sum transform(value) |',
|
||||
'boundTables(value: Int) (out: Int) { out = applyFlow(value, identity) + applyRule(value, identity) + applyLoop([value], identity) }', ''
|
||||
].join('\n');
|
||||
await fs.writeFile(sourcePath, source);
|
||||
const providers = {};
|
||||
const commands = {};
|
||||
const executed = [];
|
||||
const panels = [];
|
||||
const opened = [];
|
||||
const documents = new Map();
|
||||
const saved = new EventEmitter();
|
||||
const disposable = () => ({ dispose() {} });
|
||||
const context = { subscriptions: [], extensionUri: Uri.file(path.resolve(__dirname, '../../editor/vscode')) };
|
||||
function document(uri, text) {
|
||||
return {
|
||||
uri, languageId: uri.fsPath.endsWith('.md') ? 'markdown' : 'dever', isDirty: false, text,
|
||||
offsetAt(position) {
|
||||
return this.text.split('\n').slice(0, position.line).reduce((offset, line) => offset + line.length + 1, 0) + position.character;
|
||||
},
|
||||
getText(range) { return range ? this.text.slice(this.offsetAt(range.start), this.offsetAt(range.end)) : this.text; }
|
||||
};
|
||||
}
|
||||
const vscode = {
|
||||
Uri, Range, EventEmitter,
|
||||
DiagnosticSeverity: { Error: 0 },
|
||||
Diagnostic: class { constructor(range, message, severity) { Object.assign(this, {range, message, severity}); } },
|
||||
DiagnosticRelatedInformation: class { constructor(location, message) { Object.assign(this, {location, message}); } },
|
||||
MarkdownString: class {
|
||||
value = '';
|
||||
appendMarkdown(text) { this.value += text; return this; }
|
||||
appendCodeblock(text, language) { this.value += '```' + language + '\n' + text + '\n```\n'; return this; }
|
||||
},
|
||||
Hover: class { constructor(contents) { this.contents = contents; } },
|
||||
Location: class { constructor(uri, range) { Object.assign(this, { uri, range }); } },
|
||||
CodeLens: class { constructor(range, command) { Object.assign(this, { range, command }); } },
|
||||
CallHierarchyItem: class { constructor(kind, name, detail, uri, range, selectionRange) { Object.assign(this, { kind, name, detail, uri, range, selectionRange }); } },
|
||||
CallHierarchyIncomingCall: class { constructor(from, fromRanges) { Object.assign(this, { from, fromRanges }); } },
|
||||
CallHierarchyOutgoingCall: class { constructor(to, fromRanges) { Object.assign(this, { to, fromRanges }); } },
|
||||
SymbolKind: { Function: 11 },
|
||||
ViewColumn: { One: 1, Beside: 2 },
|
||||
window: {
|
||||
createOutputChannel: () => ({ appendLine() {}, dispose() {} }),
|
||||
createStatusBarItem: () => ({ show() {}, hide() {}, dispose() {} }),
|
||||
showErrorMessage(message) { throw new Error(message); },
|
||||
async showTextDocument(document, options) { opened.push({ document, options }); },
|
||||
createWebviewPanel(type, title, column, options) {
|
||||
const disposed = new EventEmitter();
|
||||
const panel = { type, title, column, options, dispose() { disposed.fire(); }, onDidDispose: disposed.event,
|
||||
webview: { cspSource: 'https://webview.test', asWebviewUri: uri => uri,
|
||||
onDidReceiveMessage(callback) { panel.message = callback; return disposable(); } }
|
||||
};
|
||||
panels.push(panel);
|
||||
return panel;
|
||||
}
|
||||
},
|
||||
commands: { registerCommand(name, callback) { commands[name] = callback; return disposable(); }, executeCommand: async (...values) => { executed.push(values); } },
|
||||
languages: { createDiagnosticCollection: () => ({ clear() {}, set() {}, dispose() {} }) },
|
||||
workspace: {
|
||||
isTrusted: true,
|
||||
get textDocuments() { return [...documents.values()]; },
|
||||
getWorkspaceFolder: uri => uri.fsPath.startsWith(root + path.sep) ? { uri: Uri.file(root) } : undefined,
|
||||
getConfiguration: () => ({ get: () => [process.env.DEVER_TEST_BIN] }),
|
||||
onDidChangeTextDocument: disposable, onDidSaveTextDocument: saved.event, onDidChangeConfiguration: disposable, onDidCloseTextDocument: disposable,
|
||||
createFileSystemWatcher: () => ({ onDidChange: disposable, onDidCreate: disposable, onDidDelete: disposable, dispose() {} }),
|
||||
registerTextDocumentContentProvider(scheme, provider) { providers[scheme] = provider; return disposable(); },
|
||||
async openTextDocument(uri) {
|
||||
const key = uri.toString();
|
||||
if (!documents.has(key)) {
|
||||
const text = uri.scheme === 'file' ? await fs.readFile(uri.fsPath, 'utf8') : await providers[uri.scheme].provideTextDocumentContent(uri);
|
||||
documents.set(key, document(uri, text));
|
||||
}
|
||||
return documents.get(key);
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const name of ['Definition', 'Reference', 'CallHierarchy', 'CodeLens', 'Hover']) {
|
||||
vscode.languages[`register${name}Provider`] = (_, provider) => { providers[name] = provider; return disposable(); };
|
||||
}
|
||||
const originalLoad = Module._load;
|
||||
Module._load = function(request, ...rest) { return request === 'vscode' ? vscode : originalLoad.call(this, request, ...rest); };
|
||||
try {
|
||||
const { registerNavigation } = require('../../editor/vscode/navigation.cjs');
|
||||
registerNavigation(context);
|
||||
Module._load = originalLoad;
|
||||
const doc = await vscode.workspace.openTextDocument(Uri.file(sourcePath));
|
||||
const callLine = source.split('\n').findIndex(line => line.includes('"😀"'));
|
||||
const position = { line: callLine, character: source.split('\n')[callLine].indexOf('label') + 1 };
|
||||
const definitions = await providers.Definition.provideDefinition(doc, position);
|
||||
assert.equal(definitions.length, 1);
|
||||
assert.equal(definitions[0].uri.fsPath, sourcePath);
|
||||
assert.equal(definitions[0].range.start.line, source.split('\n').findIndex(line => line.startsWith('label(')));
|
||||
const constantLine = source.split('\n').findIndex(line => line.startsWith('suffixSize'));
|
||||
const constantPosition = { line: constantLine, character: source.split('\n')[constantLine].indexOf('(suffix)') + 2 };
|
||||
const constantDefinition = await providers.Definition.provideDefinition(doc, constantPosition);
|
||||
assert.equal(constantDefinition.length, 1);
|
||||
assert.equal(constantDefinition[0].range.start.line, constantLine - 1);
|
||||
const constantReferences = await providers.Reference.provideReferences(doc, constantPosition, { includeDeclaration: false });
|
||||
assert.equal(constantReferences.length, 1);
|
||||
assert.equal(constantReferences[0].range.start.line, constantLine);
|
||||
const constantHover = await providers.Hover.provideHover(doc, constantPosition);
|
||||
assert.match(constantHover.contents[0].value, /const main\.main\.app\.suffix = "😀"/);
|
||||
const references = await providers.Reference.provideReferences(doc, position, { includeDeclaration: false });
|
||||
assert.equal(references.length, 3);
|
||||
assert.equal(references[0].range.start.character, source.split('\n')[callLine].indexOf('label'));
|
||||
const [target] = await providers.CallHierarchy.prepareCallHierarchy(doc, position);
|
||||
const incoming = await providers.CallHierarchy.provideCallHierarchyIncomingCalls(target);
|
||||
assert.equal(incoming.length, 2);
|
||||
assert.deepEqual(incoming.map(call => call.fromRanges.length).sort(), [1, 2]);
|
||||
const outgoing = await providers.CallHierarchy.provideCallHierarchyOutgoingCalls(incoming[0].from);
|
||||
assert.equal(outgoing[0].to.name, 'main.main.app.label');
|
||||
const lenses = await providers.CodeLens.provideCodeLenses(doc);
|
||||
assert.match(lenses[0].command.title, /2 个调用方 · 3 处调用/);
|
||||
const boundLine = source.split('\n').findIndex(line => line.startsWith('bound('));
|
||||
const [bound] = await providers.CallHierarchy.prepareCallHierarchy(doc, { line: boundLine, character: 1 });
|
||||
const bindings = await providers.CallHierarchy.provideCallHierarchyOutgoingCalls(bound);
|
||||
assert.equal(bindings.length, 2);
|
||||
assert.deepEqual(bindings.map(call => call.to.name).sort(), [
|
||||
'main.main.app.apply [transform = main.main.app.double]',
|
||||
'main.main.app.apply [transform = main.main.app.identity]'
|
||||
]);
|
||||
assert.ok(bindings.every(call => call.to.range.start.line === boundLine - 1));
|
||||
const boundHover = await providers.Hover.provideHover(doc, { line: boundLine, character: source.split('\n')[boundLine].indexOf('apply') + 1 });
|
||||
assert.match(boundHover.contents[0].value, /apply \[transform = main\.main\.app\.identity\]\(value: Int/);
|
||||
const tablesLine = source.split('\n').findIndex(line => line.startsWith('boundTables('));
|
||||
for (const [name, prefix] of [['applyFlow', 'flow'], ['applyRule', 'rule'], ['applyLoop', 'loop']]) {
|
||||
const hover = await providers.Hover.provideHover(doc, { line: tablesLine, character: source.split('\n')[tablesLine].indexOf(name) + 1 });
|
||||
assert.ok(hover.contents[0].value.includes(`${prefix} main.main.app.${name} [transform = main.main.app.identity](`), hover.contents[0].value);
|
||||
}
|
||||
const preview = Uri.from({ scheme: 'dever-calls', path: '/calls.md', query: JSON.stringify({ root, name: 'main.main.app.label' }) });
|
||||
const markdown = await providers['dever-calls'].provideTextDocumentContent(preview);
|
||||
assert.match(markdown, /## 定义/);
|
||||
assert.ok(markdown.includes('```dever'));
|
||||
assert.match(markdown, /\| 函数 \| 领域/);
|
||||
assert.match(markdown, /main.main.app.first/);
|
||||
assert.match(markdown, /main.main.app.second/);
|
||||
assert.ok(markdown.includes(`#L${callLine + 1}`));
|
||||
await commands['dever.showCalls'](root, 'main.main.app.label');
|
||||
const callsPanel = panels.at(-1);
|
||||
assert.match(callsPanel.webview.html, /<table>/);
|
||||
assert.match(callsPanel.webview.html, /<a href="file:/);
|
||||
const sourceHref = /<a href="(file:[^"]+)"/.exec(callsPanel.webview.html)[1];
|
||||
await callsPanel.message({ type: 'open', href: sourceHref });
|
||||
assert.equal(opened.at(-1).document.uri.fsPath, sourcePath);
|
||||
await callsPanel.message({ type: 'open', href: 'command:dever.showCalls?' + encodeURIComponent(JSON.stringify([root, 'main.main.app.first'])) });
|
||||
assert.match(callsPanel.webview.html, /<h1>main.main.app.first<\/h1>/);
|
||||
assert.match(callsPanel.webview.html, /执行流程/);
|
||||
const reply = [];
|
||||
callsPanel.webview.postMessage = async message => reply.push(message);
|
||||
await callsPanel.message({ type: 'expand', href: 'command:dever.expandFlow?' + encodeURIComponent(JSON.stringify([root, 'main.main.app.label'])), request: 1 });
|
||||
assert.equal(reply[0].type, 'expanded');
|
||||
assert.match(reply[0].html, /flowchart TD/);
|
||||
doc.isDirty = true;
|
||||
await assert.rejects(callsPanel.message({ type: 'open', href: sourceHref }), /保存/);
|
||||
doc.isDirty = false;
|
||||
callsPanel.dispose();
|
||||
doc.isDirty = true;
|
||||
assert.deepEqual(await providers.Definition.provideDefinition(doc, position), []);
|
||||
doc.isDirty = false;
|
||||
doc.text = source.replace('text = label(name)', 'text = name');
|
||||
await fs.writeFile(sourcePath, doc.text);
|
||||
saved.fire(doc);
|
||||
assert.equal((await providers.Reference.provideReferences(doc, position, { includeDeclaration: false })).length, 2);
|
||||
doc.text = source.replace('label(name)', 'missing(name)');
|
||||
await fs.writeFile(sourcePath, doc.text);
|
||||
saved.fire(doc);
|
||||
assert.deepEqual(await providers.Definition.provideDefinition(doc, position), []);
|
||||
const valid = await providers.Definition.provideDefinition(doc, { line: 0, character: 1 });
|
||||
assert.equal(valid.length, 1, 'unrelated valid definitions remain navigable');
|
||||
|
||||
const libraryLine = source.split('\n').findIndex(line => line.startsWith('decodeBytes'));
|
||||
const libraryPosition = { line: libraryLine, character: source.split('\n')[libraryLine].indexOf('dever.bytes.toText') + 1 };
|
||||
const [librarySite] = await providers.Definition.provideDefinition(doc, libraryPosition);
|
||||
const libraryPath = path.resolve(__dirname, '../../lib/dever/bytes.dv');
|
||||
assert.equal(librarySite.uri.fsPath, libraryPath);
|
||||
const [libraryItem] = await providers.CallHierarchy.prepareCallHierarchy(doc, libraryPosition);
|
||||
const libraryIncoming = await providers.CallHierarchy.provideCallHierarchyIncomingCalls(libraryItem);
|
||||
assert.ok(libraryIncoming.some(call => call.from.name === 'main.main.app.decodeBytes'));
|
||||
await commands['dever.showCalls'](root, 'dever.bytes.app.toText');
|
||||
const libraryPanel = panels.at(-1);
|
||||
const libraryHref = pathToFileURL(libraryPath).href + '#L15,1';
|
||||
await libraryPanel.message({ type: 'open', href: libraryHref });
|
||||
assert.equal(opened.at(-1).document.uri.fsPath, libraryPath);
|
||||
await assert.rejects(libraryPanel.message({ type: 'open', href: pathToFileURL(path.join(root, '../outside.dever')).href }), /当前源码或说明索引/);
|
||||
const libraryDoc = opened.at(-1).document;
|
||||
libraryDoc.isDirty = true;
|
||||
await assert.rejects(libraryPanel.message({ type: 'open', href: libraryHref }), /保存/);
|
||||
libraryDoc.isDirty = false;
|
||||
libraryPanel.dispose();
|
||||
|
||||
const cms = path.resolve(__dirname, '../../examples/next/cms');
|
||||
await commands['dever.showCalls'](cms, 'POST /content/article/admin/manage/publish');
|
||||
const entryPanel = panels.at(-1);
|
||||
const entryHtml = entryPanel.webview.html;
|
||||
assert.match(entryHtml, /只有草稿可以发布。.*<h2>执行流程<\/h2>/s);
|
||||
const [, topicHref] = /<a href="(file:[^"]+)">主题说明<\/a>/.exec(entryHtml);
|
||||
await entryPanel.message({ type: 'open', href: topicHref });
|
||||
const openedTopic = opened.at(-1);
|
||||
assert.equal(openedTopic.document.uri.fsPath, path.join(cms, 'module/content/article/doc/article.md'));
|
||||
assert.equal(openedTopic.document.getText().split('\n')[openedTopic.options.selection.start.line], '## content.article.app.publish');
|
||||
await commands['dever.showCalls'](cms, 'content.article.app.publish');
|
||||
const appHtml = panels.at(-1).webview.html;
|
||||
const folded = '<details><summary>实现细节</summary>';
|
||||
const split = appHtml.indexOf(folded);
|
||||
assert.ok(split > 0);
|
||||
assert.match(appHtml.slice(0, split), /只有草稿可以发布。.*data\.update\(…\)/s);
|
||||
assert.doesNotMatch(appHtml.slice(0, split), /where = id == article_id and status == Draft/);
|
||||
assert.match(appHtml.slice(split), /where = id == article_id and status == Draft/);
|
||||
|
||||
const project = path.join(root, 'application');
|
||||
const run = require('node:util').promisify(require('node:child_process').execFile);
|
||||
const domain = path.join(project, 'module/hello/greeting');
|
||||
await Promise.all(['doc', 'flow', 'api'].map(dir => fs.mkdir(path.join(domain, dir), { recursive: true })));
|
||||
await fs.writeFile(path.join(domain, 'flow/greeting.dv'), 'greet(name: Text) (message: Text) { message = name /* 局部实现说明 */ } # 行尾说明');
|
||||
await fs.writeFile(path.join(domain, 'api/greeting.dv'), 'cmd greet = app.greet');
|
||||
await fs.writeFile(path.join(domain, 'doc/greeting.md'), '## hello.greeting.app.greet\n按原样保留。');
|
||||
await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--links']);
|
||||
const app = await vscode.workspace.openTextDocument(Uri.file(path.join(project, 'module/hello/greeting/flow/greeting.dv')));
|
||||
vscode.window.activeTextEditor = { document: app, selection: { active: { line: 0, character: 1 } } };
|
||||
const hover = await providers.Hover.provideHover(app, { line: 0, character: 1 });
|
||||
assert.match(hover.contents[0].value, /greet\(name: Text\) \(message: Text\)/);
|
||||
assert.match(hover.contents[0].value, /按原样保留/);
|
||||
assert.doesNotMatch(hover.contents[0].value, /局部实现说明|行尾说明/);
|
||||
assert.match(hover.contents[0].value, /hello\.greeting\.greet/);
|
||||
assert.match(hover.contents[0].value, /command:dever.showCalls/);
|
||||
const api = await vscode.workspace.openTextDocument(Uri.file(path.join(project, 'module/hello/greeting/api/greeting.dv')));
|
||||
assert.match((await providers.Hover.provideHover(api, { line: 0, character: api.getText().indexOf('app.greet') + 5 })).contents[0].value, /按原样保留/);
|
||||
const topic = await vscode.workspace.openTextDocument(Uri.file(path.join(project, 'module/hello/greeting/doc/greeting.md')));
|
||||
topic.text = topic.text.replace('按原样保留', '输入不做改写');
|
||||
topic.isDirty = true;
|
||||
await assert.rejects(providers.Hover.provideHover(app, { line: 0, character: 1 }), /保存/);
|
||||
await fs.writeFile(topic.uri.fsPath, topic.text);
|
||||
topic.isDirty = false;
|
||||
saved.fire(topic);
|
||||
assert.match((await providers.Hover.provideHover(app, { line: 0, character: 1 })).contents[0].value, /输入不做改写/);
|
||||
await commands['dever.previewDocumentation'](project, 'hello.greeting.app.greet');
|
||||
assert.equal(executed.at(-1)[0], 'markdown.showPreviewToSide');
|
||||
await assert.rejects(commands['dever.openDomainLinks'](), /stale/);
|
||||
await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--links']);
|
||||
await commands['dever.openDomainLinks']();
|
||||
const panel = panels.at(-1);
|
||||
assert.equal(panel.type, 'dever.links');
|
||||
assert.match(panel.webview.html, /language-mermaid/);
|
||||
assert.match(panel.webview.html, /flowchart TD/);
|
||||
assert.match(panel.webview.html, /flow-browser\.js/);
|
||||
await panel.message({ type: 'open', href: 'flow/greeting.dv#L15,3' });
|
||||
assert.equal(opened.at(-1).document.uri.fsPath, app.uri.fsPath);
|
||||
assert.deepEqual(opened.at(-1).options.selection.start, { line: 14, character: 2 });
|
||||
const anchor = /id="(flow-[^"]+)"/.exec(panel.webview.html)[1];
|
||||
await panel.message({ type: 'open', href: `link.md#${anchor}` });
|
||||
assert.ok(panel.webview.html.includes(`data-anchor="${anchor}"`));
|
||||
await assert.rejects(panel.message({ type: 'open', href: 'https://example.invalid/' }), /只打开项目/);
|
||||
await assert.rejects(panel.message({ type: 'open', href: '../../../../outside.dever' }), /当前源码或说明索引/);
|
||||
topic.text = topic.text.replace('## hello.greeting.app.greet', '## hello.greeting.missing');
|
||||
await fs.writeFile(topic.uri.fsPath, topic.text);
|
||||
saved.fire(topic);
|
||||
const invalidDocumentation = await providers.Hover.provideHover(app, { line: 0, character: 1 });
|
||||
assert.match(invalidDocumentation.contents[0].value, /说明校验未通过/);
|
||||
assert.match(invalidDocumentation.contents[0].value, /greet\(name: Text\)/);
|
||||
await assert.rejects(commands['dever.openDomainLinks'](project, 'hello.greeting.app.greet'), /unknown or invalid documentation symbol/);
|
||||
} finally {
|
||||
Module._load = originalLoad;
|
||||
for (const subscription of context.subscriptions) subscription.dispose();
|
||||
for (const name of ['navigation', 'inspection', 'reading', 'hover']) {
|
||||
delete require.cache[require.resolve(`../../editor/vscode/${name}.cjs`)];
|
||||
}
|
||||
delete require.cache[require.resolve('../../editor/vscode/dist/flow-preview.cjs')];
|
||||
await fs.rm(root, { recursive: true });
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user