|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#25078] Export → import round trip through each REST door that parses CSV. |
| 5 | + * |
| 6 | + * The CSV export writes a text cell its consumer would interpret in a form that |
| 7 | + * consumer reads as text; the CSV import parse reverses exactly that. The rule |
| 8 | + * is pinned at its readers in `csv-text-cell.test.ts`. This file drives the |
| 9 | + * REAL routes over a REAL `ObjectQL` engine with a better-sqlite3 `:memory:` |
| 10 | + * driver: rows are stored in `note`, exported as CSV through |
| 11 | + * `GET /data/note/export`, and that file is imported into `note_copy`'s text |
| 12 | + * fields through |
| 13 | + * |
| 14 | + * - the sync door, `POST /data/note_copy/import`, with an inline mapping; |
| 15 | + * - the sync door with a NAMED mapping, whose rows keep their source headers |
| 16 | + * until core's `applyMappingToRows` — the reversal must not depend on a |
| 17 | + * target field's type; |
| 18 | + * - the async door, `POST /data/note_copy/import/jobs`. |
| 19 | + * |
| 20 | + * Every stored value comes back exactly. Each case also asserts that the file |
| 21 | + * it imported carried the marks, so the round trip cannot pass by the export |
| 22 | + * never having marked anything. plugin-auth's admin user import is pinned in |
| 23 | + * its own package (`admin-import-users-csv-text-cell.test.ts`). |
| 24 | + * |
| 25 | + * Control characters are written as escapes in this file, never as raw bytes. |
| 26 | + */ |
| 27 | + |
| 28 | +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; |
| 29 | +import { ObjectQL } from '@objectstack/objectql'; |
| 30 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 31 | +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; |
| 32 | +import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject, SysMetadataObject } from '@objectstack/metadata-core'; |
| 33 | +import { SysImportJob } from '@objectstack/platform-objects/audit'; |
| 34 | +import { RestServer } from './rest-server'; |
| 35 | + |
| 36 | +const liveEngines: ObjectQL[] = []; |
| 37 | +afterEach(async () => { |
| 38 | + while (liveEngines.length) { |
| 39 | + try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } |
| 40 | + } |
| 41 | +}); |
| 42 | + |
| 43 | +/** |
| 44 | + * Text fields only, so every value lands in a text field. `memo`'s label starts |
| 45 | + * with a trigger character, so the header row carries a marked label too. |
| 46 | + */ |
| 47 | +function noteObject(name: string) { |
| 48 | + return { |
| 49 | + name, |
| 50 | + label: name, |
| 51 | + systemFields: false, |
| 52 | + fields: { |
| 53 | + id: { name: 'id', type: 'text' as const, primaryKey: true, label: 'ID' }, |
| 54 | + body: { name: 'body', type: 'text' as const, label: 'Body' }, |
| 55 | + memo: { name: 'memo', type: 'text' as const, label: '-Memo' }, |
| 56 | + }, |
| 57 | + }; |
| 58 | +} |
| 59 | + |
| 60 | +/** Plain words after a trigger character: marked by the export. */ |
| 61 | +const MARKED = ['=Total', '+Name', '-Note', '@acme']; |
| 62 | +/** Ordinary business values, and a user-authored cell that begins with the mark itself. */ |
| 63 | +const UNMARKED = ['+86 138 0013 8000', '+1 555 010 0000', '-120.50', 'Acme Ltd', '120.50', "'Quoted"]; |
| 64 | +const VALUES = [...MARKED, ...UNMARKED]; |
| 65 | + |
| 66 | +const INLINE_MAPPING = { ID: 'id', Body: 'body', '-Memo': 'memo' }; |
| 67 | + |
| 68 | +function createMockServer() { |
| 69 | + const noop = () => {}; |
| 70 | + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; |
| 71 | +} |
| 72 | + |
| 73 | +function makeRes() { |
| 74 | + const chunks: string[] = []; |
| 75 | + const res: any = { |
| 76 | + write: (s: string) => { chunks.push(typeof s === 'string' ? s : String(s)); return true; }, |
| 77 | + end: () => {}, |
| 78 | + header: () => res, |
| 79 | + status: (code: number) => { res._status = code; return res; }, |
| 80 | + json: (body: any) => { res._json = body; return res; }, |
| 81 | + }; |
| 82 | + return { res, text: () => chunks.join('') }; |
| 83 | +} |
| 84 | + |
| 85 | +async function boot(values: string[]) { |
| 86 | + const engine = new ObjectQL(); |
| 87 | + liveEngines.push(engine); |
| 88 | + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true); |
| 89 | + await engine.init(); |
| 90 | + engine.registry.registerObject(noteObject('note') as any); |
| 91 | + engine.registry.registerObject(noteObject('note_copy') as any); |
| 92 | + engine.registry.registerObject(SysImportJob as any); |
| 93 | + await engine.syncSchemas(); |
| 94 | + for (let i = 0; i < values.length; i++) { |
| 95 | + await engine.insert('note', { id: `r${i + 1}`, body: values[i], memo: values[i] }); |
| 96 | + } |
| 97 | + for (const o of [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { |
| 98 | + if (!engine.registry.getObject(o.name)) engine.registry.registerObject(o as any); |
| 99 | + } |
| 100 | + engine.registry.registerItem('mapping', { |
| 101 | + name: 'note_copy_feed', |
| 102 | + label: 'Note copy feed', |
| 103 | + sourceFormat: 'csv', |
| 104 | + targetObject: 'note_copy', |
| 105 | + fieldMapping: [ |
| 106 | + { source: 'ID', target: 'id', transform: 'none' }, |
| 107 | + { source: 'Body', target: 'body', transform: 'none' }, |
| 108 | + { source: '-Memo', target: 'memo', transform: 'none' }, |
| 109 | + ], |
| 110 | + } as any, 'name'); |
| 111 | + const protocol = new ObjectStackProtocolImplementation(engine as any); |
| 112 | + const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); |
| 113 | + (rest as any).resolveExecCtx = async () => ({ userId: 'test-user' }); |
| 114 | + rest.registerRoutes(); |
| 115 | + const routes = rest.getRoutes(); |
| 116 | + const find = (method: string, path: string) => routes.find((r: any) => r.method === method && r.path === path)!; |
| 117 | + return { |
| 118 | + engine, |
| 119 | + exportRoute: find('GET', '/api/v1/data/:object/export'), |
| 120 | + importRoute: find('POST', '/api/v1/data/:object/import'), |
| 121 | + jobCreate: find('POST', '/api/v1/data/:object/import/jobs'), |
| 122 | + jobProgress: find('GET', '/api/v1/data/import/jobs/:jobId'), |
| 123 | + }; |
| 124 | +} |
| 125 | + |
| 126 | +type Booted = Awaited<ReturnType<typeof boot>>; |
| 127 | + |
| 128 | +async function exportCsv(ctx: Booted): Promise<string> { |
| 129 | + const { res, text } = makeRes(); |
| 130 | + await ctx.exportRoute.handler({ params: { object: 'note' }, query: { format: 'csv' } } as any, res); |
| 131 | + return text(); |
| 132 | +} |
| 133 | + |
| 134 | +async function importSync(ctx: Booted, body: Record<string, unknown>): Promise<any> { |
| 135 | + const { res } = makeRes(); |
| 136 | + await ctx.importRoute.handler({ params: { object: 'note_copy' }, body } as any, res); |
| 137 | + return res._json; |
| 138 | +} |
| 139 | + |
| 140 | +async function importAsync(ctx: Booted, body: Record<string, unknown>): Promise<any> { |
| 141 | + const { res } = makeRes(); |
| 142 | + await ctx.jobCreate.handler({ params: { object: 'note_copy' }, body } as any, res); |
| 143 | + expect(res._status).toBe(201); |
| 144 | + const jobId = res._json.jobId; |
| 145 | + for (let i = 0; i < 200; i++) { |
| 146 | + const p = makeRes(); |
| 147 | + await ctx.jobProgress.handler({ params: { jobId }, query: {} } as any, p.res); |
| 148 | + const status = p.res._json?.status; |
| 149 | + if (status === 'succeeded' || status === 'failed' || status === 'cancelled') return p.res._json; |
| 150 | + await new Promise((r) => setTimeout(r, 5)); |
| 151 | + } |
| 152 | + throw new Error(`import job ${jobId} did not finish`); |
| 153 | +} |
| 154 | + |
| 155 | +async function storedCopies(ctx: Booted, count: number): Promise<Array<{ body: unknown; memo: unknown }>> { |
| 156 | + const out: Array<{ body: unknown; memo: unknown }> = []; |
| 157 | + for (let i = 1; i <= count; i++) { |
| 158 | + const row: any = await ctx.engine.findOne('note_copy', { where: { id: `r${i}` } }); |
| 159 | + out.push({ body: row?.body, memo: row?.memo }); |
| 160 | + } |
| 161 | + return out; |
| 162 | +} |
| 163 | + |
| 164 | +/** The file carried the marks: the round trip below is not a pass-through. */ |
| 165 | +function expectMarkedFile(csv: string): void { |
| 166 | + expect(csv.split('\r\n')[0]).toBe("ID,Body,'-Memo"); |
| 167 | + for (const v of MARKED) expect(csv).toContain(`,'${v},'${v}\r\n`); |
| 168 | + for (const v of ['+86 138 0013 8000', '-120.50', 'Acme Ltd']) expect(csv).toContain(`,${v},${v}\r\n`); |
| 169 | +} |
| 170 | + |
| 171 | +describe('CSV export → import round trip, every value returns exactly (#25078)', () => { |
| 172 | + let ctx: Booted; |
| 173 | + beforeEach(async () => { |
| 174 | + ctx = await boot(VALUES); |
| 175 | + }); |
| 176 | + |
| 177 | + it('sync door, inline mapping', async () => { |
| 178 | + const csv = await exportCsv(ctx); |
| 179 | + expectMarkedFile(csv); |
| 180 | + const res = await importSync(ctx, { format: 'csv', csv, mapping: INLINE_MAPPING }); |
| 181 | + expect(res).toMatchObject({ total: VALUES.length, ok: VALUES.length, errors: 0, created: VALUES.length }); |
| 182 | + expect(await storedCopies(ctx, VALUES.length)).toEqual(VALUES.map((v) => ({ body: v, memo: v }))); |
| 183 | + }); |
| 184 | + |
| 185 | + it('sync door, named mapping (reversal runs before the mapping renames the columns)', async () => { |
| 186 | + const csv = await exportCsv(ctx); |
| 187 | + expectMarkedFile(csv); |
| 188 | + const res = await importSync(ctx, { format: 'csv', csv, mappingName: 'note_copy_feed' }); |
| 189 | + expect(res).toMatchObject({ total: VALUES.length, ok: VALUES.length, errors: 0, created: VALUES.length }); |
| 190 | + expect(await storedCopies(ctx, VALUES.length)).toEqual(VALUES.map((v) => ({ body: v, memo: v }))); |
| 191 | + }); |
| 192 | + |
| 193 | + it('async import-job door', async () => { |
| 194 | + const csv = await exportCsv(ctx); |
| 195 | + expectMarkedFile(csv); |
| 196 | + const done = await importAsync(ctx, { format: 'csv', csv, mapping: INLINE_MAPPING }); |
| 197 | + expect(done).toMatchObject({ status: 'succeeded', total: VALUES.length, created: VALUES.length, errors: 0 }); |
| 198 | + expect(await storedCopies(ctx, VALUES.length)).toEqual(VALUES.map((v) => ({ body: v, memo: v }))); |
| 199 | + }); |
| 200 | +}); |
| 201 | + |
| 202 | +describe('CSV round trip of a value that begins with TAB or CR (#25078)', () => { |
| 203 | + const LEADING_WHITESPACE = ['\tTotal', '\rTotal']; |
| 204 | + let ctx: Booted; |
| 205 | + beforeEach(async () => { |
| 206 | + ctx = await boot(LEADING_WHITESPACE); |
| 207 | + }); |
| 208 | + |
| 209 | + it('the file carries the mark, and `trimWhitespace: false` returns the stored value exactly', async () => { |
| 210 | + const csv = await exportCsv(ctx); |
| 211 | + expect(csv).toContain("r1,'\tTotal,'\tTotal\r\n"); |
| 212 | + expect(csv).toContain(`r2,"'\rTotal","'\rTotal"\r\n`); |
| 213 | + const res = await importSync(ctx, { format: 'csv', csv, mapping: INLINE_MAPPING, trimWhitespace: false }); |
| 214 | + expect(res).toMatchObject({ ok: 2, errors: 0 }); |
| 215 | + expect(await storedCopies(ctx, 2)).toEqual(LEADING_WHITESPACE.map((v) => ({ body: v, memo: v }))); |
| 216 | + }); |
| 217 | + |
| 218 | + it("under the default `trimWhitespace`, core's text trim still removes the leading TAB / CR after the reversal", async () => { |
| 219 | + const csv = await exportCsv(ctx); |
| 220 | + const res = await importSync(ctx, { format: 'csv', csv, mapping: INLINE_MAPPING }); |
| 221 | + expect(res).toMatchObject({ ok: 2, errors: 0 }); |
| 222 | + expect(await storedCopies(ctx, 2)).toEqual([{ body: 'Total', memo: 'Total' }, { body: 'Total', memo: 'Total' }]); |
| 223 | + }); |
| 224 | +}); |
0 commit comments