@openpeepshq/rn-components 0.20.0 → 0.22.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.
@@ -0,0 +1,281 @@
1
+ import { readdirSync, readFileSync } from 'fs';
2
+ import { join } from 'path';
3
+
4
+ /**
5
+ * Regression guard for the glob 9/10 -> 14.0.6 override (GHSA-3g3m-2fjr-6pw4,
6
+ * issue #2255).
7
+ *
8
+ * babel-plugin-module-resolver reads glob through
9
+ * `interopRequireDefault(require('glob')).default`. glob >= 10 (CJS) sets
10
+ * `__esModule: true` but exports no `default`, so the plugin's
11
+ * `normalizeRoot` (its `glob.default.hasMagic` / `glob.default.sync` calls)
12
+ * throws `Cannot read properties of undefined` whenever module-resolver is
13
+ * configured with a `root` option. The 14.0.6 override therefore makes a
14
+ * module-resolver `root` option a hard crash. No first-party babel / metro /
15
+ * bob config may pass `root` to that plugin, so this guard scans every such
16
+ * config and fails the suite if any of them does.
17
+ *
18
+ * It intentionally does NOT evaluate the configs (they require their runtime
19
+ * deps); it is a static source check. Detection is name-based, not
20
+ * resolver-based: both the quoted (`'root'` / `"root"`) and unquoted
21
+ * spellings of a top-level `root` key are handled, but only the textual
22
+ * plugin-reference-followed-by-options shape is detectable — a `root`
23
+ * passed through a variable or computed key would not be flagged.
24
+ *
25
+ * Name coverage: `babel.config.*`, `.babelrc*`, `metro.config.*`, and
26
+ * `metro.js` (the plain-JS Metro filename used in-repo by
27
+ * `platform/rn-components`) are all matched. `bob.config.*` currently
28
+ * matches no file — bob 0.35.2 reads its config from the `package.json`
29
+ * `bob` field — so that pattern is a placeholder, not a live detection.
30
+ */
31
+
32
+ const REPO_ROOT = join(__dirname, '..', '..', '..', '..');
33
+
34
+ const SKIP_DIRS = new Set([
35
+ 'node_modules',
36
+ '.git',
37
+ 'dist',
38
+ 'lib',
39
+ 'build',
40
+ 'coverage',
41
+ '.next',
42
+ '.turbo',
43
+ 'android',
44
+ 'ios',
45
+ ]);
46
+
47
+ function isConfigName(name: string): boolean {
48
+ return (
49
+ name.startsWith('babel.config.') ||
50
+ name === '.babelrc' ||
51
+ name.startsWith('.babelrc.') ||
52
+ name.startsWith('metro.config.') ||
53
+ name === 'metro.js' ||
54
+ name.startsWith('bob.config.')
55
+ );
56
+ }
57
+
58
+ function collectConfigFiles(dir: string, found: string[]): void {
59
+ let entries;
60
+ try {
61
+ entries = readdirSync(dir, { withFileTypes: true });
62
+ } catch {
63
+ return;
64
+ }
65
+ for (const entry of entries) {
66
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
67
+ // Do not follow symlinked dependency stores (pnpm).
68
+ if (entry.isSymbolicLink()) continue;
69
+ const p = join(dir, entry.name);
70
+ if (entry.isDirectory()) {
71
+ if (!SKIP_DIRS.has(entry.name)) collectConfigFiles(p, found);
72
+ } else if (entry.isFile() && isConfigName(entry.name)) {
73
+ found.push(p);
74
+ }
75
+ }
76
+ }
77
+
78
+ /** Strip /* ... *\/ and // ... line comments so they can't match as code. */
79
+ function stripComments(src: string): string {
80
+ return src
81
+ .replace(/\/\*[\s\S]*?\*\//g, '')
82
+ .replace(/(^|[^:\\])\/\/[^\n]*/g, '$1');
83
+ }
84
+
85
+ /**
86
+ * Matches a module-resolver plugin reference, with or without a
87
+ * require / require.resolve wrapper, e.g. `'module-resolver'`,
88
+ * `"babel-plugin-module-resolver"`, or
89
+ * `require.resolve('babel-plugin-module-resolver')`.
90
+ */
91
+ const PLUGIN_REF =
92
+ /(?:require\(\s*['"]|require\.resolve\(\s*['"])?(?:@?[\w.-]+\/)?(?:babel-plugin-)?module-resolver['"]?\s*\)?/g;
93
+
94
+ /** Return the balanced `{...}` options object that immediately follows a
95
+ * plugin reference (the `,{ ... }` after it), or null if there is none. */
96
+ function extractFollowingOptions(code: string, refEnd: number): string | null {
97
+ const after = code.slice(refEnd);
98
+ const comma = after.indexOf(',');
99
+ if (comma === -1) return null;
100
+ const seg = after.slice(comma + 1);
101
+ const braceIdx = seg.indexOf('{');
102
+ if (braceIdx === -1) return null;
103
+ if (!/^\s*$/.test(seg.slice(0, braceIdx))) return null;
104
+ const openIdx = comma + 1 + braceIdx;
105
+ let depth = 0;
106
+ for (let i = openIdx; i < after.length; i++) {
107
+ if (after[i] === '{') depth++;
108
+ else if (after[i] === '}') {
109
+ depth--;
110
+ if (depth === 0) return after.slice(openIdx, i + 1);
111
+ }
112
+ }
113
+ return null;
114
+ }
115
+
116
+ /**
117
+ * True if a top-level (depth 0) `root` key starts at `inner[i]` — the
118
+ * unquoted or the quoted (`'root'` / `"root"`) spelling, in the colon form
119
+ * (`root: …` / `"root": …`) or the unquoted shorthand form (`root,` /
120
+ * `root }` / end). A key position is one whose previous non-whitespace
121
+ * character is `{` or `,` (or the start of the body) — so a *value* named
122
+ * `root` (after `:`) is never matched.
123
+ */
124
+ function isRootKeyAt(inner: string, i: number): boolean {
125
+ let isKeyStart = true;
126
+ for (let j = i - 1; j >= 0; j--) {
127
+ const ch = inner[j];
128
+ if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') continue;
129
+ isKeyStart = ch === '{' || ch === ',';
130
+ break;
131
+ }
132
+ if (!isKeyStart) return false;
133
+ const c = inner[i];
134
+ let end: number;
135
+ if (c === '"' || c === "'") {
136
+ if (!inner.startsWith(c + 'root' + c, i)) return false;
137
+ end = i + 6; // quote + "root" + quote
138
+ } else {
139
+ if (c !== 'r' || !inner.startsWith('root', i)) return false;
140
+ end = i + 4;
141
+ }
142
+ const rest = inner.slice(end);
143
+ return /^\s*:/.test(rest) || /^\s*[,}]/.test(rest) || /^\s*$/.test(rest);
144
+ }
145
+
146
+ /**
147
+ * True if `obj` (a `{...}` literal) has a top-level (depth 0) `root` key —
148
+ * the colon form `{ root: ... }`, the quoted-key form `{ "root": ... }`
149
+ * (as in a JSON `.babelrc`), or the shorthand `{ root }`. Nested
150
+ * occurrences (e.g. `alias: { root: ... }`) do not count.
151
+ */
152
+ function hasTopLevelRoot(obj: string): boolean {
153
+ const inner = obj.slice(1, obj.length - 1);
154
+ let depth = 0;
155
+ let inStr: string | null = null;
156
+ for (let i = 0; i < inner.length; i++) {
157
+ const c = inner[i];
158
+ if (inStr) {
159
+ if (c === '\\') i++;
160
+ else if (c === inStr) inStr = null;
161
+ continue;
162
+ }
163
+ if (
164
+ depth === 0 &&
165
+ (c === 'r' || c === '"' || c === "'") &&
166
+ isRootKeyAt(inner, i)
167
+ ) {
168
+ return true;
169
+ }
170
+ if (c === '"' || c === "'" || c === '`') {
171
+ inStr = c;
172
+ continue;
173
+ }
174
+ if (c === '{' || c === '[') {
175
+ depth++;
176
+ continue;
177
+ }
178
+ if (c === '}' || c === ']') {
179
+ depth--;
180
+ continue;
181
+ }
182
+ }
183
+ return false;
184
+ }
185
+
186
+ function moduleResolverHasRoot(code: string): boolean {
187
+ PLUGIN_REF.lastIndex = 0;
188
+ let m: RegExpExecArray | null;
189
+ while ((m = PLUGIN_REF.exec(code)) !== null) {
190
+ const options = extractFollowingOptions(code, m.index + m[0].length);
191
+ if (options && hasTopLevelRoot(options)) return true;
192
+ if (m[0].length === 0) PLUGIN_REF.lastIndex++;
193
+ }
194
+ return false;
195
+ }
196
+
197
+ describe('module-resolver `root` regression guard (#2255 glob 14.0.6)', () => {
198
+ it('discovers at least one first-party babel/metro/bob config (guard is active)', () => {
199
+ const configs: string[] = [];
200
+ collectConfigFiles(REPO_ROOT, configs);
201
+ expect(configs.length).toBeGreaterThan(0);
202
+ });
203
+
204
+ it('no first-party babel/metro/bob config passes `root` to module-resolver', () => {
205
+ const configs: string[] = [];
206
+ collectConfigFiles(REPO_ROOT, configs);
207
+ const violations = configs.filter((file) => {
208
+ const src = readFileSync(file, 'utf8');
209
+ return moduleResolverHasRoot(stripComments(src));
210
+ });
211
+ expect(violations).toEqual([]);
212
+ });
213
+ });
214
+
215
+ describe('module-resolver `root` guard: scanner unit checks', () => {
216
+ it('flags a top-level `root` key on a module-resolver options object', () => {
217
+ const code = `plugins: [['module-resolver', { root: ['./src'], alias: { x: 'y' } }]]`;
218
+ expect(moduleResolverHasRoot(stripComments(code))).toBe(true);
219
+ });
220
+
221
+ it('flags the require.resolve-wrapped reference with `root`', () => {
222
+ const code = `plugins: [[require.resolve('babel-plugin-module-resolver'), { root: ['.'] }]]`;
223
+ expect(moduleResolverHasRoot(stripComments(code))).toBe(true);
224
+ });
225
+
226
+ it('flags a single-quoted `root` key on a module-resolver options object', () => {
227
+ const code = `plugins: [['module-resolver', { 'root': ['./src'], alias: { x: 'y' } }]]`;
228
+ expect(moduleResolverHasRoot(stripComments(code))).toBe(true);
229
+ });
230
+
231
+ it('flags a double-quoted (JSON .babelrc) `root` key on a module-resolver options object', () => {
232
+ const code = `plugins: [["module-resolver", { "root": "./src" }]]`;
233
+ expect(moduleResolverHasRoot(stripComments(code))).toBe(true);
234
+ });
235
+
236
+ it('does not flag a module-resolver reference without `root`', () => {
237
+ const code = `plugins: [['babel-plugin-module-resolver', { alias: { x: 'y' } }]]`;
238
+ expect(moduleResolverHasRoot(stripComments(code))).toBe(false);
239
+ });
240
+
241
+ it('does not flag a value named `root` (a key, not a value)', () => {
242
+ const code = `plugins: [['module-resolver', { x: 'root', alias: { x: 'y' } }]]`;
243
+ expect(moduleResolverHasRoot(stripComments(code))).toBe(false);
244
+ });
245
+
246
+ it('does not flag a nested `root` (e.g. under `alias`)', () => {
247
+ const code = `plugins: [['module-resolver', { alias: { root: './src' } }]]`;
248
+ expect(moduleResolverHasRoot(stripComments(code))).toBe(false);
249
+ });
250
+
251
+ it('does not flag a module-resolver mention in a comment', () => {
252
+ const code = `// module-resolver root: do not use\nplugins: []`;
253
+ expect(moduleResolverHasRoot(stripComments(code))).toBe(false);
254
+ });
255
+
256
+ it('isConfigName: accepts the plain-JS `metro.js` filename, rejects near-misses', () => {
257
+ expect(isConfigName('metro.js')).toBe(true);
258
+ expect(isConfigName('metro.config.js')).toBe(true);
259
+ expect(isConfigName('babel.config.cjs')).toBe(true);
260
+ expect(isConfigName('bob.config.js')).toBe(true);
261
+ expect(isConfigName('metro.js.map')).toBe(false);
262
+ expect(isConfigName('x-metro.js')).toBe(false);
263
+ });
264
+
265
+ it('stripComments: drops `// module-resolver root: …` comment text', () => {
266
+ const out = stripComments(
267
+ "plugins: [] // module-resolver root: './src' would crash under glob 14\nx = 1"
268
+ );
269
+ expect(out).not.toContain('module-resolver');
270
+ expect(out).not.toContain('would crash');
271
+ expect(out).toContain('plugins: []');
272
+ expect(out).toContain('x = 1');
273
+ });
274
+
275
+ it('stripComments: does not truncate URL-ish values (`//` after `:` or `\\`)', () => {
276
+ const url = "url = 'https://openpeeps.org/docs/glob';";
277
+ expect(stripComments(url)).toBe(url);
278
+ const winPath = "root = 'c:\\//share';";
279
+ expect(stripComments(winPath)).toBe(winPath);
280
+ });
281
+ });
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Regression tests for the RN account export flow (issue #237 round-8
3
+ * review S1/S3). The page hands the shared `useAccountExport` hook an
4
+ * external `downloadDocument` step; a failed, expired, or handed-off-failed
5
+ * export must not be silent on RN — the hook's `status` has to surface as a
6
+ * toast, and the handoff must receive the resolved download URL.
7
+ *
8
+ * The hook under test is the real react-package implementation (required
9
+ * directly in the `@openpeepshq/react` mock, so the ESM-only transitive deps
10
+ * of the react barrel stay out of Jest's runtime).
11
+ */
12
+
13
+ const React = require('react');
14
+ const ReactTestRenderer = require('react-test-renderer');
15
+
16
+ // Fake export job client. The status queue mirrors the react-package test:
17
+ // each poll pops the next payload, the last repeats when exhausted.
18
+ const start = jest.fn(async () => ({ data: { jobId: 'job-1' } }));
19
+ const status = jest.fn();
20
+ const downloadUrl = jest.fn(async () => 'https://x/export?token=tok');
21
+ const statusResults: Array<Record<string, unknown>> = [];
22
+ const downloadDocument = jest.fn();
23
+ const toastShow = jest.fn();
24
+
25
+ jest.mock('react-native', () => ({
26
+ View: (props: { children?: unknown }) =>
27
+ React.createElement('View', null, props.children),
28
+ ActivityIndicator: () => null,
29
+ Linking: {
30
+ canOpenURL: jest.fn(async () => true),
31
+ openURL: jest.fn(async () => undefined),
32
+ },
33
+ }));
34
+
35
+ jest.mock('react-i18next', () => ({
36
+ useTranslation: () => ({
37
+ t: (key: string, opts?: { defaultValue?: string }) =>
38
+ opts?.defaultValue ?? key,
39
+ }),
40
+ }));
41
+
42
+ jest.mock('react-native-keyboard-aware-scroll-view', () => ({
43
+ KeyboardAwareScrollView: (props: { children?: unknown }) =>
44
+ React.createElement('KeyboardAwareScrollView', null, props.children),
45
+ }));
46
+
47
+ jest.mock('react-native-toast-message', () => ({
48
+ __esModule: true,
49
+ default: { show: toastShow },
50
+ }));
51
+
52
+ jest.mock('@openpeepshq/react', () => ({
53
+ useOpenpeeps: () => ({
54
+ openpeepsApi: {
55
+ useCurrentAccount: () => ({ data: undefined }),
56
+ logoutAction: jest.fn(),
57
+ updateCurrentAccountAction: jest.fn(),
58
+ validationEmailAction: jest.fn(),
59
+ },
60
+ queryClient: { invalidateQueries: jest.fn() },
61
+ client: {
62
+ accounts: {
63
+ current: {
64
+ export: {
65
+ start: () => start(),
66
+ status: (opts: unknown) => {
67
+ status(opts);
68
+ const next = statusResults.shift() ?? statusResults[0];
69
+ return Promise.resolve(next ? { data: next } : undefined);
70
+ },
71
+ downloadUrl: (token: string) => downloadUrl(token),
72
+ },
73
+ },
74
+ },
75
+ },
76
+ }),
77
+ // Real hook, straight from the react package source.
78
+ useAccountExport:
79
+ require('../../../../react/src/hooks/settings/useAccountExport')
80
+ .useAccountExport,
81
+ }));
82
+
83
+ jest.mock('@openpeepshq/common', () => ({
84
+ Account: 'Account',
85
+ }));
86
+
87
+ jest.mock('react-hook-form', () => ({
88
+ useForm: () => ({
89
+ getValues: () => ({
90
+ email: 'a@b.c',
91
+ oldPassword: '',
92
+ newPassword: undefined,
93
+ confirmPassword: undefined,
94
+ }),
95
+ setValue: jest.fn(),
96
+ control: {},
97
+ }),
98
+ }));
99
+
100
+ jest.mock('../../lib/downloadFile', () => ({
101
+ downloadDocument,
102
+ }));
103
+
104
+ jest.mock('../../components/ui/themed-view', () => ({
105
+ ThemedView: (props: { children?: unknown }) =>
106
+ React.createElement('ThemedView', null, props.children),
107
+ }));
108
+
109
+ jest.mock('../../components/ui/themed-text', () => ({
110
+ ThemedText: (props: { children?: unknown }) =>
111
+ React.createElement('ThemedText', null, props.children),
112
+ }));
113
+
114
+ jest.mock('../../components/ui/form', () => ({
115
+ Form: (props: { children?: unknown }) =>
116
+ React.createElement('Form', null, props.children),
117
+ FormField: (props: {
118
+ render?: (p: { field: { value: string } }) => unknown;
119
+ }) => (props.render ? props.render({ field: { value: '' } }) : null),
120
+ FormInput: () => null,
121
+ }));
122
+
123
+ jest.mock('../../components/ui/button', () => ({
124
+ Button: (props: Record<string, unknown>) =>
125
+ React.createElement('Button', props),
126
+ }));
127
+
128
+ jest.mock('../../components/layout', () => ({
129
+ HeaderActionButton: () => null,
130
+ useSetPageHeader: () => undefined,
131
+ }));
132
+
133
+ import { AccountSettings } from './Account';
134
+
135
+ type Instance = {
136
+ type?: unknown;
137
+ props?: Record<string, unknown>;
138
+ children?: Array<unknown>;
139
+ };
140
+
141
+ let tree: ReturnType<typeof ReactTestRenderer.create> | undefined;
142
+
143
+ const renderPage = () => {
144
+ ReactTestRenderer.act(() => {
145
+ tree = ReactTestRenderer.create(
146
+ React.createElement(AccountSettings, { navigation: {} } as never)
147
+ );
148
+ });
149
+ };
150
+
151
+ const advance = async (ms: number) => {
152
+ await ReactTestRenderer.act(async () => {
153
+ await jest.advanceTimersByTimeAsync(ms);
154
+ });
155
+ };
156
+
157
+ const toasts = () =>
158
+ toastShow.mock.calls.map((c: Array<Record<string, unknown>>) => c[0]);
159
+
160
+ const textCount = (text: string) =>
161
+ tree!.root.findAll(
162
+ (node: Instance) =>
163
+ node.type === 'ThemedText' && node.children?.includes(text)
164
+ ).length;
165
+
166
+ // The export button (not the email-verify one): the Button whose subtree
167
+ // carries the idle "Download" label.
168
+ const downloadButton = (): Instance => {
169
+ const buttons = tree!.root.findAll(
170
+ (node: Instance) =>
171
+ node.type === 'Button' && typeof node.props?.onPress === 'function'
172
+ ) as Array<
173
+ Instance & {
174
+ findAll: (pred: (n: Instance) => boolean) => Instance[];
175
+ }
176
+ >;
177
+ const btn = buttons.find(
178
+ (b) =>
179
+ b.findAll(
180
+ (n: Instance) =>
181
+ n.type === 'ThemedText' && n.children?.includes('Download')
182
+ ).length > 0
183
+ );
184
+ if (!btn) throw new Error('download button not found');
185
+ return btn;
186
+ };
187
+
188
+ beforeEach(() => {
189
+ (
190
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
191
+ ).IS_REACT_ACT_ENVIRONMENT = true;
192
+ jest.useFakeTimers();
193
+ start.mockClear();
194
+ status.mockClear();
195
+ downloadUrl.mockClear().mockResolvedValue('https://x/export?token=tok');
196
+ statusResults.length = 0;
197
+ downloadDocument.mockClear();
198
+ toastShow.mockClear();
199
+ tree = undefined;
200
+ });
201
+
202
+ afterEach(() => {
203
+ if (tree) {
204
+ ReactTestRenderer.act(() => {
205
+ tree!.unmount();
206
+ });
207
+ tree = undefined;
208
+ }
209
+ jest.useRealTimers();
210
+ });
211
+
212
+ describe('RN account export flow (issue #237 round-8 S1/S3)', () => {
213
+ it('hands the resolved download URL to the external handler', async () => {
214
+ statusResults.push(
215
+ { state: 'building' },
216
+ { state: 'ready', downloadToken: 'tok-1' }
217
+ );
218
+ downloadDocument.mockResolvedValue(true);
219
+ renderPage();
220
+
221
+ await ReactTestRenderer.act(async () => {
222
+ await downloadButton().props!.onPress!();
223
+ });
224
+
225
+ await advance(2001); // first poll: building
226
+ await advance(2001); // second poll: ready → hand off
227
+ expect(downloadUrl).toHaveBeenCalledWith('tok-1');
228
+ expect(downloadDocument).toHaveBeenCalledWith('https://x/export?token=tok');
229
+ expect(toasts()).toHaveLength(0);
230
+ });
231
+
232
+ it('toasts when the export job fails (status error)', async () => {
233
+ statusResults.push({ state: 'error', error: 'boom' });
234
+ renderPage();
235
+
236
+ await ReactTestRenderer.act(async () => {
237
+ await downloadButton().props!.onPress!();
238
+ });
239
+ await advance(2001);
240
+
241
+ expect(toasts()).toEqual([{ type: 'error', text1: 'Failed: boom' }]);
242
+ });
243
+
244
+ it('toasts when the external download handoff fails', async () => {
245
+ statusResults.push({ state: 'ready', downloadToken: 'tok-1' });
246
+ downloadDocument.mockResolvedValue(false);
247
+ renderPage();
248
+
249
+ await ReactTestRenderer.act(async () => {
250
+ await downloadButton().props!.onPress!();
251
+ });
252
+ await advance(2001);
253
+
254
+ expect(downloadDocument).toHaveBeenCalled();
255
+ expect(toasts()).toEqual([
256
+ {
257
+ type: 'error',
258
+ text1:
259
+ 'Failed: No app was found to download the file. Please try again.',
260
+ },
261
+ ]);
262
+ });
263
+
264
+ it('toasts when polling outlives the deadline without a result', async () => {
265
+ // Only `building` is ever queued (450 = the polls inside the 15-minute
266
+ // deadline at the 2 s cadence), so the loop runs until the deadline.
267
+ statusResults.push(
268
+ ...Array.from({ length: 450 }, () => ({ state: 'building' }))
269
+ );
270
+ renderPage();
271
+
272
+ await ReactTestRenderer.act(async () => {
273
+ await downloadButton().props!.onPress!();
274
+ });
275
+ // One jump past the 15-minute deadline (fake timers make it cheap).
276
+ await advance(15 * 60 * 1000 + 1);
277
+
278
+ expect(status).toHaveBeenCalledTimes(450);
279
+ expect(toasts()).toEqual([
280
+ {
281
+ type: 'error',
282
+ text1: 'Failed: The export did not finish in time. Please try again.',
283
+ },
284
+ ]);
285
+ // The button is back to its idle label once polling stopped.
286
+ expect(textCount('Preparing your export…')).toBe(0);
287
+ });
288
+
289
+ it('shows the preparing label while the export is running', async () => {
290
+ statusResults.push(
291
+ ...Array.from({ length: 450 }, () => ({ state: 'building' }))
292
+ );
293
+ renderPage();
294
+ expect(textCount('Preparing your export…')).toBe(0);
295
+
296
+ await ReactTestRenderer.act(async () => {
297
+ await downloadButton().props!.onPress!();
298
+ });
299
+ expect(textCount('Preparing your export…')).toBe(1);
300
+ await advance(15 * 60 * 1000 + 1); // let the deadline stop polling
301
+ expect(textCount('Preparing your export…')).toBe(0);
302
+ });
303
+ });
@@ -1,7 +1,7 @@
1
1
  import { MainScreenProps } from '../../components/navigation/types/index';
2
- import { useOpenpeeps } from '@openpeepshq/react';
2
+ import { useOpenpeeps, useAccountExport } from '@openpeepshq/react';
3
3
  import { HeaderActionButton, useSetPageHeader } from '../../components/layout';
4
- import React, { useEffect, useState } from 'react';
4
+ import React, { useCallback, useEffect, useState } from 'react';
5
5
  import { ThemedText } from '../../components/ui/themed-text';
6
6
  import { ThemedView } from '../../components/ui/themed-view';
7
7
  import { useForm } from 'react-hook-form';
@@ -12,6 +12,7 @@ import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view
12
12
  import { Account } from '@openpeepshq/common';
13
13
  import { ActivityIndicator, View } from 'react-native';
14
14
  import { useTranslation } from 'react-i18next';
15
+ import { downloadDocument } from '../../lib/downloadFile';
15
16
 
16
17
  type AccountSettingsProps = MainScreenProps<'AccountSettings'>;
17
18
 
@@ -23,7 +24,7 @@ type AccountFormValues = {
23
24
  };
24
25
 
25
26
  export const AccountSettings: React.FC<AccountSettingsProps> = () => {
26
- const { openpeepsApi, queryClient } = useOpenpeeps();
27
+ const { openpeepsApi, queryClient, client } = useOpenpeeps();
27
28
  const { data: currentAccount } = openpeepsApi.useCurrentAccount();
28
29
  const logout = openpeepsApi.logoutAction();
29
30
  const [isOldPasswordVisible, setIsOldPasswordVisible] = React.useState(false);
@@ -36,6 +37,40 @@ export const AccountSettings: React.FC<AccountSettingsProps> = () => {
36
37
  const [verifying, setVerifying] = useState(false);
37
38
  const { t } = useTranslation();
38
39
 
40
+ // RN has no fetch/blob, so the shared hook's web download step is replaced
41
+ // with an external handler. `download` must stay stable across renders:
42
+ // the hook closes over it in its memoized run callback.
43
+ const download = useCallback(
44
+ async (url: string) => {
45
+ const opened = await downloadDocument(url);
46
+ if (!opened) {
47
+ throw new Error(
48
+ t('settings.account.exportDownloadFailed', {
49
+ defaultValue:
50
+ 'No app was found to download the file. Please try again.',
51
+ })
52
+ );
53
+ }
54
+ },
55
+ [t]
56
+ );
57
+ const { exporting, status, startExport } = useAccountExport({
58
+ client,
59
+ t,
60
+ download,
61
+ });
62
+
63
+ // The hook reports export failures through its `status` (the web page
64
+ // renders it as an inline toast); RN has no such surface, so mirror the
65
+ // change to the imperative toast.
66
+ useEffect(() => {
67
+ if (!status) return;
68
+ Toast.show({
69
+ type: status.type,
70
+ text1: status.message,
71
+ });
72
+ }, [status]);
73
+
39
74
  const form = useForm<AccountFormValues>({
40
75
  defaultValues: {
41
76
  email: (currentAccount as Account)?.email ?? '',
@@ -309,6 +344,38 @@ export const AccountSettings: React.FC<AccountSettingsProps> = () => {
309
344
  {t('settings.account.oldPasswordReason')}
310
345
  </ThemedText>
311
346
  </View>
347
+ <ThemedText className="text-sm text-muted-foreground">
348
+ {t('settings.account.exportData', {
349
+ defaultValue: 'Download my content',
350
+ })}
351
+ </ThemedText>
352
+ <ThemedText className="text-xs text-muted-foreground">
353
+ {t('settings.account.exportDataDescription', {
354
+ defaultValue:
355
+ 'Download a copy of your data: your posts (with their thread context), posts you reacted to, and your profile and media, as a zip archive.',
356
+ })}
357
+ </ThemedText>
358
+ <View className="w-full">
359
+ <Button
360
+ variant="outline"
361
+ onPress={() => void startExport()}
362
+ disabled={exporting}
363
+ >
364
+ {exporting ? (
365
+ <ThemedText className="text-sm">
366
+ {t('settings.account.exportPreparing', {
367
+ defaultValue: 'Preparing your export…',
368
+ })}
369
+ </ThemedText>
370
+ ) : (
371
+ <ThemedText className="text-sm">
372
+ {t('settings.account.downloadData', {
373
+ defaultValue: 'Download',
374
+ })}
375
+ </ThemedText>
376
+ )}
377
+ </Button>
378
+ </View>
312
379
  </ThemedView>
313
380
  </Form>
314
381
  </KeyboardAwareScrollView>