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
1 change: 0 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ jobs:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version:
- 18.x
- 20.x
- 22.x
- 24.x
Expand Down
25 changes: 11 additions & 14 deletions lib/construction/strategy/ConstructionStrategyCommonJs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export class ConstructionStrategyCommonJs implements IConstructionStrategy<any>
if (typeof object !== 'function') {
throw new Error(`Attempted to construct ${options.requireElement} from module ${options.requireName} that does not have a constructor`);
}
object = new (Function.prototype.bind.apply(object, <[any, ...any]>[{}].concat(options.args)))();
object = new (Function.prototype.bind.apply(object, <[any, ...any]>[{}, ...options.args ]))();
}

return object;
Expand All @@ -72,25 +72,22 @@ export class ConstructionStrategyCommonJs implements IConstructionStrategy<any>
*/
public requireCurrentRunningModuleIfCurrent(moduleState: IModuleState, requireName: string): { value: any } | false {
const pckg = moduleState.packageJsons[moduleState.mainModulePath];
if (pckg) {
if (requireName === pckg.name) {
const mainPath: string = Path.posix.join(moduleState.mainModulePath, pckg.main);
const required = this.req(mainPath);
if (required) {
return { value: required };
}
if (pckg && requireName === pckg.name) {
const mainPath: string = Path.posix.join(moduleState.mainModulePath, pckg.main);
const required = this.req(mainPath);
if (required) {
return { value: required };
}
}
return false;
}

public createHash(options: ICreationStrategyHashOptions<any>): any {
return options.entries.reduce((data: Record<string, any>, entry: { key: string; value: any } | undefined) => {
if (entry) {
data[entry.key] = entry.value;
}
return data;
}, {});
return Object.fromEntries(
options.entries
.filter((entry): entry is { key: string; value: any } => entry !== undefined)
.map(entry => [ entry.key, entry.value ]),
);
}

public createArray(options: ICreationStrategyArrayOptions<any>): any {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export class ConstructionStrategyCommonJsString implements IConstructionStrategy
this.getCurrentRunningModuleMain(options.moduleState),
)}` :
options.requireName;
let serialization = `require('${resultingRequirePath.replace(/\\/gu, '/')}')`;
let serialization = `require('${resultingRequirePath.replaceAll('\\', '/')}')`;

// Determine the child of the require'd element
if (options.requireElement) {
Expand Down
2 changes: 1 addition & 1 deletion lib/loading/ComponentRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class ComponentRegistry {
*/
public async registerAvailableModules(): Promise<void> {
await Promise.all(Object.values(this.moduleState.componentModules)
.flatMap(Object.values)
.flatMap(x => Object.values(x))
.map((moduleResourceUrl: string) => this.registerModule(moduleResourceUrl)));
}

Expand Down
6 changes: 2 additions & 4 deletions lib/preprocess/ConfigPreprocessorComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,10 +289,8 @@ export class ConfigPreprocessorComponent implements IConfigPreprocessor<ICompone
// Emit warning on undefined parameters inside the component's scope
const prefix = handleResponse.component.value;
for (const property of Object.keys(config.property)) {
if (property.startsWith(prefix)) {
if (!validParameters[property]) {
this.logger.warn(`Detected potentially invalid component parameter '${property}' in a config`);
}
if (property.startsWith(prefix) && !validParameters[property]) {
this.logger.warn(`Detected potentially invalid component parameter '${property}' in a config`);
}
}
}
Expand Down
16 changes: 8 additions & 8 deletions lib/preprocess/ConfigPreprocessorOverride.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ export class ConfigPreprocessorOverride implements IConfigPreprocessor<Resource[
while (change) {
change = false;
for (const [ id, chain ] of Object.entries(overrideChains)) {
let next = chain[chain.length - 1];
let next = chain.at(-1)!;
// If the next part of the chain is found in `overrideChains` we can merge them and remove the tail entry
while (overrideChains[next.value]) {
change = true;
Expand All @@ -158,7 +158,7 @@ export class ConfigPreprocessorOverride implements IConfigPreprocessor<Resource[
// In case of a cycle there will be a point where next equals the first element,
// at which point it will delete itself.
delete overrideChains[next.value];
next = chain[chain.length - 1];
next = chain.at(-1)!;
}
// Reset the loop since we are modifying the object we are iterating over
if (change) {
Expand All @@ -175,7 +175,7 @@ export class ConfigPreprocessorOverride implements IConfigPreprocessor<Resource[
* @param chains - The override chains to check.
*/
protected validateChains(chains: Resource[][]): void {
const targets = chains.map((chain): string => chain[chain.length - 1].value);
const targets = chains.map((chain): string => chain.at(-1)!.value);
for (let i = 0; i < targets.length; ++i) {
const duplicateIdx = targets.findIndex((target, idx): boolean => idx > i && target === targets[i]);
if (duplicateIdx > 0) {
Expand Down Expand Up @@ -231,18 +231,18 @@ export class ConfigPreprocessorOverride implements IConfigPreprocessor<Resource[
* @param chain - The chain to find the target of.
*/
protected getChainTarget(chain: Resource[]): Resource {
const target = chain[chain.length - 1];
const target = chain.at(-1)!;
const types = uniqueTypes(target, this.componentResources);
if (!types || types.length === 0) {
throw new ErrorResourcesContext(`Missing type for override target ${target.value} of Override ${chain[chain.length - 2].value}`, {
throw new ErrorResourcesContext(`Missing type for override target ${target.value} of Override ${chain.at(-2)!.value}`, {
target,
override: chain[chain.length - 2],
override: chain.at(-2),
});
}
if (types.length > 1) {
throw new ErrorResourcesContext(`Found multiple types for override target ${target.value} of Override ${chain[chain.length - 2].value}`, {
throw new ErrorResourcesContext(`Found multiple types for override target ${target.value} of Override ${chain.at(-2)!.value}`, {
target,
override: chain[chain.length - 2],
override: chain.at(-2),
});
}
return target;
Expand Down
2 changes: 1 addition & 1 deletion lib/preprocess/ParameterHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export class ParameterHandler {
});
}
value = this.objectLoader.createCompactedResource({
list: values.flatMap(subValue => <Resource[]> subValue.list),
list: values.flatMap(subValue => subValue.list!),
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class ConstructorArgumentsElementMappingHandlerList implements IConstruct
// Recursively handle all field values.
const ret = mapper.objectLoader.createCompactedResource({});
ret.list = [];
for (const argument of (<Resource[]> constructorArgs.list)) {
for (const argument of constructorArgs.list!) {
if (argument.property.fields || argument.property.elements) {
ret.list.push(mapper
.applyConstructorArgumentsParameters(configRoot, argument, configElement, genericsContext));
Expand Down
5 changes: 3 additions & 2 deletions lib/preprocess/overridesteps/OverrideUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export type OverrideStepFieldName = `${typeof OVERRIDE_STEP_FIELD_NAMES[number]}
* @param step - Override step to get the fields from.
* @param expected - For each field, how many are expected. The value can be undefined if there is no fixed amount.
*/
export function extractOverrideStepFields(step: Resource, expected: { [key in OverrideStepFieldName]?: number } = {}):
export function extractOverrideStepFields(step: Resource, expected: {[key in OverrideStepFieldName]?: number } = {}):
Record<OverrideStepFieldName, Resource[]> {
// Type is not correct yet now but will be completed in the loop below
const result = <Record<OverrideStepFieldName, Resource[]>> {};
Expand Down Expand Up @@ -57,7 +57,8 @@ export function getPropertyResourceList(config: Resource, parameter: Resource):

// Having multiple lists can happen if multiple config files add elements to the same list
const list = properties.flatMap(prop => prop.list);
if (list.some(res => res === undefined)) {
// eslint-disable-next-line unicorn/no-useless-undefined
if (list.includes(undefined)) {
throw new ErrorResourcesContext(`Invalid target in Override step targeting ${config.value}: ${parameter.value} does not reference a list`, {
config,
});
Expand Down
2 changes: 1 addition & 1 deletion lib/rdf/RdfStreamIncluder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,6 @@ export class RdfStreamIncluder extends Transform {
* @param iri A potential IRI.
*/
public static isValidIri(iri: string): boolean {
return Boolean(/:((\/\/)|(.*:))/u.exec(iri));
return Boolean(/:((\/\/)|(.*:))/u.test(iri));
}
}
1 change: 0 additions & 1 deletion lib/util/ErrorResourcesContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ export class ErrorResourcesContext extends Error {
}
}

// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
export interface IErrorContext {
[key: string]: Resource | Resource[] | string | undefined | IErrorContext | IParamValueConflict;
}
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,15 @@
"minimist": "^1.2.0",
"rdf-data-factory": "^2.0.2",
"rdf-object": "^3.0.0",
"rdf-parse": "^4.0.0",
"rdf-parse": "^5.0.0",
"rdf-quad": "^2.0.0",
"rdf-string": "^2.0.1",
"rdf-terms": "^2.0.0",
"semver": "^7.3.2",
"winston": "^3.3.3"
},
"devDependencies": {
"@rubensworks/eslint-config": "1.0.1",
"@rubensworks/eslint-config": "1.2.0",
"@types/jest": "^30.0.0",
"@types/stream-to-array": "^2.3.0",
"@types/streamify-string": "^1.0.0",
Expand All @@ -70,16 +70,16 @@
"jshint": "^2.1.10",
"manual-git-changelog": "^1.0.1",
"n3": "^2.0.0",
"node-polyfill-webpack-plugin": "^3.0.0",
"node-polyfill-webpack-plugin": "^4.0.0",
"pre-commit": "^1.2.2",
"simple-copy": "^2.2.1",
"stream-to-array": "^2.3.0",
"streamify-string": "^1.0.1",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.1",
"typescript": "~5.5.0",
"typescript": "~6.0.0",
"webpack": "^5.75.0",
"webpack-cli": "^6.0.0"
"webpack-cli": "^7.0.0"
},
"files": [
"components",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,6 @@ describe('construction with mapped component configs as Resource', () => {
'http://example.org/n3#lineMode': { list: [ '"true"' ]},
});
await expect(configConstructorPool.instantiate(config, settings)).rejects
// eslint-disable-next-line max-len
.toThrow(/The value "\[true\]" for parameter ".*lineMode" is not of required range type ".*string\[\]\[\]"/u);
});

Expand Down
7 changes: 4 additions & 3 deletions test/unit/loading/ComponentsManager-test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as fs from 'fs';
import { mocked } from 'jest-mock';
import type { Resource } from 'rdf-object';
import { RdfObjectLoader } from 'rdf-object';
import type { Logger } from 'winston';
Expand All @@ -9,8 +8,10 @@ import { ConfigRegistry } from '../../../lib/loading/ConfigRegistry';
import type { IModuleState } from '../../../lib/loading/ModuleStateBuilder';
import { ErrorResourcesContext } from '../../../lib/util/ErrorResourcesContext';

jest.spyOn(fs, 'writeFileSync');
mocked(fs.writeFileSync).mockReturnValue();
jest.mock('fs', () => ({
...jest.requireActual<typeof fs>('fs'),
writeFileSync: jest.fn(),
}));
jest.mock('../../../lib/loading/ComponentsManagerBuilder', () => ({
// eslint-disable-next-line object-shorthand
ComponentsManagerBuilder: function(args: any) {
Expand Down
20 changes: 8 additions & 12 deletions test/unit/preprocess/ConfigPreprocessorComponent-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import * as fs from 'fs';
import type { Resource } from 'rdf-object';
import { RdfObjectLoader } from 'rdf-object';
import type { Logger } from 'winston';
import type {
IComponentConfigPreprocessorHandleResponse,
} from '../../../lib/preprocess/ConfigPreprocessorComponent';

import {
ConfigPreprocessorComponent,
} from '../../../lib/preprocess/ConfigPreprocessorComponent';
Expand Down Expand Up @@ -50,7 +48,7 @@ describe('ConfigPreprocessorComponent', () => {
'@id': 'ex:myComponentInstance',
types: 'ex:Component',
});
const { module, component } = <IComponentConfigPreprocessorHandleResponse> preprocessor.canHandle(config);
const { module, component } = preprocessor.canHandle(config)!;
expect(module).toBe(componentResources['ex:Component'].property.module);
expect(component).toBe(componentResources['ex:Component']);
});
Expand Down Expand Up @@ -112,7 +110,6 @@ describe('ConfigPreprocessorComponent', () => {
types: [ 'ex:Component', 'ex:Component2' ],
});
expect(() => preprocessor.canHandle(config))
// eslint-disable-next-line max-len
.toThrow(/^Detected more than one component types for config "ex:myComponentInstance"/u);
});

Expand Down Expand Up @@ -159,7 +156,7 @@ describe('ConfigPreprocessorComponent', () => {

describe('transformConstructorArguments', () => {
function expectTransformOutput(config: Resource, expectedArgs: Resource) {
const hr = <IComponentConfigPreprocessorHandleResponse> preprocessor.canHandle(config);
const hr = preprocessor.canHandle(config)!;
const ret = preprocessor.transformConstructorArguments(config, hr);
expect(expectedArgs.toQuads()).toBeRdfIsomorphic(ret.toQuads());
}
Expand Down Expand Up @@ -440,7 +437,7 @@ describe('ConfigPreprocessorComponent', () => {

describe('transform', () => {
function expectTransformOutput(config: Resource, expectedResource: Resource) {
const hr = <IComponentConfigPreprocessorHandleResponse> preprocessor.canHandle(config);
const hr = preprocessor.canHandle(config)!;
const { finishTransformation, rawConfig } = preprocessor.transform(config, hr);
expect(expectedResource.toQuads()).toBeRdfIsomorphic(rawConfig.toQuads());
expect(finishTransformation).toBe(true);
Expand Down Expand Up @@ -573,9 +570,8 @@ describe('ConfigPreprocessorComponent', () => {
'@id': 'ex:ComponentThis',
module: 'ex:Module',
});
const hr = <IComponentConfigPreprocessorHandleResponse> preprocessor.canHandle(config);
const hr = preprocessor.canHandle(config)!;
expect(() => preprocessor.transform(config, hr))
// eslint-disable-next-line max-len
.toThrow(/^Could not find a requireName in either the config's module or component/u);
});

Expand Down Expand Up @@ -1025,7 +1021,7 @@ describe('ConfigPreprocessorComponent', () => {
'@id': 'ex:ComponentThis#param1',
},
});
const hr = <IComponentConfigPreprocessorHandleResponse> preprocessor.canHandle(config);
const hr = preprocessor.canHandle(config)!;
preprocessor.validateConfig(config, hr);
expect(logger.warn).toHaveBeenCalledWith(`Detected potentially invalid component parameter 'ex:ComponentThis#param2' in a config`);
});
Expand All @@ -1043,7 +1039,7 @@ describe('ConfigPreprocessorComponent', () => {
'@id': 'ex:ComponentThis#param1',
},
});
const hr = <IComponentConfigPreprocessorHandleResponse> preprocessor.canHandle(config);
const hr = preprocessor.canHandle(config)!;
preprocessor.validateConfig(config, hr);
expect(logger.warn).not.toHaveBeenCalled();
});
Expand All @@ -1061,7 +1057,7 @@ describe('ConfigPreprocessorComponent', () => {
'@id': 'ex:ComponentThis#param1',
},
});
const hr = <IComponentConfigPreprocessorHandleResponse> preprocessor.canHandle(config);
const hr = preprocessor.canHandle(config)!;
preprocessor.validateConfig(config, hr);
expect(logger.warn).not.toHaveBeenCalled();
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as fs from 'fs';
import { RdfObjectLoader } from 'rdf-object/lib/RdfObjectLoader';
import type { Resource } from 'rdf-object/lib/Resource';
import type { IComponentConfigPreprocessorHandleResponse } from '../../../lib/preprocess/ConfigPreprocessorComponent';
import { ConfigPreprocessorComponentMapped } from '../../../lib/preprocess/ConfigPreprocessorComponentMapped';
import 'jest-rdf';
import { GenericsContext } from '../../../lib/preprocess/GenericsContext';
Expand Down Expand Up @@ -64,7 +63,7 @@ describe('ConfigPreprocessorComponentMapped', () => {
'@id': 'ex:myComponentInstance',
types: 'ex:Component',
});
const { module, component } = <IComponentConfigPreprocessorHandleResponse> preprocessor.canHandle(config);
const { module, component } = preprocessor.canHandle(config)!;
expect(module).toBe(componentResources['ex:Component'].property.module);
expect(component).toBe(componentResources['ex:Component']);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2897,12 +2897,10 @@ describe('ParameterPropertyHandlerRange', () => {

describe('rangeToDisplayString', () => {
it('handles undefined range', () => {
// eslint-disable-next-line unicorn/no-useless-undefined
expect(ParameterPropertyHandlerRange.rangeToDisplayString(undefined, genericsContext)).toEqual('any');
});

it('handles wildcard range', () => {
// eslint-disable-next-line unicorn/no-useless-undefined
expect(ParameterPropertyHandlerRange.rangeToDisplayString(objectLoader.createCompactedResource({
'@type': 'ParameterRangeWildcard',
}), genericsContext)).toEqual('any');
Expand Down
2 changes: 1 addition & 1 deletion test/unit/rdf/PrefetchedDocumentLoader-test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as fs from 'fs';
import { PrefetchedDocumentLoader } from '../../../lib/rdf/PrefetchedDocumentLoader';

global.fetch = <any>jest.fn(async() => ({
globalThis.fetch = <any>jest.fn(async() => ({
json: () => ({ x: 'y' }),
ok: true,
headers: new Headers({ 'Content-Type': 'application/ld+json' }),
Expand Down
2 changes: 1 addition & 1 deletion test/unit/rdf/RdfParser-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const quad = require('rdf-quad');
const stringifyStream = require('stream-to-string');
const streamifyString = require('streamify-string');

global.fetch = <any>jest.fn(async(url: string) => {
globalThis.fetch = <any>jest.fn(async(url: string) => {
if (url === 'http://example.org/myfile1.ttl') {
return {
body: streamifyString(`<ex:s1> <ex:p1> <ex:o1>.`),
Expand Down
2 changes: 1 addition & 1 deletion test/webpack/test-web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

// Monkey patch in the window object so we can test the script in Node
// @ts-expect-error
// eslint-disable-next-line no-undef
globalThis.window = globalThis;

import { RdfObjectLoader } from 'rdf-object';
Expand Down Expand Up @@ -32,3 +31,4 @@ try {
console.error(error);
process.exit(1);
}
/* eslint-enable no-console, unicorn/no-process-exit, @typescript-eslint/no-implicit-any-catch */
Loading