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

refactor: format build scripts using eslint #3401

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions scripts/adopters/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { resolve } = require('path');
const writeJSON = require('../utils/readAndWriteJson.js')
const writeJSON = require('../utils/readAndWriteJson.js');

module.exports = async function buildAdoptersList() {
writeJSON('config/adopters.yml',resolve(__dirname, '../../config', 'adopters.json'));
writeJSON('config/adopters.yml', resolve(__dirname, '../../config', 'adopters.json'));
};
98 changes: 53 additions & 45 deletions scripts/build-docs.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
const sortBy = require('lodash/sortBy')
const sortBy = require('lodash/sortBy');

function buildNavTree(navItems) {
try {
const tree = {
'welcome': {
item: { title: 'Welcome', weight: 0, isRootSection: true, isSection: true, rootSectionId: 'welcome', sectionWeight: 0, slug: '/docs' },
welcome: {
item: {
title: 'Welcome',
weight: 0,
isRootSection: true,
isSection: true,
rootSectionId: 'welcome',
sectionWeight: 0,
slug: '/docs'
},
children: {}
}
}
};

//first we make sure that list of items lists main section items and then sub sections, documents last
// first we make sure that list of items lists main section items and then sub sections, documents last
const sortedItems = sortBy(navItems, ['isRootSection', 'weight', 'isSection']);

sortedItems.forEach(item => {
//identify main sections
sortedItems.forEach((item) => {
// identify main sections
if (item.isRootSection) {
tree[item.rootSectionId] = { item, children: {} }
tree[item.rootSectionId] = { item, children: {} };
}

//identify subsections
// identify subsections
if (item.parent) {
if (!tree[item.parent]) {
throw new Error(`Parent section ${item.parent} not found for item ${item.title}`);
Expand All @@ -27,9 +36,12 @@ function buildNavTree(navItems) {

if (!item.isSection) {
if (item.sectionId) {
let section = tree[item.rootSectionId]?.children[item.sectionId];
const section = tree[item.rootSectionId]?.children[item.sectionId];
if (!section) {
tree[item.rootSectionId].children[item.sectionId] = { item, children: [] };
tree[item.rootSectionId].children[item.sectionId] = {
item,
children: []
};
}
tree[item.rootSectionId].children[item.sectionId].children.push(item);
} else {
Expand All @@ -51,7 +63,7 @@ function buildNavTree(navItems) {
return obj;
}, {});

//handling subsections
// handling subsections
if (allChildrenKeys.length > 1) {
for (const key of allChildrenKeys) {
if (allChildren[key].children) {
Expand All @@ -62,73 +74,70 @@ function buildNavTree(navItems) {

// point in slug for specification subgroup to the latest specification version
if (rootKey === 'reference' && key === 'specification') {
allChildren[key].item.href = allChildren[key].children.find(c => c.isPrerelease === undefined).slug;
allChildren[key].item.href = allChildren[key].children.find((c) => c.isPrerelease === undefined).slug;
}
}
}
}

return tree;

} catch (err) {
throw new Error(`Failed to build navigation tree: ${err.message}`);
}
}

// A recursion function, works on the logic of Depth First Search to traverse all the root and child posts of the
// A recursion function, works on the logic of Depth First Search to traverse all the root and child posts of the
// DocTree to get sequential order of the Doc Posts
const convertDocPosts = (docObject) => {
try {
let docsArray = []
let docsArray = [];
// certain entries in the DocPosts are either a parent to many posts or itself a post.
docsArray.push(docObject?.item || docObject)
docsArray.push(docObject?.item || docObject);
if (docObject.children) {
let children = docObject.children
const { children } = docObject;
Object.keys(children).forEach((child) => {
let docChildArray = convertDocPosts(children[child])
docsArray = [...docsArray, ...docChildArray]
})
const docChildArray = convertDocPosts(children[child]);
docsArray = [...docsArray, ...docChildArray];
});
}
return docsArray
}
catch (err) {
return docsArray;
} catch (err) {
throw new Error('Error in convertDocPosts:', err);
}
}

};

function addDocButtons(docPosts, treePosts) {
let structuredPosts = [];
let rootSections = [];
const rootSections = [];

try {
// Traversing the whole DocTree and storing each post inside them in sequential order
Object.keys(treePosts).forEach((rootElement) => {
structuredPosts.push(treePosts[rootElement].item);
if (treePosts[rootElement].children) {
let children = treePosts[rootElement].children;
const { children } = treePosts[rootElement];
Object.keys(children).forEach((child) => {
let docChildArray = convertDocPosts(children[child]);
const docChildArray = convertDocPosts(children[child]);
structuredPosts = [...structuredPosts, ...docChildArray];
});
}
});

// Appending the content of welcome page of Docs from the posts.json
structuredPosts[0] = docPosts.filter(p => p.slug === '/docs')[0];
structuredPosts[0] = docPosts.filter((p) => p.slug === '/docs')[0];

// Traversing the structuredPosts in order to add `nextPage` and `prevPage` details for each page
let countDocPages = structuredPosts.length;
const countDocPages = structuredPosts.length;
structuredPosts = structuredPosts.map((post, index) => {
// post item specifying the root Section or sub-section in the docs are excluded as
// they doesn't comprise any Doc Page or content to be shown in website.
// post item specifying the root Section or sub-section in the docs are excluded as
// they doesn't comprise any Doc Page or content to be shown in website.
if (post?.isRootSection || post?.isSection || index == 0) {
if (post?.isRootSection || index == 0)
rootSections.push(post.title)
return post
if (post?.isRootSection || index == 0) rootSections.push(post.title);
return post;
Comment on lines 134 to +135
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Use strict equality comparison

Replace loose equality (==) with strict equality (===) for more reliable comparisons.

-      if (post?.isRootSection || post?.isSection || index == 0) {
-        if (post?.isRootSection || index == 0) rootSections.push(post.title);
+      if (post?.isRootSection || post?.isSection || index === 0) {
+        if (post?.isRootSection || index === 0) rootSections.push(post.title);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (post?.isRootSection || post?.isSection || index == 0) {
if (post?.isRootSection || index == 0)
rootSections.push(post.title)
return post
if (post?.isRootSection || index == 0) rootSections.push(post.title);
if (post?.isRootSection || post?.isSection || index === 0) {
if (post?.isRootSection || index === 0) rootSections.push(post.title);
🧰 Tools
🪛 eslint

[error] 134-134: Expected '===' and instead saw '=='.

(eqeqeq)


[error] 135-135: Expected '===' and instead saw '=='.

(eqeqeq)

}

let nextPage = {}, prevPage = {}
let nextPage = {};
let prevPage = {};
let docPost = post;

// checks whether the next page for the current docPost item exists or not
Expand All @@ -139,14 +148,14 @@ function addDocButtons(docPosts, treePosts) {
nextPage = {
title: structuredPosts[index + 1].title,
href: structuredPosts[index + 1].slug
}
};
} else {
nextPage = {
title: `${structuredPosts[index + 1].title} - ${structuredPosts[index + 2].title}`,
href: structuredPosts[index + 2].slug
}
};
}
docPost = { ...docPost, nextPage }
docPost = { ...docPost, nextPage };
}

// checks whether the previous page for the current docPost item exists or not
Expand All @@ -157,8 +166,8 @@ function addDocButtons(docPosts, treePosts) {
prevPage = {
title: structuredPosts[index - 1].title,
href: structuredPosts[index - 1].slug
}
docPost = { ...docPost, prevPage }
};
docPost = { ...docPost, prevPage };
} else {
// additonal check for the first page of Docs so that it doesn't give any Segementation fault
if (index - 2 >= 0) {
Expand All @@ -172,11 +181,10 @@ function addDocButtons(docPosts, treePosts) {
}
return docPost;
});

} catch (err) {
throw new Error("An error occurred while adding doc buttons:", err);
throw new Error('An error occurred while adding doc buttons:', err);
}
return structuredPosts;
}

module.exports = { buildNavTree, addDocButtons, convertDocPosts }
module.exports = { buildNavTree, addDocButtons, convertDocPosts };
23 changes: 8 additions & 15 deletions scripts/build-meetings.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,31 +9,26 @@ async function buildMeetings(writePath) {
try {
auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/calendar'],
credentials: process.env.CALENDAR_SERVICE_ACCOUNT ? JSON.parse(process.env.CALENDAR_SERVICE_ACCOUNT) : undefined,
credentials: process.env.CALENDAR_SERVICE_ACCOUNT ? JSON.parse(process.env.CALENDAR_SERVICE_ACCOUNT) : undefined
});

calendar = google.calendar({ version: 'v3', auth });

} catch (err) {
throw new Error(`Authentication failed: ${err.message}`);
}

let eventsItems;

try {
//cron job runs this always on midnight
// cron job runs this always on midnight
const currentTime = new Date(Date.now()).toISOString();
const timeMin = new Date(
Date.parse(currentTime) - 100 * 24 * 60 * 60 * 1000
).toISOString();
const timeMax = new Date(
Date.parse(currentTime) + 30 * 24 * 60 * 60 * 1000
).toISOString();
const timeMin = new Date(Date.parse(currentTime) - 100 * 24 * 60 * 60 * 1000).toISOString();
const timeMax = new Date(Date.parse(currentTime) + 30 * 24 * 60 * 60 * 1000).toISOString();

const eventsList = await calendar.events.list({
calendarId: process.env.CALENDAR_ID,
timeMax: timeMax,
timeMin: timeMin,
timeMax,
timeMin
});

eventsItems = eventsList.data.items.map((e) => {
Expand All @@ -43,17 +38,15 @@ async function buildMeetings(writePath) {
url:
e.extendedProperties?.private &&
`https://github.com/asyncapi/community/issues/${e.extendedProperties.private.ISSUE_ID}`,
banner:
e.extendedProperties?.private && e.extendedProperties.private.BANNER,
date: new Date(e.start.dateTime),
banner: e.extendedProperties?.private && e.extendedProperties.private.BANNER,
date: new Date(e.start.dateTime)
Comment on lines +41 to +42
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add consistent optional chaining to prevent potential runtime errors.

The optional chaining is used inconsistently. While extendedProperties?.private is safely accessed, private.BANNER could throw an error if private is undefined.

-        banner: e.extendedProperties?.private && e.extendedProperties.private.BANNER,
+        banner: e.extendedProperties?.private?.BANNER,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
banner: e.extendedProperties?.private && e.extendedProperties.private.BANNER,
date: new Date(e.start.dateTime)
banner: e.extendedProperties?.private?.BANNER,
date: new Date(e.start.dateTime)
🧰 Tools
🪛 Biome

[error] 41-41: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

};
});

const eventsForHuman = JSON.stringify(eventsItems, null, ' ');
console.log('The following events got fetched', eventsForHuman);

writeFileSync(writePath, eventsForHuman);

} catch (err) {
throw new Error(`Failed to fetch or process events: ${err.message}`);
}
Expand Down
78 changes: 40 additions & 38 deletions scripts/build-newsroom-videos.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,51 @@ const { resolve } = require('path');
const fetch = require('node-fetch-2');

async function buildNewsroomVideos(writePath) {
try {
const response = await fetch('https://youtube.googleapis.com/youtube/v3/search?' + new URLSearchParams({
key: process.env.YOUTUBE_TOKEN,
part: 'snippet',
channelId: 'UCIz9zGwDLbrYQcDKVXdOstQ',
eventType: 'completed',
type: 'video',
order: 'Date',
maxResults: 5,
}));

if (!response.ok) {
throw new Error(`HTTP error! with status code: ${response.status}`);
}

const data = await response.json();
console.log(data);

if (!data.items || !Array.isArray(data.items)) {
throw new Error('Invalid data structure received from YouTube API');
}

const videoDataItems = data.items.map((video) => ({
image_url: video.snippet.thumbnails.high.url,
title: video.snippet.title,
description: video.snippet.description,
videoId: video.id.videoId,
}));

const videoData = JSON.stringify(videoDataItems, null, ' ');
console.log('The following are the Newsroom Youtube videos: ', videoData);

writeFileSync(writePath, videoData);

return videoData;
} catch (err) {
throw new Error(`Failed to build newsroom videos: ${err.message}`);
try {
const response = await fetch(
`https://youtube.googleapis.com/youtube/v3/search?${new URLSearchParams({
key: process.env.YOUTUBE_TOKEN,
part: 'snippet',
channelId: 'UCIz9zGwDLbrYQcDKVXdOstQ',
eventType: 'completed',
type: 'video',
order: 'Date',
maxResults: 5
})}`
);

if (!response.ok) {
throw new Error(`HTTP error! with status code: ${response.status}`);
}

const data = await response.json();
console.log(data);

if (!data.items || !Array.isArray(data.items)) {
throw new Error('Invalid data structure received from YouTube API');
}

const videoDataItems = data.items.map((video) => ({
image_url: video.snippet.thumbnails.high.url,
title: video.snippet.title,
description: video.snippet.description,
videoId: video.id.videoId
}));

const videoData = JSON.stringify(videoDataItems, null, ' ');
console.log('The following are the Newsroom Youtube videos: ', videoData);

writeFileSync(writePath, videoData);

return videoData;
} catch (err) {
throw new Error(`Failed to build newsroom videos: ${err.message}`);
}
}

/* istanbul ignore next */
if (require.main === module) {
buildNewsroomVideos(resolve(__dirname, '../config', 'newsroom_videos.json'))
buildNewsroomVideos(resolve(__dirname, '../config', 'newsroom_videos.json'));
}

module.exports = { buildNewsroomVideos };
2 changes: 1 addition & 1 deletion scripts/build-pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,4 @@ function copyAndRenameFiles(srcDir, targetDir) {

copyAndRenameFiles(SRC_DIR, TARGET_DIR);

module.exports = {copyAndRenameFiles,capitalizeJsxTags}
module.exports = { copyAndRenameFiles, capitalizeJsxTags };
Loading
Loading