|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * #25785 — the translation bundle a console open downloads leaves out |
| 5 | + * Studio's `metadataForms`, and Studio's forms stay translated. |
| 6 | + * |
| 7 | + * ## The defect |
| 8 | + * |
| 9 | + * `GET /i18n/translations/:locale` served the i18n service's whole locale tree, |
| 10 | + * `metadataForms` included: 75 KB of the 221 KB raw a console open downloaded |
| 11 | + * on `examples/app-crm` zh-CN, the second-largest group after `objects`. No |
| 12 | + * browser reads it there. Studio's authoring forms arrive already translated: |
| 13 | + * the `/meta` (`/meta/types`) handler resolves `metadataForms.<type>` on the |
| 14 | + * server, over the same service, before it serves each form. |
| 15 | + * |
| 16 | + * ## What is pinned |
| 17 | + * |
| 18 | + * - A: both exits (the requested locale and the `zh` → `zh-CN` fallback) and |
| 19 | + * both spellings serve every group but the server-resolved ones, unchanged, |
| 20 | + * and the body is the closed `GetTranslationsResponseSchema`. |
| 21 | + * - B: the service's own tree is never edited, and `/meta`, read over the same |
| 22 | + * service AFTER a boot read, still serves Studio's form translated. That is |
| 23 | + * the consumer an in-place delete would silently break. |
| 24 | + * - C: the validator still hashes the bytes served, so a warm reopen is still |
| 25 | + * `304`, and a change confined to a group that is not served does not move it. |
| 26 | + */ |
| 27 | + |
| 28 | +import { createHash } from 'node:crypto'; |
| 29 | +import { describe, it, expect, vi } from 'vitest'; |
| 30 | +import { RestServer } from '@objectstack/rest'; |
| 31 | +import { GetTranslationsResponseSchema } from '@objectstack/spec/api'; |
| 32 | +import { SERVER_RESOLVED_TRANSLATION_GROUPS } from '@objectstack/spec/system'; |
| 33 | + |
| 34 | +import { handleI18nRequest } from './i18n.js'; |
| 35 | +import { apiErrorResponse } from '../error-envelope.js'; |
| 36 | +import type { DomainHandlerDeps } from '../domain-handler-registry.js'; |
| 37 | +import type { HttpProtocolContext } from '../http-dispatcher.js'; |
| 38 | + |
| 39 | +const MEMBER_EC = { userId: 'usr_member', isSystem: false, positions: [], permissions: [], systemPermissions: [] }; |
| 40 | + |
| 41 | +function member(headers: Record<string, string> = {}): HttpProtocolContext { |
| 42 | + return { request: { headers }, executionContext: { ...MEMBER_EC } } as unknown as HttpProtocolContext; |
| 43 | +} |
| 44 | + |
| 45 | +type Bundles = Record<string, Record<string, unknown>>; |
| 46 | + |
| 47 | +/** Hands back the STORED tree, as the core fallback and service-i18n both do. */ |
| 48 | +function makeService(bundles: Bundles) { |
| 49 | + return { |
| 50 | + getLocales: vi.fn(() => Object.keys(bundles)), |
| 51 | + getDefaultLocale: vi.fn(() => 'en'), |
| 52 | + getFallbackLocale: vi.fn(() => 'en'), |
| 53 | + getTranslations: vi.fn((locale: string) => bundles[locale] ?? {}), |
| 54 | + }; |
| 55 | +} |
| 56 | + |
| 57 | +function makeDeps(service: ReturnType<typeof makeService>): DomainHandlerDeps { |
| 58 | + return { |
| 59 | + getService: vi.fn(async () => service), |
| 60 | + resolveService: vi.fn(async () => service), |
| 61 | + success: (data: any, meta?: any) => ({ status: 200, body: { success: true, data, meta } }), |
| 62 | + error: (message: string, httpStatus = 500, details?: any) => |
| 63 | + apiErrorResponse({ message, httpStatus, details }), |
| 64 | + } as unknown as DomainHandlerDeps; |
| 65 | +} |
| 66 | + |
| 67 | +async function read( |
| 68 | + service: ReturnType<typeof makeService>, |
| 69 | + subPath = '/translations/zh-CN', |
| 70 | + query: Record<string, unknown> = {}, |
| 71 | + context: HttpProtocolContext = member(), |
| 72 | +): Promise<any> { |
| 73 | + return handleI18nRequest(makeDeps(service), subPath, 'GET', query, context); |
| 74 | +} |
| 75 | + |
| 76 | +function validatorOf(body: unknown): string { |
| 77 | + return `W/"${createHash('sha256').update(JSON.stringify(body)).digest('base64url')}"`; |
| 78 | +} |
| 79 | + |
| 80 | +/** The groups a console reads, as the platform bundle carries them. */ |
| 81 | +const SERVED_GROUPS = { |
| 82 | + objects: { lead: { label: '潜在客户', fields: { company: { label: '公司' } } } }, |
| 83 | + apps: { crm: { label: '客户关系管理' } }, |
| 84 | + settings: { mail: { title: '邮件投递' } }, |
| 85 | + messages: { save: '保存' }, |
| 86 | +}; |
| 87 | + |
| 88 | +/** Studio's dashboard authoring form, translated the way platform-objects ships it. */ |
| 89 | +const METADATA_FORMS = { |
| 90 | + dashboard: { |
| 91 | + label: '仪表板', |
| 92 | + sections: { layout: { label: '布局' } }, |
| 93 | + fields: { columns: { label: '列数', helpText: '栅格列数' } }, |
| 94 | + }, |
| 95 | +}; |
| 96 | + |
| 97 | +function zhTree(): Record<string, unknown> { |
| 98 | + return { ...SERVED_GROUPS, metadataForms: METADATA_FORMS }; |
| 99 | +} |
| 100 | + |
| 101 | +describe('#25785 A — the served document leaves the server-resolved groups out', () => { |
| 102 | + it('names metadataForms as a server-resolved group (the constant this door reads)', () => { |
| 103 | + expect(SERVER_RESOLVED_TRANSLATION_GROUPS).toContain('metadataForms'); |
| 104 | + }); |
| 105 | + |
| 106 | + it.each([ |
| 107 | + ['the path spelling', '/translations/zh-CN', {}], |
| 108 | + ['the query spelling', '/translations', { locale: 'zh-CN' }], |
| 109 | + ])('%s: every other group is served unchanged, metadataForms is not', async (_label, subPath, query) => { |
| 110 | + const result = await read(makeService({ en: {}, 'zh-CN': zhTree() }), subPath, query); |
| 111 | + expect(result.response.status).toBe(200); |
| 112 | + expect(result.response.body.data).toEqual({ locale: 'zh-CN', translations: SERVED_GROUPS }); |
| 113 | + expect(result.response.body.data.translations).not.toHaveProperty('metadataForms'); |
| 114 | + }); |
| 115 | + |
| 116 | + it('the locale fallback exit (zh → zh-CN) leaves it out too', async () => { |
| 117 | + const result = await read(makeService({ en: {}, 'zh-CN': zhTree() }), '/translations/zh'); |
| 118 | + expect(result.response.status).toBe(200); |
| 119 | + expect(result.response.body.data).toEqual({ locale: 'zh-CN', requestedLocale: 'zh', translations: SERVED_GROUPS }); |
| 120 | + }); |
| 121 | + |
| 122 | + it('the body satisfies the closed GetTranslationsResponseSchema, which refuses the unserved group', async () => { |
| 123 | + const result = await read(makeService({ en: {}, 'zh-CN': zhTree() })); |
| 124 | + expect(GetTranslationsResponseSchema.safeParse(result.response.body.data).success).toBe(true); |
| 125 | + |
| 126 | + // Control: the same document WITH the group is refused by the schema, so |
| 127 | + // the parse above passes because the door left it out, not because the |
| 128 | + // schema reads nothing. |
| 129 | + const unserved = GetTranslationsResponseSchema.safeParse({ locale: 'zh-CN', translations: zhTree() }); |
| 130 | + expect(unserved.success).toBe(false); |
| 131 | + expect(unserved.error?.issues.map((i) => i.code)).toContain('unrecognized_keys'); |
| 132 | + }); |
| 133 | + |
| 134 | + it('a tree with nothing to leave out is served as it is', async () => { |
| 135 | + const result = await read(makeService({ en: {}, 'zh-CN': { ...SERVED_GROUPS } })); |
| 136 | + expect(result.response.body.data.translations).toEqual(SERVED_GROUPS); |
| 137 | + }); |
| 138 | +}); |
| 139 | + |
| 140 | +// ── B: the service's tree, and the consumer that reads it ─────────────────── |
| 141 | + |
| 142 | +function mockRes() { |
| 143 | + return { json: vi.fn(), status: vi.fn().mockReturnThis(), header: vi.fn(), send: vi.fn() }; |
| 144 | +} |
| 145 | + |
| 146 | +/** A RestServer whose `/meta` handler translates from `i18n` — the route Studio reads its forms from. */ |
| 147 | +function restOver(i18n: ReturnType<typeof makeService>): RestServer { |
| 148 | + const server = { |
| 149 | + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), |
| 150 | + use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), |
| 151 | + }; |
| 152 | + const protocol = { |
| 153 | + getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' } }), |
| 154 | + getMetaTypes: vi.fn(async () => ({ |
| 155 | + entries: [{ |
| 156 | + type: 'dashboard', |
| 157 | + label: 'Dashboard', |
| 158 | + form: { |
| 159 | + schemaId: 'dashboard', |
| 160 | + type: 'simple', |
| 161 | + sections: [{ name: 'layout', label: 'Layout', fields: [{ field: 'columns', type: 'number', label: 'Columns' }] }], |
| 162 | + }, |
| 163 | + }], |
| 164 | + types: ['dashboard'], |
| 165 | + registered: ['dashboard'], |
| 166 | + })), |
| 167 | + getMetaItems: vi.fn(async () => []), |
| 168 | + getMetaItem: vi.fn(async () => undefined), |
| 169 | + getMetaItemCached: undefined as any, |
| 170 | + findData: vi.fn().mockResolvedValue([]), |
| 171 | + }; |
| 172 | + const rest = new RestServer( |
| 173 | + server as any, protocol as any, { api: { requireAuth: false } } as any, |
| 174 | + undefined, undefined, undefined, undefined, undefined, |
| 175 | + undefined, undefined, undefined, undefined, undefined, |
| 176 | + async () => i18n, |
| 177 | + ); |
| 178 | + (rest as any).resolveExecCtx = async () => ({ userId: 'u1', systemPermissions: [] }); |
| 179 | + rest.registerRoutes(); |
| 180 | + return rest; |
| 181 | +} |
| 182 | + |
| 183 | +async function readStudioForm(rest: RestServer, locale: string): Promise<any> { |
| 184 | + const route = (rest as any).getRoutes().find((r: any) => r.method === 'GET' && r.path === '/api/v1/meta'); |
| 185 | + if (!route) throw new Error('route not registered: GET /api/v1/meta'); |
| 186 | + const res = mockRes(); |
| 187 | + await route.handler({ method: 'GET', params: {}, query: {}, body: {}, headers: { 'accept-language': locale } }, res); |
| 188 | + const body = res.json.mock.calls.at(-1)?.[0]; |
| 189 | + return body.entries.find((e: any) => e.type === 'dashboard'); |
| 190 | +} |
| 191 | + |
| 192 | +describe("#25785 B — the service keeps the group, and Studio's forms stay translated", () => { |
| 193 | + it("a boot read does not edit the service's tree", async () => { |
| 194 | + const stored = zhTree(); |
| 195 | + const service = makeService({ en: {}, 'zh-CN': stored }); |
| 196 | + await read(service); |
| 197 | + expect(stored.metadataForms).toBe(METADATA_FORMS); |
| 198 | + expect(service.getTranslations('zh-CN')).toHaveProperty('metadataForms', METADATA_FORMS); |
| 199 | + }); |
| 200 | + |
| 201 | + it('/meta, read over the same service after a boot read, serves the form translated', async () => { |
| 202 | + const service = makeService({ en: {}, 'zh-CN': zhTree() }); |
| 203 | + const boot = await read(service); |
| 204 | + expect(boot.response.body.data.translations).not.toHaveProperty('metadataForms'); |
| 205 | + |
| 206 | + const entry = await readStudioForm(restOver(service), 'zh-CN'); |
| 207 | + expect(entry.label).toBe('仪表板'); |
| 208 | + expect(entry.form.sections[0].label).toBe('布局'); |
| 209 | + expect(entry.form.sections[0].fields[0].label).toBe('列数'); |
| 210 | + }); |
| 211 | +}); |
| 212 | + |
| 213 | +// ── C: the validator, over the bytes now served ───────────────────────────── |
| 214 | + |
| 215 | +describe('#25785 C — a warm reopen is still answered 304', () => { |
| 216 | + it('the validator hashes the served body, and naming it answers 304', async () => { |
| 217 | + const service = makeService({ en: {}, 'zh-CN': zhTree() }); |
| 218 | + const first = await read(service); |
| 219 | + expect(first.response.headers.ETag).toBe(validatorOf(first.response.body)); |
| 220 | + |
| 221 | + const again = await read(service, '/translations/zh-CN', {}, member({ 'if-none-match': first.response.headers.ETag })); |
| 222 | + expect(again.response.status).toBe(304); |
| 223 | + expect(again.response.body).toBeUndefined(); |
| 224 | + }); |
| 225 | + |
| 226 | + it('a change confined to an unserved group serves the same bytes, so the validator holds', async () => { |
| 227 | + const bundles: Bundles = { en: {}, 'zh-CN': zhTree() }; |
| 228 | + const service = makeService(bundles); |
| 229 | + const before = (await read(service)).response.headers.ETag; |
| 230 | + |
| 231 | + bundles['zh-CN'] = { ...SERVED_GROUPS, metadataForms: { dashboard: { label: '看板' } } }; |
| 232 | + expect((await read(service)).response.headers.ETag).toBe(before); |
| 233 | + |
| 234 | + bundles['zh-CN'] = { ...SERVED_GROUPS, messages: { save: '存储' }, metadataForms: METADATA_FORMS }; |
| 235 | + expect((await read(service)).response.headers.ETag).not.toBe(before); |
| 236 | + }); |
| 237 | +}); |
0 commit comments