import assert from 'node:assert/strict' import test from 'node:test' import { readFile } from 'node:fs/promises' import { createRequire } from 'node:module' const requireWeb = createRequire(new URL('../../unreal_tran_web/package.json', import.meta.url)) const ts = requireWeb('typescript') const web = new URL('../../unreal_tran_web/src/', import.meta.url) const dataModule = source => `data:text/javascript;base64,${Buffer.from(source).toString('base64')}` async function compile(file, replacements = {}) { let source = await readFile(new URL(file, web), 'utf8') for (const [from, to] of Object.entries(replacements)) source = source.replaceAll(from, to) return dataModule(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText) } const { canUsePermission } = await import(await compile('config/roles.ts')) const { contentPermission, contentReviewPermission } = await import(await compile('utils/contentPermissions.ts')) test('content abilities use exact grants independently of teacher/admin/custom role names', () => { for (const code of ['admin', 'teacher', 'custom-author', 'student']) { assert.equal(canUsePermission('content.model.update', ['content.model.update'], [{ code, enabled: true, active: true }], 'SINGLE_ACTIVE'), true) assert.equal(canUsePermission('content.scene.update', ['content.model.update'], [{ code, enabled: true, active: true }], 'UNION'), false) assert.equal(canUsePermission('content.model.update', ['content.update'], [{ code, enabled: true, active: true }], 'UNION'), false) } }) test('copy, delete, review, revoke and submit retain separate action grants', () => { assert.equal(contentPermission('GUIDE', 'create'), 'content.ofd.create') assert.equal(contentPermission('TRAINING', 'delete'), 'content.training.delete') for (const action of ['APPROVE', 'REJECT']) assert.equal(contentReviewPermission('GUIDE', action), 'content.ofd.review') assert.equal(contentReviewPermission('GUIDE', 'REVOKE'), 'content.ofd.publish') for (const action of ['SUBMIT', 'WITHDRAW', 'REVISE']) assert.equal(contentReviewPermission('GUIDE', action), 'content.ofd.update') }) const authUrl = dataModule(`export const auth = { profile: { userId: 'reader', displayName: 'Actual user', permissions: [] }, activeRole: { code: 'admin' }, availableRoles: [], hasEffectiveRole: () => false, hasPermission(permission) { return this.profile.permissions.includes(permission) } }; export const useAuthStore = () => auth;`) const { auth } = await import(authUrl) const storageUrl = await compile('features/legacy-shared/scopedStorage.ts') const guideRuntime = await import(await compile('features/guide-legacy/runtime.ts', { './demo-src/asset-store.js': new URL('features/guide-legacy/demo-src/asset-store.js', web).href, './demo-src/content-list-store.js': new URL('features/guide-legacy/demo-src/content-list-store.js', web).href, '../legacy-shared/scopedStorage': storageUrl, '../../stores/auth': authUrl, })) test('OFD runtime uses the real session and rejects local create/update/delete without exact grants', async () => { const { createInitialOFDState } = await import(new URL('features/guide-legacy/demo-src/ofd-document.js', web)) const context = guideRuntime.legacyGuideRuntimeContext() assert.equal(context.actor.id, 'reader') assert.equal(context.readOnly, true) assert.equal(context.can('content.create'), false) assert.equal(context.storage.length, 0, 'read-only initialization must not seed projects') assert.throws(() => context.contentStore.createOFDProject({ title: 'Denied' }), /权限/) auth.profile.permissions = ['content.ofd.create'] const initial = createInitialOFDState() initial.project.name = 'Full initial payload' const created = context.contentStore.createOFDProject({ title: 'Created only', state: initial }) assert.ok(created.id) assert.equal(created.author, 'Actual user') assert.throws(() => context.contentStore.saveOFDProjectState(created.id, created.state), /权限/) assert.throws(() => context.contentStore.deleteOFDProject(created.id), /权限/) auth.profile.permissions = ['content.ofd.delete'] assert.equal(context.contentStore.deleteOFDProject(created.id), true) }) const { canPerformOFDAction, createInitialOFDState } = await import(new URL('features/guide-legacy/demo-src/ofd-document.js', web)) test('OFD lifecycle does not treat admin/teacher identity as a publish grant', () => { const state = createInitialOFDState() for (const role of ['admin', 'teacher']) assert.equal(canPerformOFDAction(state, 'publish', { role, permissions: [] }), false) assert.equal(canPerformOFDAction(state, 'publish', { role: 'custom', permissions: ['content.ofd.publish'] }), true) assert.equal(canPerformOFDAction(state, 'publish', { role: 'custom', permissions: ['content.ofd.update'] }), false) }) const { installLegacyModelPermissions } = await import(await compile('features/editors/model/legacy-iframe-permissions.ts', { '../common/editor-project-io.js': new URL('features/editors/common/editor-project-io.js', web).href, })) function modelFixture({ update = false, publish = false } = {}) { const calls = [] const editor = { apiEditorHydrated: true, apiState: 'ready', apiSession: { project: { id: 'test', version: 7 }, lastSavedFingerprint: '' }, saveProject: async () => { calls.push('save'); return {} }, publishToSceneLibrary: async () => { calls.push('save-and-publish'); return {} }, saveRecoveryCopy: () => calls.push('recovery'), serializeProject: () => ({}), toast: message => calls.push(message), transform: { enabled: true, detach() {}, attach() { calls.push('transform') } }, } const doc = { defaultView: { editorApp: editor }, body: {}, querySelector: () => null, querySelectorAll: () => [], addEventListener() {}, removeEventListener() {} } const previousObserver = globalThis.MutationObserver globalThis.MutationObserver = class { observe() {} disconnect() {} } const bridge = installLegacyModelPermissions(doc, { canCreate: () => false, canUpdate: () => update, canPublish: () => publish, publishSaved: async version => { calls.push(['publish-saved', version]); return { id: 'test', version: 8 } }, }) globalThis.MutationObserver = previousObserver return { editor, calls, bridge } } test('model iframe read-only bridge blocks autosave, recovery writes and transform attach', async () => { const { editor, calls, bridge } = modelFixture() assert.equal(await editor.saveProject(true, { automatic: true }), null) assert.equal(await editor.publishToSceneLibrary(), null) editor.saveRecoveryCopy() editor.transform.attach({}) assert.deepEqual(calls, []) assert.equal(editor.transform.enabled, false) bridge.dispose() }) test('model iframe publisher-only uses the loaded optimistic-lock version without saving', async () => { const { editor, calls, bridge } = modelFixture({ publish: true }) const published = await editor.publishToSceneLibrary() assert.equal(published.version, 8) assert.deepEqual(calls[0], ['publish-saved', 7]) assert.equal(calls.includes('save-and-publish'), false) bridge.dispose() }) test('committed role switch prevents iframe unload recovery from writing discarded changes', async () => { const { editor, calls, bridge } = modelFixture({ update: true, publish: true }) bridge.roleSwitchCommitted() editor.saveRecoveryCopy() assert.equal(await editor.saveProject(), null) assert.equal(await editor.publishToSceneLibrary(), null) assert.deepEqual(calls, []) bridge.dispose() }) test('read-only model viewing skips automatic migration and recovery without modifying saved data', async () => { const { editor, bridge } = modelFixture() editor.apiDocumentNeedsMigrationSave = true assert.equal(editor.apiDocumentNeedsMigrationSave, false) assert.equal(await editor.saveProject(true), null) bridge.dispose() assert.equal(editor.apiDocumentNeedsMigrationSave, true, 'the host must restore the original runtime state on disposal') }) const policy = await import(await compile('features/guide/publishDeliveriesPolicy.ts')) const publishSource = await readFile(new URL('features/guide/publishDeliveries.ts', web), 'utf8') const publishFunction = ts.transpileModule(publishSource.slice(publishSource.indexOf('export async function publishGuideWithDeliveries(')), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, }).outputText.replace(/^export /gm, '') const publishGuide = new Function('normalizeGuideContent', 'resolveGuideDeliveryAssets', 'commitGuideDeliveries', 'reusableGuideDelivery', 'assertCompleteGuideDeliveries', 'GUIDE_DELIVERY_ASSET_CODES', 'artifactFile', 'text', `${publishFunction};return publishGuideWithDeliveries`)( value => value, async () => ({}), policy.commitGuideDeliveries, policy.reusableGuideDelivery, policy.assertCompleteGuideDeliveries, policy.GUIDE_DELIVERY_ASSET_CODES, () => { throw new Error('publisher must not upload') }, value => String(value ?? '').trim(), ) function guidePublisherFixture(savedFingerprint) { const calls = [] const formats = ['OFD', 'OFFLINE_HTML'] const assets = formats.map(format => ({ code: policy.GUIDE_DELIVERY_ASSET_CODES[format], type: 'DOCUMENT', status: 'READY', sha256: 'a'.repeat(64), storageUri: `content://${format}`, metadata: { deliveryFormat: format, sourceFingerprint: savedFingerprint } })) const dependencies = { loadProject: async () => ({ id: 'g', version: 17, status: 'DRAFT', content: {}, assets }), readAsset: async () => new Blob(), uploadAsset: async () => { calls.push('upload'); throw new Error('forbidden') }, buildArtifacts: async () => ({ sourceFingerprint: 'current-source', artifacts: formats.map(format => ({ format, code: policy.GUIDE_DELIVERY_ASSET_CODES[format] })) }), publishProject: async (_id, _type, input) => { calls.push(input); return { id: 'g', version: 18 } }, } return { calls, dependencies } } test('OFD publisher reuses the exact saved source artifacts and optimistic-lock version without uploading', async () => { const { calls, dependencies } = guidePublisherFixture('current-source') const result = await publishGuide('g', { allowUpload: false }, dependencies) assert.equal(result.project.version, 18) assert.deepEqual(result.uploadedFormats, []) assert.deepEqual(result.reusedFormats, ['OFD', 'OFFLINE_HTML']) assert.equal(calls.length, 1) assert.equal(calls[0].version, 17) assert.equal(calls[0].deliveries.length, 2) }) test('OFD publisher cannot regenerate/upload stale artifacts or publish them against changed content', async () => { const { calls, dependencies } = guidePublisherFixture('stale-source') await assert.rejects(publishGuide('g', { allowUpload: false }, dependencies), /交付物/) assert.deepEqual(calls, []) })