Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/guides/sources-and-loading.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,11 @@ the document.
A source must be a `require()` asset number or an object with `uri`, `filePath`
or `base64`. Anything else — a raw URL string (e.g. `'https://...'`), an empty
object `{}`, property types that do not match (such as `{ uri: 42 }`), or list
items that are not objects (such as `[null]`) — is malformed:
items that are not objects (such as `[null]`) — is malformed. So is a URI
source with an option of the wrong type: `headers` that is not an object of
strings (a header whose value is `undefined` included), `cache` other than
`'session'` or `'persistent'`, `maxAgeMs` that is not a finite number of at
least 0, or `cacheKey` that is not a string. `null` options count as absent.

- In `PdfView`: it never throws during render. Nothing is sent to native, and
`onError` is called once with `code: 'invalid-source'` and an explanatory
Expand Down
17 changes: 17 additions & 0 deletions package/src/PdfCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,4 +241,21 @@ describe('PdfCache', () => {
await expect(removePromise!).rejects.toThrow();
}
});

test('download, getEntry and remove reject options of the wrong type before native code', async () => {
const source = { uri: 'https://x.test/a.pdf', cacheKey: 42 } as never;
const error = await PdfCache.download(source).catch((e: unknown) => e);
expect(error).toBeInstanceOf(PdfDownloadError);
expect(error).toMatchObject({
code: 'invalid-source',
message: 'source.cacheKey must be a string; got 42',
});
await expect(PdfCache.getEntry(source)).rejects.toThrow(
'source.cacheKey must be a string; got 42',
);
await expect(PdfCache.remove(source)).rejects.toThrow(
'source.cacheKey must be a string; got 42',
);
expect(downloads).toEqual([]);
});
});
13 changes: 13 additions & 0 deletions package/src/PdfDocument.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,19 @@ describe('PdfDocument.open', () => {
}
});

test('rejects options of the wrong type before creating the native object', async () => {
const error = await PdfDocument.open({
uri: 'https://x.test/a.pdf',
cacheKey: 42,
} as never).catch((e: unknown) => e);
expect(error).toBeInstanceOf(PdfOpenError);
expect(error).toMatchObject({
code: 'invalid-source',
message: 'source.cacheKey must be a string; got 42',
});
expect(natives).toEqual([]);
});

