omnimux-forms 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -2
- package/assets/examples/README.md +7 -0
- package/assets/examples/replication-demo.mp4 +0 -0
- package/cordis.patch.yml +3 -0
- package/dsh.manifest.json +6 -0
- package/lib/client.js +39576 -0
- package/package.json +56 -4
- package/src/client/Fields.jsx +44 -0
- package/src/client/FormsPage.jsx +69 -0
- package/src/client/components.test.mjs +62 -0
- package/src/client/index.js +17 -0
- package/src/client/model.js +142 -0
- package/src/client/model.test.mjs +21 -0
- package/src/client/sidebar-entry.js +94 -0
- package/src/client/theme.js +20 -0
- package/src/client/workbench-seat.test.mjs +23 -0
- package/src/http.test.mjs +53 -0
- package/src/index.js +58 -0
- package/src/store.js +70 -0
- package/src/store.test.mjs +27 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { test } from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { mkdtemp, rm, mkdir, cp, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { createServer } from 'node:http'
|
|
7
|
+
import { pathToFileURL } from 'node:url'
|
|
8
|
+
import { copyExamples } from '../scripts/copy-examples.mjs'
|
|
9
|
+
|
|
10
|
+
test('draft routes enforce origin, optimistic revision and self-contained media ranges', async t => {
|
|
11
|
+
const directory = await mkdtemp(join(tmpdir(), 'forms-http-'))
|
|
12
|
+
t.after(() => rm(directory, { recursive: true, force: true }))
|
|
13
|
+
const installed = join(directory, 'installed')
|
|
14
|
+
await mkdir(join(installed, 'src'), { recursive: true })
|
|
15
|
+
await writeFile(join(installed, 'package.json'), '{"type":"module"}')
|
|
16
|
+
await cp(new URL('./index.js', import.meta.url), join(installed, 'src/index.js'))
|
|
17
|
+
await cp(new URL('./store.js', import.meta.url), join(installed, 'src/store.js'))
|
|
18
|
+
await copyExamples(new URL('../../../packages/form-contract/examples', import.meta.url), join(installed, 'assets/examples'))
|
|
19
|
+
const { apply } = await import(pathToFileURL(join(installed, 'src/index.js')).href)
|
|
20
|
+
const previous = process.env.DSH_HOME
|
|
21
|
+
process.env.DSH_HOME = directory
|
|
22
|
+
let handler
|
|
23
|
+
const services = { connection: { requestRejection: req => req.headers.cookie === 'session=authorized' ? undefined : 401 }, workspaceRegistry: { get: id => id === 'w' ? { id } : undefined } }
|
|
24
|
+
try { apply({ get: name => services[name], webServer: { register(route) { handler = route.handler; return () => {} } } }) }
|
|
25
|
+
finally { if (previous === undefined) delete process.env.DSH_HOME; else process.env.DSH_HOME = previous }
|
|
26
|
+
const server = createServer(handler)
|
|
27
|
+
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
|
|
28
|
+
t.after(() => new Promise(resolve => server.close(resolve)))
|
|
29
|
+
const origin = `http://127.0.0.1:${server.address().port}`, path = `${origin}/api/omnimux/forms/draft`
|
|
30
|
+
const query = new URLSearchParams({ workspaceId: 'w', templateId: 't', templateVersion: '1.0.0' })
|
|
31
|
+
assert.equal((await fetch(`${path}?${query}`)).status, 401)
|
|
32
|
+
assert.equal((await fetch(path, { method: 'PUT', headers: { 'Content-Type': 'application/json', Origin: origin }, body: '{}' })).status, 401)
|
|
33
|
+
const connection = services.connection
|
|
34
|
+
services.connection = undefined
|
|
35
|
+
assert.equal((await fetch(`${path}?${query}`)).status, 503)
|
|
36
|
+
services.connection = connection
|
|
37
|
+
const body = { workspaceId: 'w', templateId: 't', templateVersion: '1.0.0', expectedRevision: 0, values: { title: '用户草稿' } }
|
|
38
|
+
assert.equal((await fetch(path, { method: 'PUT', headers: { 'Content-Type': 'application/json', Origin: 'http://attacker.test', Cookie: 'session=authorized' }, body: JSON.stringify(body) })).status, 403)
|
|
39
|
+
const headers = { 'Content-Type': 'application/json', Origin: origin, Cookie: 'session=authorized' }
|
|
40
|
+
assert.equal((await fetch(path, { method: 'PUT', headers, body: JSON.stringify(body) })).status, 200)
|
|
41
|
+
assert.equal((await fetch(path, { method: 'PUT', headers, body: JSON.stringify(body) })).status, 409)
|
|
42
|
+
assert.equal((await fetch(path, { method: 'PUT', headers, body: JSON.stringify({ ...body, workspaceId: 'unknown' }) })).status, 404)
|
|
43
|
+
assert.equal((await fetch(`${path}?${new URLSearchParams({ ...Object.fromEntries(query), workspaceId: 'unknown' })}`, { headers })).status, 404)
|
|
44
|
+
const registry = services.workspaceRegistry
|
|
45
|
+
services.workspaceRegistry = undefined
|
|
46
|
+
assert.equal((await fetch(`${path}?${query}`, { headers })).status, 503)
|
|
47
|
+
services.workspaceRegistry = registry
|
|
48
|
+
const result = await (await fetch(`${path}?${new URLSearchParams({ workspaceId: 'w', templateId: 't', templateVersion: '1.0.0' })}`, { headers })).json()
|
|
49
|
+
assert.equal(result.draft.values.title, '用户草稿')
|
|
50
|
+
const media = await fetch(`${origin}/api/omnimux/forms/examples/replication-demo.mp4`, { headers: { ...headers, Range: 'bytes=0-99' } })
|
|
51
|
+
assert.equal(media.status, 206); assert.equal(media.headers.get('content-type'), 'video/mp4'); assert.equal((await media.arrayBuffer()).byteLength, 100)
|
|
52
|
+
assert.equal((await fetch(`${origin}/api/omnimux/forms/examples/missing.mp4`, { headers })).status, 404)
|
|
53
|
+
})
|
package/src/index.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { createReadStream } from 'node:fs'
|
|
2
|
+
import { stat } from 'node:fs/promises'
|
|
3
|
+
import { resolve, dirname, join } from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import { createDraftStore, DraftError } from './store.js'
|
|
6
|
+
export const name = 'omnimux-forms'
|
|
7
|
+
export const inject = ['webServer']
|
|
8
|
+
const PREFIX = '/api/omnimux/forms'
|
|
9
|
+
export function apply(ctx) {
|
|
10
|
+
if (!process.env.DSH_HOME) throw new Error('omnimux-forms requires explicit DSH_HOME')
|
|
11
|
+
const store = createDraftStore(join(process.env.DSH_HOME, 'omnimux', 'forms'))
|
|
12
|
+
const examples = resolve(dirname(fileURLToPath(import.meta.url)), '../assets/examples')
|
|
13
|
+
const webServer = ctx.webServer ?? ctx.get?.('webServer')
|
|
14
|
+
const dispose = webServer.register({ kind: 'prefix', path: PREFIX, async handler(req, res) {
|
|
15
|
+
const send = (status, body) => { res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(body)) }
|
|
16
|
+
try {
|
|
17
|
+
const connection = ctx.get?.('connection') ?? ctx.connection
|
|
18
|
+
if (typeof connection?.requestRejection !== 'function') return send(503, { error: 'Host connection authentication is unavailable' })
|
|
19
|
+
const rejection = connection.requestRejection(req)
|
|
20
|
+
if (rejection !== undefined) return send(rejection, { error: 'Host connection authentication refused the request' })
|
|
21
|
+
const url = new URL(req.url, 'http://localhost')
|
|
22
|
+
if (req.method === 'GET' && url.pathname.startsWith(`${PREFIX}/examples/`)) {
|
|
23
|
+
const filename = url.pathname.slice(`${PREFIX}/examples/`.length)
|
|
24
|
+
if (!/^[a-z0-9-]+\.(mp4|webm|png|jpg)$/.test(filename)) return send(404, { error: 'Not found' })
|
|
25
|
+
const path = join(examples, filename)
|
|
26
|
+
let info; try { info = await stat(path) } catch { return send(404, { error: 'Not found' }) }
|
|
27
|
+
const type = filename.endsWith('.mp4') ? 'video/mp4' : filename.endsWith('.webm') ? 'video/webm' : filename.endsWith('.png') ? 'image/png' : 'image/jpeg'
|
|
28
|
+
const range = req.headers.range?.match(/^bytes=(\d+)-(\d*)$/)
|
|
29
|
+
const start = range ? Number(range[1]) : 0, end = range?.[2] ? Math.min(Number(range[2]), info.size - 1) : info.size - 1
|
|
30
|
+
if (start > end || start >= info.size) { res.writeHead(416, { 'Content-Range': `bytes */${info.size}` }); return res.end() }
|
|
31
|
+
res.writeHead(range ? 206 : 200, { 'Content-Type': type, 'Content-Length': end - start + 1, 'Accept-Ranges': 'bytes', ...(range ? { 'Content-Range': `bytes ${start}-${end}/${info.size}` } : {}) })
|
|
32
|
+
const stream = createReadStream(path, { start, end }); stream.on('error', () => res.destroy()); stream.pipe(res); return
|
|
33
|
+
}
|
|
34
|
+
if (url.pathname !== `${PREFIX}/draft`) return send(404, { error: 'Not found' })
|
|
35
|
+
const registry = ctx.get?.('workspaceRegistry') ?? ctx.workspaceRegistry
|
|
36
|
+
if (typeof registry?.get !== 'function') return send(503, { error: 'Workspace registry is unavailable' })
|
|
37
|
+
const checkWorkspace = input => {
|
|
38
|
+
if (typeof input?.workspaceId !== 'string' || !input.workspaceId) throw new DraftError('Workspace is required')
|
|
39
|
+
if (!registry.get(input.workspaceId)) throw new DraftError('Workspace not found', 404)
|
|
40
|
+
}
|
|
41
|
+
if (req.method === 'GET') {
|
|
42
|
+
const input = Object.fromEntries(url.searchParams)
|
|
43
|
+
checkWorkspace(input)
|
|
44
|
+
return send(200, await store.get(input))
|
|
45
|
+
}
|
|
46
|
+
if (req.method !== 'PUT') return send(405, { error: 'Method not allowed' })
|
|
47
|
+
const origin = req.headers.origin
|
|
48
|
+
if (req.headers['sec-fetch-site'] === 'cross-site' || !origin || new URL(origin).host !== req.headers.host) return send(403, { error: 'Same-origin request required' })
|
|
49
|
+
if (!String(req.headers['content-type']).startsWith('application/json')) return send(415, { error: 'JSON required' })
|
|
50
|
+
const chunks = []; let size = 0
|
|
51
|
+
for await (const chunk of req) { size += chunk.length; if (size > 150_000) throw new DraftError('Draft too large', 413); chunks.push(chunk) }
|
|
52
|
+
let input; try { input = JSON.parse(Buffer.concat(chunks).toString()) } catch { throw new DraftError('Invalid JSON') }
|
|
53
|
+
checkWorkspace(input)
|
|
54
|
+
return send(200, await store.put(input))
|
|
55
|
+
} catch (error) { send(error instanceof DraftError ? error.status : 500, { error: error instanceof DraftError ? error.message : '无法读取或保存表单草稿' }) }
|
|
56
|
+
} })
|
|
57
|
+
ctx.effect?.(() => dispose, 'omnimux-forms: HTTP')
|
|
58
|
+
}
|
package/src/store.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
export class DraftError extends Error {
|
|
6
|
+
constructor(message, status = 400) { super(message); this.status = status }
|
|
7
|
+
}
|
|
8
|
+
function identity(value) {
|
|
9
|
+
for (const key of ['workspaceId', 'templateId', 'templateVersion']) {
|
|
10
|
+
if (typeof value?.[key] !== 'string' || !value[key].trim() || value[key].length > 500) throw new DraftError(`Invalid ${key}`)
|
|
11
|
+
}
|
|
12
|
+
return { workspaceId: value.workspaceId, templateId: value.templateId, templateVersion: value.templateVersion }
|
|
13
|
+
}
|
|
14
|
+
function draftValues(values) {
|
|
15
|
+
if (!values || typeof values !== 'object' || Array.isArray(values)) throw new DraftError('Invalid values')
|
|
16
|
+
if (JSON.stringify(values).length > 128_000) throw new DraftError('Draft too large', 413)
|
|
17
|
+
for (const [key, value] of Object.entries(values)) {
|
|
18
|
+
if (!/^[a-z][a-z0-9_]{0,63}$/.test(key)) throw new DraftError('Invalid field id')
|
|
19
|
+
if (typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value))) continue
|
|
20
|
+
if (!Array.isArray(value) || value.length > 20) throw new DraftError('Invalid field value')
|
|
21
|
+
for (const item of value) {
|
|
22
|
+
if (!item || typeof item !== 'object' || Object.keys(item).some(k => !['ref', 'name', 'mimeType', 'sizeBytes'].includes(k)) ||
|
|
23
|
+
typeof item.ref !== 'string' || !item.ref || /^(blob:|data:|file:|https?:)/i.test(item.ref) ||
|
|
24
|
+
typeof item.name !== 'string' || typeof item.mimeType !== 'string' || !Number.isSafeInteger(item.sizeBytes) || item.sizeBytes <= 0) {
|
|
25
|
+
throw new DraftError('Only stable attachment references may be saved')
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return structuredClone(values)
|
|
30
|
+
}
|
|
31
|
+
export function createDraftStore(directory) {
|
|
32
|
+
// Each workspace/template file retains prior versions. Optimistic revisions prevent cross-tab overwrite.
|
|
33
|
+
const queues = new Map()
|
|
34
|
+
function location(key) {
|
|
35
|
+
return join(directory, createHash('sha256').update(JSON.stringify([key.workspaceId, key.templateId])).digest('hex') + '.json')
|
|
36
|
+
}
|
|
37
|
+
async function read(key) {
|
|
38
|
+
try { return JSON.parse(await readFile(location(key), 'utf8')) }
|
|
39
|
+
catch (error) { if (error.code === 'ENOENT') return { versions: {} }; throw error }
|
|
40
|
+
}
|
|
41
|
+
function serialized(key, fn) {
|
|
42
|
+
const path = location(key), previous = queues.get(path) ?? Promise.resolve()
|
|
43
|
+
const pending = previous.catch(() => {}).then(fn)
|
|
44
|
+
queues.set(path, pending)
|
|
45
|
+
pending.finally(() => { if (queues.get(path) === pending) queues.delete(path) }).catch(() => {})
|
|
46
|
+
return pending
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
async get(input) {
|
|
50
|
+
const key = identity(input)
|
|
51
|
+
const data = await read(key)
|
|
52
|
+
return { draft: data.versions[key.templateVersion] ?? null, otherVersions: Object.keys(data.versions).filter(v => v !== key.templateVersion) }
|
|
53
|
+
},
|
|
54
|
+
async put(input) {
|
|
55
|
+
const key = identity(input), values = draftValues(input.values)
|
|
56
|
+
if (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0) throw new DraftError('Invalid revision')
|
|
57
|
+
return serialized(key, async () => {
|
|
58
|
+
const data = await read(key), previous = data.versions[key.templateVersion]
|
|
59
|
+
if ((previous?.revision ?? 0) !== input.expectedRevision) throw new DraftError('表单已在其他页面更新,请重新打开后再编辑。', 409)
|
|
60
|
+
const draft = { ...key, values, revision: input.expectedRevision + 1, updatedAt: new Date().toISOString() }
|
|
61
|
+
data.versions[key.templateVersion] = draft
|
|
62
|
+
await mkdir(directory, { recursive: true })
|
|
63
|
+
const path = location(key), temporary = `${path}.${randomUUID()}.tmp`
|
|
64
|
+
await writeFile(temporary, JSON.stringify(data), { mode: 0o600 })
|
|
65
|
+
await rename(temporary, path)
|
|
66
|
+
return { draft }
|
|
67
|
+
})
|
|
68
|
+
},
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { test } from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { mkdtemp, rm } from 'node:fs/promises'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { createDraftStore } from './store.js'
|
|
7
|
+
const key = { workspaceId: 'workspace-a', templateId: 'video', templateVersion: '1.0.0' }
|
|
8
|
+
async function fixture(t) { const dir = await mkdtemp(join(tmpdir(), 'forms-store-')); t.after(() => rm(dir, { recursive: true, force: true })); return createDraftStore(dir) }
|
|
9
|
+
test('persists stable values through reopening and isolates workspace and template versions', async t => {
|
|
10
|
+
const store = await fixture(t)
|
|
11
|
+
await store.put({ ...key, expectedRevision: 0, values: { name: 'A', video: [{ref:'opaque-1',name:'a.mp4',mimeType:'video/mp4',sizeBytes:12}] } })
|
|
12
|
+
assert.equal((await store.get(key)).draft.values.name, 'A')
|
|
13
|
+
assert.equal((await store.get({...key, workspaceId:'b'})).draft,null)
|
|
14
|
+
assert.deepEqual(await store.get({...key, templateVersion:'2.0.0'}),{draft:null,otherVersions:['1.0.0']})
|
|
15
|
+
})
|
|
16
|
+
test('serializes writes and rejects stale concurrent revision without losing content', async t => {
|
|
17
|
+
const store = await fixture(t)
|
|
18
|
+
const results = await Promise.allSettled([store.put({...key,expectedRevision:0,values:{name:'first'}}),store.put({...key,expectedRevision:0,values:{name:'second'}})])
|
|
19
|
+
assert.equal(results[0].status,'fulfilled'); assert.equal(results[1].reason.status,409)
|
|
20
|
+
assert.equal((await store.get(key)).draft.values.name,'first')
|
|
21
|
+
})
|
|
22
|
+
test('rejects temporary URLs, unexpected metadata and path-shaped ids without writing outside storage', async t => {
|
|
23
|
+
const store=await fixture(t)
|
|
24
|
+
for(const ref of ['blob:temporary','data:image/png;base64,a','file:///tmp/a','https://example.com']) await assert.rejects(store.put({...key,expectedRevision:0,values:{file:[{ref,name:'a',mimeType:'image/png',sizeBytes:1}]}}))
|
|
25
|
+
await assert.rejects(store.put({...key,expectedRevision:0,values:{'../x':'value'}}))
|
|
26
|
+
assert.equal((await store.get(key)).draft,null)
|
|
27
|
+
})
|