Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

infra: enable strictNullChecks in tsconfig #2435

Merged
merged 47 commits into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from 42 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
7e89379
infra: enable strictNullChecks in tsconfig
ST-DDT Oct 5, 2023
8d3497b
Apply suggestions from code review
ST-DDT Oct 5, 2023
3ba4b4e
Apply suggestions from code review
ST-DDT Oct 5, 2023
c555cb8
build it
ST-DDT Oct 5, 2023
2c3c7c6
Update src/modules/finance/index.ts
ST-DDT Oct 5, 2023
3caf9d5
Apply suggestions from code review
ST-DDT Oct 5, 2023
2818847
Update test/faker.spec.ts
ST-DDT Oct 6, 2023
50531c8
Update scripts/apidoc/fakerClass.ts
ST-DDT Oct 6, 2023
ebc6ac5
chore: work around ts error in vitest extension
ST-DDT Oct 6, 2023
00f0fcf
chore: simplify version grouping
ST-DDT Oct 6, 2023
3e7d2d0
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 6, 2023
cf2397b
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 6, 2023
0042bdf
chore: prettyPrintIban helper function
ST-DDT Oct 6, 2023
45f6b06
chore: add assertLocaleData
ST-DDT Oct 6, 2023
fa8bb66
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 6, 2023
485cc60
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 7, 2023
a2a303d
chore: apply suggestions
ST-DDT Oct 7, 2023
5d88fb2
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 8, 2023
c9a9229
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 9, 2023
8ca3169
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 10, 2023
487cac2
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 11, 2023
91ad574
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 12, 2023
817d5a0
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 15, 2023
292aa81
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 15, 2023
4fe5153
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 20, 2023
6fe4253
revert: helpers changes
ST-DDT Oct 20, 2023
f36f34e
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 22, 2023
bae7b20
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 25, 2023
bf010a7
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 26, 2023
d3088bd
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 26, 2023
f82a7f6
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 28, 2023
c797146
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 29, 2023
6a54e73
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Oct 30, 2023
d8e078a
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Nov 6, 2023
bf88c58
chore: fix lint issues
ST-DDT Nov 6, 2023
865d4de
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Nov 6, 2023
234c12f
chore: fix another lint warning
ST-DDT Nov 6, 2023
85e9096
chore: fix import issue
ST-DDT Nov 6, 2023
109738f
Update src/modules/date/index.ts
ST-DDT Nov 6, 2023
94f7927
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Nov 6, 2023
e1e6c8a
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Nov 7, 2023
0d73a2a
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Nov 7, 2023
cb4383a
chore: fix lint warning
ST-DDT Nov 10, 2023
6efe430
chore: remove wrong defaults and make the properties required
ST-DDT Nov 10, 2023
0aa69d0
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Nov 13, 2023
c86f261
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Nov 13, 2023
84df921
Merge branch 'next' into infra/tsconfig/enable-strictNullChecks
ST-DDT Nov 14, 2023
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
2 changes: 1 addition & 1 deletion cypress/e2e/api.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ describe('API Test', () => {
cy.get('.api-group li').each(($el) => {
const anchor = $el.find('a');
const text = anchor.text();
const link = anchor.attr('href').split('#')[0];
const link = anchor.attr('href')?.split('#')[0] ?? 'MISSING';
if (checked.has(link)) {
return;
}
Expand Down
13 changes: 8 additions & 5 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,14 @@ const config = defineConfig({
{ icon: 'github', link: 'https://github.com/faker-js/faker' },
],

algolia: {
apiKey: process.env.API_KEY,
appId: process.env.APP_ID,
indexName: 'fakerjs',
},
algolia:
process.env.API_KEY == null || process.env.APP_ID == null
? undefined
: {
apiKey: process.env.API_KEY,
appId: process.env.APP_ID,
indexName: 'fakerjs',
},

footer: {
message: 'Released under the MIT License.',
Expand Down
21 changes: 13 additions & 8 deletions docs/.vitepress/versions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,23 @@ function readOtherLatestReleaseTagNames(): string[] {
.toString('utf8')
.split('\n')
.filter((tag) => semver.valid(tag))
.reduce<Record<number, string[]>>((acc, tag) => {
const majorVersion = semver.major(tag);
.filter((tag) => {
// Only consider tags for our deployed website versions,
// excluding the current major version.
if (majorVersion >= 6 && majorVersion !== currentMajorVersion) {
(acc[majorVersion] = acc[majorVersion] ?? []).push(tag);
const majorVersion = semver.major(tag);
return majorVersion >= 6 && majorVersion !== currentMajorVersion;
})
.reduce<Record<number, string>>((latestTagByMajor, tag) => {
const majorVersion = semver.major(tag);

const latestTag = latestTagByMajor[majorVersion];
if (latestTag == null || semver.lt(latestTag, tag)) {
latestTagByMajor[majorVersion] = tag;
}
return acc;

ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
return latestTagByMajor;
}, {});
return Object.entries(latestReleaseTagNames)
.map(([major, tags]) => semver.maxSatisfying(tags, `^${major}`))
.sort(semver.rcompare);
return Object.values(latestReleaseTagNames).sort(semver.rcompare);
}

// Set by netlify
Expand Down
6 changes: 5 additions & 1 deletion scripts/apidoc/faker-class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ export async function processFakerRandomizer(
.getChildrenByKind(ReflectionKind.Interface)
.find((clazz) => clazz.name === 'Randomizer');

if (randomizerClass == null) {
throw new Error('Randomizer class not found');
}

return processClass(randomizerClass);
}

Expand Down Expand Up @@ -62,7 +66,7 @@ async function processClass(
function hasConstructor(clazz: DeclarationReflection): boolean {
return clazz
.getChildrenByKind(ReflectionKind.Constructor)
.some((constructor) => constructor.signatures.length > 0);
.some((constructor) => (constructor.signatures?.length ?? 0) > 0);
}

async function processConstructor(
Expand Down
2 changes: 1 addition & 1 deletion scripts/apidoc/signature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ async function signatureTypeToText(
await Promise.all(
signature.parameters?.map(
async (p) => `${p.name}: ${await typeToText(p.type)}`
)
) ?? []
)
).join(', ')}) => ${await typeToText(signature.type)}`;
}
Expand Down
3 changes: 2 additions & 1 deletion src/definitions/date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@

/**
* The short name/abbreviation of the entry.
* If null, the locale does not support a short name/abbreviation for the entry.

Check warning on line 29 in src/definitions/date.ts

View check run for this annotation

Codecov / codecov/patch

src/definitions/date.ts#L29

Added line #L29 was not covered by tests
*/
abbr: string[];
abbr: string[] | null;

Check warning on line 31 in src/definitions/date.ts

View check run for this annotation

Codecov / codecov/patch

src/definitions/date.ts#L31

Added line #L31 was not covered by tests

/**
* The wide name of the entry when used in context. If absent wide will be used instead.
Expand Down
2 changes: 1 addition & 1 deletion src/definitions/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@
system?: SystemDefinition;
vehicle?: VehicleDefinition;
word?: WordDefinition;
} & Record<string, Record<string, unknown> | undefined>;
} & Record<string, Record<string, unknown>>;

Check warning on line 53 in src/definitions/definitions.ts

View check run for this annotation

Codecov / codecov/patch

src/definitions/definitions.ts#L53

Added line #L53 was not covered by tests
40 changes: 27 additions & 13 deletions src/locale-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,30 @@ export function createLocaleProxy(locale: LocaleDefinition): LocaleProxy {
}) as LocaleProxy;
}

/**
* Checks that the value is not null or undefined and throws an error if it is.
*
* @param value The value to check.
* @param path The path to the locale data.
*/
export function assertLocaleData<T>(
value: T,
...path: string[]
): asserts value is NonNullable<T> {
if (value === null) {
throw new FakerError(
`The locale data for '${path.join('.')}' aren't applicable to this locale.
If you think this is a bug, please report it at: https://github.com/faker-js/faker`
);
} else if (value === undefined) {
throw new FakerError(
`The locale data for '${path.join('.')}' are missing in this locale.
Please contribute the missing data to the project or use a locale/Faker instance that has these data.
For more information see https://fakerjs.dev/guide/localization.html`
);
}
}

/**
* Creates a proxy for a category that throws an error when accessing an undefined property.
*
Expand All @@ -79,20 +103,10 @@ function createCategoryProxy<
const value = target[entryName];
if (typeof entryName === 'symbol' || entryName === 'nodeType') {
return value;
} else if (value === null) {
throw new FakerError(
`The locale data for '${categoryName}.${entryName.toString()}' aren't applicable to this locale.
If you think this is a bug, please report it at: https://github.com/faker-js/faker`
);
} else if (value === undefined) {
throw new FakerError(
`The locale data for '${categoryName}.${entryName.toString()}' are missing in this locale.
Please contribute the missing data to the project or use a locale/Faker instance that has these data.
For more information see https://fakerjs.dev/guide/localization.html`
);
} else {
return value;
}

assertLocaleData(value, categoryName, entryName.toString());
return value;
},

set: throwReadOnlyError,
Expand Down
2 changes: 1 addition & 1 deletion src/modules/airline/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export class AirlineModule extends ModuleBase {
): string {
const { allowNumerics = false, allowVisuallySimilarCharacters = false } =
options;
const excludedChars = [];
const excludedChars: string[] = [];
if (!allowNumerics) {
excludedChars.push(...numerics);
}
Expand Down
10 changes: 9 additions & 1 deletion src/modules/commerce/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { FakerError } from '../../errors/faker-error';
import { deprecated } from '../../internal/deprecated';
import { ModuleBase } from '../../internal/module-base';

Expand Down Expand Up @@ -381,7 +382,14 @@

const registrantLength = groupRules.find(
([rangeMaximum]) => elementValue <= rangeMaximum
)[1];
)?.[1];

if (!registrantLength) {
// This can only happen if the ISBN_LENGTH_RULES are corrupted
throw new FakerError(
`Unable to find a registrant length for the group ${group}`
);
}

Check warning on line 392 in src/modules/commerce/index.ts

View check run for this annotation

Codecov / codecov/patch

src/modules/commerce/index.ts#L388-L392

Added lines #L388 - L392 were not covered by tests

const registrant = element.slice(0, registrantLength);
const publication = element.slice(registrantLength);
Expand Down
51 changes: 27 additions & 24 deletions src/modules/date/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { DateEntryDefinition } from '../../definitions';
import { FakerError } from '../../errors/faker-error';
import { deprecated } from '../../internal/deprecated';
import { SimpleModuleBase } from '../../internal/module-base';
import { assertLocaleData } from '../../locale-proxy';

/**
* Converts date passed as a string, number or Date to a Date object.
Expand All @@ -15,6 +16,10 @@ function toDate(
date: string | Date | number | undefined,
fallback: () => Date
): Date {
if (date == null) {
return fallback();
}

date = new Date(date);
if (Number.isNaN(date.valueOf())) {
date = fallback();
Expand Down Expand Up @@ -383,14 +388,15 @@ export class SimpleDateModule extends SimpleModuleBase {
},
legacyTo?: string | Date | number
): Date {
if (typeof options !== 'object' || options instanceof Date) {
if (options instanceof Date || typeof options !== 'object') {
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
deprecated({
deprecated: 'faker.date.between(from, to)',
proposed: 'faker.date.between({ from, to })',
since: '8.0',
until: '9.0',
});
options = { from: options, to: legacyTo };
// We use options as fallback for legacyTo avoid TS errors for unintended usage.
options = { from: options, to: legacyTo ?? options };
xDivisionByZerox marked this conversation as resolved.
Show resolved Hide resolved
}

const { from, to } = options;
Expand Down Expand Up @@ -559,14 +565,15 @@ export class SimpleDateModule extends SimpleModuleBase {
legacyTo?: string | Date | number,
legacyCount: number = 3
): Date[] {
if (typeof options !== 'object' || options instanceof Date) {
if (options instanceof Date || typeof options !== 'object') {
deprecated({
deprecated: 'faker.date.betweens(from, to, count)',
proposed: 'faker.date.betweens({ from, to, count })',
since: '8.0',
until: '9.0',
});
options = { from: options, to: legacyTo, count: legacyCount };
// We use options as fallback for legacyTo avoid TS errors for unintended usage.
options = { from: options, to: legacyTo ?? options, count: legacyCount };
}

const { from, to, count = 3 } = options;
Expand Down Expand Up @@ -864,12 +871,6 @@ export class SimpleDateModule extends SimpleModuleBase {
refDate?: string | Date | number;
} = {}
): Date {
if (options.max < options.min) {
throw new FakerError(
`Max ${options.max} should be larger than or equal to min ${options.min}.`
);
}

const mode = options.mode === 'age' ? 'age' : 'year';
const refDate = toDate(options.refDate, this.faker.defaultRefDate);
const refYear = refDate.getUTCFullYear();
Expand All @@ -894,6 +895,12 @@ export class SimpleDateModule extends SimpleModuleBase {
);
}

if (max < min) {
throw new FakerError(
`Max ${options.max} should be larger than or equal to min ${options.min}.`
);
}

return new Date(this.faker.number.int({ min, max }));
}
}
Expand Down Expand Up @@ -1074,12 +1081,8 @@ export class DateModule extends SimpleDateModule {
context?: boolean;
} = {}
): string {
const {
// eslint-disable-next-line deprecation/deprecation
abbr,
abbreviated = abbr ?? false,
context = false,
} = options;
// eslint-disable-next-line deprecation/deprecation
const { abbr, abbreviated = abbr ?? false, context = false } = options;

if (abbr != null) {
deprecated({
Expand All @@ -1100,7 +1103,9 @@ export class DateModule extends SimpleDateModule {
type = useContext ? 'wide_context' : 'wide';
}

return this.faker.helpers.arrayElement(source[type]);
const values = source[type];
assertLocaleData(values, 'date.month', type);
return this.faker.helpers.arrayElement(values);
}

/**
Expand Down Expand Up @@ -1260,12 +1265,8 @@ export class DateModule extends SimpleDateModule {
context?: boolean;
} = {}
): string {
const {
// eslint-disable-next-line deprecation/deprecation
abbr,
abbreviated = abbr ?? false,
context = false,
} = options;
// eslint-disable-next-line deprecation/deprecation
const { abbr, abbreviated = abbr ?? false, context = false } = options;

if (abbr != null) {
deprecated({
Expand All @@ -1286,6 +1287,8 @@ export class DateModule extends SimpleDateModule {
type = useContext ? 'wide_context' : 'wide';
}

return this.faker.helpers.arrayElement(source[type]);
const values = source[type];
assertLocaleData(values, 'date.weekday', type);
return this.faker.helpers.arrayElement(values);
}
}
22 changes: 19 additions & 3 deletions src/modules/finance/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,22 @@ export interface Currency {
symbol: string;
}

/**
* Puts a space after every 4 characters.
*
* @internal
*
* @param iban The iban to pretty print.
*/
export function prettyPrintIban(iban: string): string {
let pretty = '';
for (let i = 0; i < iban.length; i += 4) {
pretty += `${iban.substring(i, i + 4)} `;
}

return pretty.trimEnd();
}

/**
* Module to generate finance and money related entries.
*
Expand Down Expand Up @@ -663,9 +679,9 @@ export class FinanceModule extends ModuleBase {
*/
currencySymbol(): string {
let symbol: string;
while (!symbol) {
do {
symbol = this.currency().symbol;
}
} while (symbol.length === 0);

return symbol;
}
Expand Down Expand Up @@ -1147,7 +1163,7 @@ export class FinanceModule extends ModuleBase {

const result = `${ibanFormat.country}${checksum}${s}`;

return formatted ? result.match(/.{1,4}/g).join(' ') : result;
return formatted ? prettyPrintIban(result) : result;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/modules/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1120,7 +1120,7 @@ export class SimpleHelpersModule extends SimpleModuleBase {
) => RecordKey,
>(
method: TMethod,
args: Parameters<TMethod> = [] as Parameters<TMethod>,
args: Parameters<TMethod> = [] as unknown as Parameters<TMethod>,
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
options: {
/**
* This parameter does nothing.
Expand Down
4 changes: 2 additions & 2 deletions src/modules/helpers/unique.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,9 @@ export function exec<
maxRetries = 50,
currentIterations = 0,
compare = defaultCompare,
store,
store = {},
} = options;
let { exclude } = options;
let { exclude = [] } = options;
options.currentIterations = currentIterations;

// Support single exclude argument as string
Expand Down
Loading
Loading