Skip to content

Commit 706edca

Browse files
committed
fix(rest)!: the CSV export writes a text cell in a form its consumer reads as text; the CSV import reverses it (#25078)
The CSV writer marks a text cell its consumer would interpret, by one rule defined once in export-format.ts and keyed on the field's declared type; the CSV import parse removes exactly that mark, so an export to import round trip through the sync, async-job and admin user import doors returns the stored value. xlsx, json and the json import door are unchanged. Claude-Session: https://claude.ai/code/session_01LmjU2x1faLZ39DVTFyVca6 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 03966ce commit 706edca

7 files changed

Lines changed: 755 additions & 10 deletions

File tree

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#25078] Export → admin user import round trip, through the CSV text-cell rule.
5+
*
6+
* `@objectstack/rest`'s CSV export writes a text cell its consumer would
7+
* interpret in a form that consumer reads as text, and its CSV import parse
8+
* (`parseCsvToRows`, reached through `prepareImportRequest`) reverses exactly
9+
* that. `POST /api/v1/auth/admin/import-users` parses a `csv` body through that
10+
* same `prepareImportRequest`, so a user list exported as CSV and imported back
11+
* here must hand better-auth's `createUser` every stored name exactly.
12+
*
13+
* The file is produced by the REAL export route of `@objectstack/rest`'s
14+
* `RestServer` over a protocol double that serves a two-field `sys_user` schema
15+
* and the rows below; the import is the real `runAdminImportUsers`. The rule
16+
* itself is pinned at its readers in `@objectstack/rest`
17+
* (`csv-text-cell.test.ts`), and the other CSV doors in its
18+
* `csv-text-cell-round-trip.test.ts`.
19+
*/
20+
21+
import { describe, it, expect, vi } from 'vitest';
22+
import { assertEngineUpdateDispatch } from '@objectstack/objectql';
23+
import { RestServer } from '@objectstack/rest';
24+
import { runAdminImportUsers, type IdentityImportDeps } from './admin-import-users.js';
25+
import type { AdminActor } from './admin-user-endpoints.js';
26+
27+
const ACTOR: AdminActor = { id: 'admin-1', email: 'admin@example.com' };
28+
29+
/** Plain words after a trigger character: marked by the export. */
30+
const MARKED = ['=Total', '+Name', '-Note', '@acme'];
31+
/** Ordinary business values, and a user-authored name that begins with the mark itself. */
32+
const UNMARKED = ['+86 138 0013 8000', '+1 555 010 0000', '-120.50', 'Acme Ltd', '120.50', "'Quoted"];
33+
const NAMES = [...MARKED, ...UNMARKED];
34+
35+
const SYS_USER_SCHEMA = {
36+
name: 'sys_user',
37+
fields: {
38+
email: { name: 'email', type: 'email' },
39+
name: { name: 'name', type: 'text' },
40+
},
41+
};
42+
43+
async function exportUsersCsv(rows: Array<Record<string, string>>): Promise<string> {
44+
const noop = () => {};
45+
const server = { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} };
46+
const protocol = {
47+
getMetaItem: vi.fn(async () => ({ type: 'object', name: 'sys_user', item: SYS_USER_SCHEMA })),
48+
findData: vi.fn(async () => ({ object: 'sys_user', records: rows, total: rows.length })),
49+
};
50+
const rest = new RestServer(server as any, protocol as any, { api: { requireAuth: false } } as any);
51+
(rest as any).resolveExecCtx = async () => ({ userId: ACTOR.id });
52+
rest.registerRoutes();
53+
const route: any = rest.getRoutes().find(
54+
(r: any) => r.method === 'GET' && r.path === '/api/v1/data/:object/export',
55+
);
56+
expect(route).toBeDefined();
57+
const chunks: string[] = [];
58+
const res: any = {
59+
write: (s: unknown) => { chunks.push(String(s)); return true; },
60+
end: () => {},
61+
header: () => res,
62+
status: () => res,
63+
json: () => res,
64+
};
65+
await route.handler({ params: { object: 'sys_user' }, query: { format: 'csv' } }, res);
66+
return chunks.join('');
67+
}
68+
69+
function makeDeps() {
70+
let nextId = 1;
71+
const createUser = vi.fn(async ({ body }: any) => ({ user: { id: `u-${nextId++}`, email: body.email, name: body.name } }));
72+
const update = vi.fn(async (_obj: string, data: any, options?: any) => {
73+
assertEngineUpdateDispatch(data, options);
74+
return {};
75+
});
76+
const deps: IdentityImportDeps = {
77+
getAuthApi: async () => ({ createUser, requestPasswordReset: vi.fn(async () => ({ status: true })) }),
78+
getDataEngine: () => ({ find: vi.fn(async () => []), update, insert: vi.fn(async () => ({})) }),
79+
phoneNumberEnabled: () => false,
80+
emailServiceAvailable: () => false,
81+
smsInviteAvailable: () => false,
82+
sendInviteSms: vi.fn(async () => {}),
83+
noteMustChangePasswordIssued: vi.fn(),
84+
logger: { warn: vi.fn() },
85+
};
86+
return { deps, createUser };
87+
}
88+
89+
function makeRequest(body: unknown): Request {
90+
return new Request('http://localhost/api/v1/auth/admin/import-users', {
91+
method: 'POST',
92+
headers: { 'content-type': 'application/json' },
93+
body: JSON.stringify(body),
94+
});
95+
}
96+
97+
describe('admin user import — CSV export → import round trip (#25078)', () => {
98+
it('hands createUser every exported name exactly', async () => {
99+
const rows = NAMES.map((name, i) => ({ email: `user${i + 1}@example.com`, name }));
100+
const csv = await exportUsersCsv(rows);
101+
102+
// The file carried the marks, so the round trip below is not a pass-through.
103+
expect(csv.split('\r\n')[0]).toBe('email,name');
104+
for (const [i, v] of MARKED.entries()) expect(csv).toContain(`user${i + 1}@example.com,'${v}\r\n`);
105+
expect(csv).toContain(',+86 138 0013 8000\r\n');
106+
expect(csv).toContain(",'Quoted\r\n");
107+
108+
const m = makeDeps();
109+
const res = await runAdminImportUsers(m.deps, makeRequest({ passwordPolicy: 'temporary', csv }), ACTOR);
110+
expect(res.status).toBe(200);
111+
expect((res.body.data as any).summary.created).toBe(NAMES.length);
112+
const byEmail = new Map(m.createUser.mock.calls.map((c: any[]) => [c[0].body.email, c[0].body.name]));
113+
expect(rows.map((r) => byEmail.get(r.email))).toEqual(NAMES);
114+
});
115+
});
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
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

Comments
 (0)