test("a source's own password takes precedence over the option", async () => {
void PdfDocument.open(
{ uri: '/docs/a.pdf', password: 'own' },
Expand Down
21 changes: 21 additions & 0 deletions package/src/PdfView.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1162,6 +1162,27 @@ describe('PdfView', () => {
]);
});

test('source options of the wrong type call onError once and send nothing to native', () => {
const errors: unknown[] = [];
render(
<PdfView
source={[
{ uri: 'https://x.test/a.pdf' },
{ uri: 'https://x.test/b.pdf', headers: { 'X-User': 7 } } as never,
]}
onError={(err) => errors.push(err)}
/>,
);
expect(hostRenders.length).toBe(0);
expect(errors).toEqual([
{
code: 'invalid-source',
message: 'source.headers["X-User"] must be a string; got 7',
sourceIndex: 1,
},
]);
});

test('promise methods reject with coded PdfMethodErrors', async () => {
const ref = createRef<PdfViewRef>();
render(<PdfView ref={ref} source={{ uri: 'x' }} />);
Expand Down
99 changes: 99 additions & 0 deletions package/src/source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,105 @@ describe('validateSourceItem', () => {
test('unresolvable assets become an empty uri, which native reports as invalid-source', () => {
expect(validatedSource(99)).toEqual({ uri: '' });
});

test('null options are absent', () => {
expect(
validatedSource({
uri: 'https://x.test/a.pdf',
headers: null,
cache: null,
maxAgeMs: null,
cacheKey: null,
}),
).toEqual({ uri: 'https://x.test/a.pdf' });
});

test('reports options of the wrong type, naming the option', () => {
const uri = 'https://x.test/a.pdf';
const cases: [Record<string, unknown>, string][] = [
[{ uri, cacheKey: 42 }, 'source.cacheKey must be a string; got 42'],
[
{ uri, headers: 'Authorization: x' },
'source.headers must be an object of strings; got a string',
],
[
{ uri, headers: ['x'] },
'source.headers must be an object of strings; got an array',
],
[
{ uri, headers: new Map([['Authorization', 'x']]) },
'source.headers must be an object of strings; got a Map',
],
[
{ uri, headers: { 'X-User': 7 } },
'source.headers["X-User"] must be a string; got 7',
],
[
{ uri, headers: { Authorization: undefined } },
'source.headers["Authorization"] must be a string; got undefined',
],
[
{ uri, headers: { Authorization: null } },
'source.headers["Authorization"] must be a string; got null',
],
[
{ uri, cache: 'Persistent' },
"source.cache must be 'session' or 'persistent'; got a string",
],
[
{ uri, cache: true },
"source.cache must be 'session' or 'persistent'; got true",
],
[
{ uri, maxAgeMs: '0' },
'source.maxAgeMs must be a finite number of at least 0; got a string',
],
[
{ uri, maxAgeMs: -1 },
'source.maxAgeMs must be a finite number of at least 0; got -1',
],
[
{ uri, maxAgeMs: Number.NaN },
'source.maxAgeMs must be a finite number of at least 0; got NaN',
],
[
{ uri, maxAgeMs: Number.POSITIVE_INFINITY },
'source.maxAgeMs must be a finite number of at least 0; got Infinity',
],
];
for (const [source, error] of cases) {
expect(validateSourceItem(source, resolveAsset)).toEqual({
ok: false,
error,
});
expect(() => normalizeUriSource(source as never)).toThrow(error);
}
});

test('reads each option once, so a getter cannot change it after the check', () => {
let reads = 0;
const headers = {
get Authorization() {
reads += 1;
return reads === 1 ? 'Bearer 1' : (7 as never);
},
};
let headersReads = 0;
const source = {
uri: 'https://x.test/a.pdf',
get headers() {
headersReads += 1;
return headersReads === 1 ? headers : (7 as never);
},
};
expect(validateSourceItem(source, resolveAsset)).toEqual({
ok: true,
source: {
uri: 'https://x.test/a.pdf',
headers: { Authorization: 'Bearer 1' },
},
});
});
});

describe('sourceKey', () => {
Expand Down
106 changes: 87 additions & 19 deletions package/src/source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,21 @@ function describeValue(value: unknown): string {
return 'a string';
case 'number':
return Number.isNaN(value) ? 'NaN' : String(value);
case 'boolean':
return String(value);
case 'bigint':
return `${value}n`;
case 'symbol':
return value.toString();
case 'function':
return 'a function';
case 'object':
return Array.isArray(value) ? 'an array' : 'an object';
case 'object': {
if (Array.isArray(value)) return 'an array';
const name = Object.getPrototypeOf(value)?.constructor?.name;
return typeof name === 'string' && name !== 'Object'
? `a ${name}`
: 'an object';
}
default:
return typeof value;
}
Expand Down Expand Up @@ -204,9 +211,8 @@ export function validateSourceItem(
};
}
if ('uri' in obj) {
if (typeof obj.uri === 'string') {
return { ok: true, source: normalizeUriSource(source as PdfUriSource) };
}
const { uri } = obj;
if (typeof uri === 'string') return uriSourceResult(uri, obj);
return {
ok: false,
error: `source must be a require() result or an object with uri, filePath or base64; got ${describeSourceType(source)}`,
Expand All @@ -219,28 +225,90 @@ export function validateSourceItem(
}

/**
* The native shape of a URI source. Copies `headers` so later mutation of
* the caller's object cannot leak into native code, and leaves absent
* options absent.
* The native shape of a URI source, or why its options are invalid: Nitro's
* converters throw on a value of the wrong type. Reads each option once and
* copies `headers`, so neither a getter nor later mutation of the caller's
* object can change what was checked. `null` options are absent.
*/
function uriSourceResult(
uri: string,
source: Record<string, unknown>,
):
| { ok: true; source: Omit<NativePdfSource, 'base64'> }
| { ok: false; error: string } {
const { headers, cache, maxAgeMs, cacheKey } = source;
const normalized: Omit<NativePdfSource, 'base64'> = { uri };
if (headers != null) {
const prototype =
typeof headers === 'object' ? Object.getPrototypeOf(headers) : undefined;
if (prototype !== Object.prototype && prototype !== null) {
return {
ok: false,
error: `source.headers must be an object of strings; got ${describeValue(headers)}`,
};
}
const copy: Record<string, string> = {};
for (const [name, value] of Object.entries(headers as object)) {
if (typeof value !== 'string') {
return {
ok: false,
error: `source.headers[${JSON.stringify(name)}] must be a string; got ${describeValue(value)}`,
};
}
copy[name] = value;
}
normalized.headers = copy;
}
if (cache != null) {
if (cache !== 'session' && cache !== 'persistent') {
return {
ok: false,
error: `source.cache must be 'session' or 'persistent'; got ${describeValue(cache)}`,
};
}
normalized.cache = cache;
}
if (maxAgeMs != null) {
if (
typeof maxAgeMs !== 'number' ||
!Number.isFinite(maxAgeMs) ||
maxAgeMs < 0
) {
return {
ok: false,
error: `source.maxAgeMs must be a finite number of at least 0; got ${describeValue(maxAgeMs)}`,
};
}
normalized.maxAgeMs = maxAgeMs;
}
if (cacheKey != null) {
if (typeof cacheKey !== 'string') {
return {
ok: false,
error: `source.cacheKey must be a string; got ${describeValue(cacheKey)}`,
};
}
normalized.cacheKey = cacheKey;
}
return { ok: true, source: normalized };
}

/** The native shape of a URI source; throws when it is invalid. */
export function normalizeUriSource(
source: PdfUriSource,
): Omit<NativePdfSource, 'base64'> {
if (
source == null ||
typeof source !== 'object' ||
typeof (source as { uri?: unknown }).uri !== 'string'
) {
const uri = (source as { uri?: unknown } | null | undefined)?.uri;
if (source == null || typeof source !== 'object' || typeof uri !== 'string') {
throw new Error(
`source must be an object with uri; got ${describeSourceType(source, true)}`,
);
}
const normalized: Omit<NativePdfSource, 'base64'> = { uri: source.uri };
if (source.headers != null) normalized.headers = { ...source.headers };
if (source.cache != null) normalized.cache = source.cache;
if (source.maxAgeMs != null) normalized.maxAgeMs = source.maxAgeMs;
if (source.cacheKey != null) normalized.cacheKey = source.cacheKey;
return normalized;
const result = uriSourceResult(
uri,
source as unknown as Record<string, unknown>,
);
if (!result.ok) throw new Error(result.error);
return result.source;
}

/** The source's own password, if it has one (bundled assets cannot). */
Expand Down
Loading