From f0de431c6bba42682f8d8612d10a3c46e6116d27 Mon Sep 17 00:00:00 2001 From: Pierre Brisorgueil Date: Thu, 12 Nov 2026 15:06:54 +0100 Subject: [PATCH 1/2] ci(typecheck): check JSDoc types with tsc in CI (part 1) Add tsconfig.check.json (explicit stack folders), pin typescript 5.9.3, add npm run typecheck and a CI step on the unit job after lint. Fix the JSDoc errors tsc reports; drop the dead helmet hsts force and aggregate noCursorTimeout options. One @ts-expect-error for the Stripe pinned apiVersion (documented by stripe-node). Closes pierreb-devkit/Node#4269 --- .github/workflows/CI.yml | 4 ++ README.md | 1 + lib/app.js | 2 +- lib/helpers/AppError.js | 31 ++++++++-------- lib/helpers/abilities.js | 2 +- lib/helpers/config.js | 10 ++--- lib/helpers/files.js | 4 +- lib/helpers/mailer/index.js | 2 +- lib/helpers/mailer/provider.nodemailer.js | 2 +- lib/helpers/mailer/provider.resend.js | 3 +- lib/helpers/responses.js | 5 ++- lib/middlewares/policy.js | 10 ++--- lib/middlewares/rateLimiter.js | 5 +-- lib/services/analytics.js | 6 +-- lib/services/distributedLock.js | 1 + lib/services/express.js | 3 +- lib/services/migrations.js | 2 +- lib/services/mongoose.js | 4 +- lib/services/multer.js | 8 ++-- .../audit/repositories/audit.repository.js | 1 + modules/audit/services/audit.service.js | 4 +- modules/billing/lib/billing.stripe-errors.js | 2 +- modules/billing/lib/stripe.js | 1 + .../core/repositories/migration.repository.js | 4 +- modules/home/repositories/home.repository.js | 2 +- .../organizations.membership.repository.js | 3 ++ .../repositories/organizations.repository.js | 3 ++ .../organizations.membership.service.js | 2 +- modules/tasks/models/tasks.model.mongoose.js | 6 +-- .../tasks/repositories/tasks.repository.js | 15 ++++---- .../repositories/uploads.repository.js | 19 ++++------ .../users/repositories/users.repository.js | 37 ++++++++++--------- modules/users/services/users.service.js | 4 +- package-lock.json | 4 +- package.json | 4 +- tsconfig.check.json | 14 +++++++ 36 files changed, 130 insertions(+), 100 deletions(-) create mode 100644 tsconfig.check.json diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index bc26584ca..1f08cbfb7 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -53,6 +53,10 @@ jobs: if: matrix.suite == 'unit' run: npm run lint + - name: Typecheck JSDoc (once on the unit job) + if: matrix.suite == 'unit' + run: npm run typecheck + - name: Run tests run: | case "${{ matrix.suite }}" in diff --git a/README.md b/README.md index 1e8463180..d3e8d781b 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,7 @@ Tests are organized per module in `modules/*/tests/`. In CI the test job runs as ```bash npm run lint # Check code quality (read-only) npm run lint:fix # Auto-fix code quality issues +npm run typecheck # Check JSDoc types with tsc (read-only, CI) npm run format # Format code with Prettier ``` diff --git a/lib/app.js b/lib/app.js index f2a96cb1c..3d3751940 100644 --- a/lib/app.js +++ b/lib/app.js @@ -30,7 +30,7 @@ const startMongoose = async () => { /** * Establish ExpressJS powered web server - * @return {object} app + * @return {Promise} app */ const startExpress = async () => { try { diff --git a/lib/helpers/AppError.js b/lib/helpers/AppError.js index b889a39c4..dc255e762 100644 --- a/lib/helpers/AppError.js +++ b/lib/helpers/AppError.js @@ -5,23 +5,22 @@ const AppErrorCodes = { serverError: 'SERVER_ERROR', }; -/** - * @desc Custom error class with Node + Express - * @param {String} message error - * @param {Object} options - * @param {*} [options.details] - structured/whitelisted or curated-internal data (see - * `lib/helpers/responses.js#getDescription` — its `details`-derived text is - * production-gated, issue #4059) - * @param {number} [options.status] - HTTP status code - * @param {string} [options.code] - stable domain error code - * @param {string} [options.description] - deliberately-authored, user-facing text a - * throw site chooses explicitly — NOT gated by `getDescription`'s production check - * (same precedence as an explicit `description` argument to `responses.error`; see - * that function's own doc comment). Use this for authored copy a real user should - * see in every environment; use `details` for internal/curated data instead. - */ - class AppError extends Error { + /** + * @desc Custom error class with Node + Express + * @param {String} message error + * @param {Object} [options] + * @param {*} [options.details] - structured/whitelisted or curated-internal data (see + * `lib/helpers/responses.js#getDescription` — its `details`-derived text is + * production-gated, issue #4059) + * @param {number} [options.status] - HTTP status code + * @param {string} [options.code] - stable domain error code + * @param {string} [options.description] - deliberately-authored, user-facing text a + * throw site chooses explicitly — NOT gated by `getDescription`'s production check + * (same precedence as an explicit `description` argument to `responses.error`; see + * that function's own doc comment). Use this for authored copy a real user should + * see in every environment; use `details` for internal/curated data instead. + */ constructor(message, { details, status, code, description } = {}) { super(message); // Set HTTP status code diff --git a/lib/helpers/abilities.js b/lib/helpers/abilities.js index 99c2520bc..4f2e6a52f 100644 --- a/lib/helpers/abilities.js +++ b/lib/helpers/abilities.js @@ -1,7 +1,7 @@ /** * Serialize CASL abilities to a JSON-safe array compatible with createMongoAbility(). * @param {import('@casl/ability').MongoAbility} ability - The CASL ability instance - * @returns {Array<{action: string, subject: string, conditions?: Object, inverted?: boolean}>} Array of serialized rules + * @returns {Array<{action: string|string[], subject: import('@casl/ability').SubjectType|import('@casl/ability').SubjectType[], conditions?: Object, inverted?: boolean}>} Array of serialized rules */ const serializeAbilities = (ability) => ability.rules.map((rule) => ({ diff --git a/lib/helpers/config.js b/lib/helpers/config.js index 5b32b8d39..2d531933d 100644 --- a/lib/helpers/config.js +++ b/lib/helpers/config.js @@ -24,18 +24,18 @@ const getGlobbedPaths = async (globPatterns, excludes) => { output = _.union(output, await getGlobbedPaths(globPattern, excludes)); } } else if (_.isString(globPatterns)) { - if (urlRegex.test(globPatterns)) { - output.push(globPatterns); + if (urlRegex.test(/** @type {string} */ (globPatterns))) { + output.push(/** @type {string} */ (globPatterns)); } else { - let files = glob.sync(globPatterns.replace(/\\/g, '/')); + let files = glob.sync(/** @type {string} */ (globPatterns).replace(/\\/g, '/')); if (excludes) { files = files.map((file) => { if (_.isArray(excludes)) { - excludes.forEach((exclude) => { + /** @type {string[]} */ (excludes).forEach((exclude) => { file = file.replace(exclude, ''); }); } else { - file = file.replace(excludes, ''); + file = file.replace(/** @type {string} */ (excludes), ''); } return file; }); diff --git a/lib/helpers/files.js b/lib/helpers/files.js index 76e240c73..50d6efe6a 100644 --- a/lib/helpers/files.js +++ b/lib/helpers/files.js @@ -5,8 +5,8 @@ import fs from 'fs'; /** * @desc readFile from path - * @param {String} file path - * @return {String} file + * @param {String} path - file path + * @return {Promise} file content */ const readFile = async (path) => new Promise((resolve, reject) => { diff --git a/lib/helpers/mailer/index.js b/lib/helpers/mailer/index.js index 700bc2d13..047cfdeb2 100644 --- a/lib/helpers/mailer/index.js +++ b/lib/helpers/mailer/index.js @@ -210,7 +210,7 @@ const render = async (key, params, { subject } = {}) => { * @param {Object} [mail.headers] - Custom headers (e.g. * `List-Unsubscribe`), forwarded to the provider as-is; absent means * today's behavior (no headers on the payload). - * @param {Array} [mail.attachments] - Optional attachments array + * @param {Object[]} [mail.attachments] - Optional attachments array * @param {string} mail.attachments[].filename - Attachment filename * @param {string|Buffer} mail.attachments[].content - Attachment content (string or Buffer) * @returns {Promise} The send result, or null if not configured diff --git a/lib/helpers/mailer/provider.nodemailer.js b/lib/helpers/mailer/provider.nodemailer.js index f5f888ff4..2e1c6b7f4 100644 --- a/lib/helpers/mailer/provider.nodemailer.js +++ b/lib/helpers/mailer/provider.nodemailer.js @@ -16,7 +16,7 @@ export default class NodemailerProvider { * payload (not sent as an empty/undefined field) when absent * @param {Object} [mail.headers] - Custom headers; omitted from the * payload when absent - * @param {Array} [mail.attachments] - Optional attachments + * @param {Object[]} [mail.attachments] - Optional attachments * @param {string} mail.attachments[].filename - Filename * @param {string|Buffer} mail.attachments[].content - Attachment content (string or Buffer) * @returns {Promise} Nodemailer send result diff --git a/lib/helpers/mailer/provider.resend.js b/lib/helpers/mailer/provider.resend.js index b8b84b49e..e54d8c542 100644 --- a/lib/helpers/mailer/provider.resend.js +++ b/lib/helpers/mailer/provider.resend.js @@ -5,7 +5,6 @@ export default class ResendProvider { * Create a Resend mail provider instance. * @param {Object} options - Resend provider options * @param {string} options.apiKey - Resend API key - * @returns {void} */ constructor(options) { if (!options?.apiKey) throw new Error('Resend provider requires an apiKey'); @@ -23,7 +22,7 @@ export default class ResendProvider { * payload (not sent as an empty/undefined field) when absent * @param {Object} [mail.headers] - Custom headers; omitted from the * payload when absent - * @param {Array} [mail.attachments] - Optional attachments + * @param {Object[]} [mail.attachments] - Optional attachments * @param {string} mail.attachments[].filename - Filename * @param {string|Buffer} mail.attachments[].content - Content (string or Buffer) * @returns {Promise} Resend API response data diff --git a/lib/helpers/responses.js b/lib/helpers/responses.js index c27492c31..749bb5ae2 100644 --- a/lib/helpers/responses.js +++ b/lib/helpers/responses.js @@ -6,7 +6,7 @@ import UNSAFE_KEYS from './unsafeKeys.js'; /** * @desc Function res success * @param {Object} res - Express response object - * @param {String} success message + * @param {String} message - success message * @return {Object} type, message and data */ const success = (res, message) => (data) => { @@ -283,7 +283,7 @@ const safeStringify = (value) => { * longer has to hand-write a title that must stay in sync with a dynamic * status. An explicit title is unchanged; the omitted-title fallback * changes from `error.message` to `STATUS_CODES[status]` (#4009). - * @param {string} description - Optional detailed error description + * @param {string} [description] - Optional detailed error description * @returns {Object} type, message, code, status, errorCode, description and (when * any whitelisted key was present) details */ @@ -304,6 +304,7 @@ const error = (res, httpStatus, message, description) => (error = {}) => { rawDetails = undefined; } const whitelistedDetails = pickWhitelistedDetails(rawDetails); + /** @type {{type: string, message: string, code: number, status: number, errorCode: string, description: string, details?: Object, error?: string}} */ const result = { type: 'error', // Explicit title wins (backward compatible with every existing call diff --git a/lib/middlewares/policy.js b/lib/middlewares/policy.js index 748bd0d68..d5122de2a 100644 --- a/lib/middlewares/policy.js +++ b/lib/middlewares/policy.js @@ -12,9 +12,9 @@ const methodToAction = { /** * Registry of ability builder functions discovered from module policy files. - * Each entry is { fn, guest } where fn(user, membership, { can, cannot }) is called - * for authenticated users and guest({ can, cannot }) is called for unauthenticated visitors. - * @type {Array<{fn?: Function, guest?: Function}>} + * Each entry is { abilities, guestAbilities } where abilities(user, membership, { can, cannot }) is called + * for authenticated users and guestAbilities({ can, cannot }) is called for unauthenticated visitors. + * @type {Array<{abilities?: Function, guestAbilities?: Function}>} */ const abilitiesRegistry = []; @@ -22,7 +22,7 @@ const abilitiesRegistry = []; * Registry of document-level subject resolvers. * Each entry maps a req property to a CASL subject type string. * Modules register themselves via registerDocumentSubject() during startup. - * @type {Array<{reqProperty: string, subjectType: string}>} + * @type {Array<{reqProperty: string, subjectType: string, guard?: Function}>} */ const documentSubjectRegistry = []; @@ -184,7 +184,7 @@ const resolveSubject = (req) => { * @param {Object} req - Express request object * @param {Object} res - Express response object * @param {Function} next - Express next middleware function - * @returns {void} + * @returns {Promise} */ const isAllowed = async (req, res, next) => { const action = methodToAction[req.method.toLowerCase()]; diff --git a/lib/middlewares/rateLimiter.js b/lib/middlewares/rateLimiter.js index b566a751c..99bb1be69 100644 --- a/lib/middlewares/rateLimiter.js +++ b/lib/middlewares/rateLimiter.js @@ -27,9 +27,8 @@ const defaultKeyGenerator = (req) => req.user?._id?.toString() || ipKeyGenerator /** * @desc Proxy that lazily creates rate-limit middleware for each named profile. * Returns the configured limiter or a passthrough when the profile is missing. - * @param {Object} target - Internal cache of created limiters - * @param {string|symbol} name - The rate-limit profile name to look up - * @returns {Function} Express middleware (rate limiter or passthrough) + * Each property read (e.g. `limiters.api`) yields an Express middleware. + * @type {Record} */ const limiters = new Proxy({}, { get(target, name) { diff --git a/lib/services/analytics.js b/lib/services/analytics.js index acdb91722..a4bc00247 100644 --- a/lib/services/analytics.js +++ b/lib/services/analytics.js @@ -67,9 +67,9 @@ const track = (distinctId, event, properties, groups) => { * 3. `req.posthogContext.source` (set by posthogContextMiddleware) * 4. `'system'` default * - * @param {Object} params - Event parameters - * @param {string} params.distinctId - User or anonymous identifier - * @param {string} params.event - Event name + * @param {Object} [params] - Event parameters + * @param {string} [params.distinctId] - User or anonymous identifier (no-op when missing) + * @param {string} [params.event] - Event name (no-op when missing) * @param {Object} [params.properties] - Additional event properties (win over defaults) * @param {import('express').Request} [params.req] - Optional Express request for context injection * @param {string} [params.source] - Explicit source override (wins over req + properties) diff --git a/lib/services/distributedLock.js b/lib/services/distributedLock.js index ba929d854..99dc3888c 100644 --- a/lib/services/distributedLock.js +++ b/lib/services/distributedLock.js @@ -31,6 +31,7 @@ const LockSchema = new mongoose.Schema( // MongoDB TTL index — auto-deletes expired docs so stale locks don't accumulate. LockSchema.index({ lockedUntil: 1 }, { expireAfterSeconds: 0 }); +/** @type {import('mongoose').Model<{_id: string, lockedAt: Date, lockedUntil: Date, holder: string}>} */ export const CronLock = mongoose.models.CronLock ?? mongoose.model('CronLock', LockSchema); /** diff --git a/lib/services/express.js b/lib/services/express.js index 632313a5d..f75db52f5 100644 --- a/lib/services/express.js +++ b/lib/services/express.js @@ -260,7 +260,6 @@ const initHelmetHeaders = (app) => { helmet.hsts({ maxAge: SIX_MONTHS, includeSubDomains: true, - force: true, }), ); app.disable('x-powered-by'); @@ -277,7 +276,7 @@ const initModulesClientRoutes = (app) => { * Configure the modules ACL policies via auto-discovery. * Each policy file exports named ability builder functions * that are registered with the central policy middleware. - * @returns {Promise} + * @type {(app?: import('express').Express) => Promise} */ const initModulesServerPolicies = async () => { const policyMod = await import('../middlewares/policy.js'); diff --git a/lib/services/migrations.js b/lib/services/migrations.js index 25eae28ba..51c0eaa6f 100644 --- a/lib/services/migrations.js +++ b/lib/services/migrations.js @@ -286,7 +286,7 @@ const runMigration = async (filePath, executed) => { * {@link claimMigration}; without it, concurrent runners can execute the same * migration twice. Delegates to the repository so the service layer never * touches Mongoose directly. - * @returns {Promise} Resolves once indexes have been synchronised. + * @returns {Promise} Names of indexes dropped during sync. */ const ensureMigrationIndexes = () => migrationRepository.syncIndexes(); diff --git a/lib/services/mongoose.js b/lib/services/mongoose.js index 27869339c..4c1440f1c 100644 --- a/lib/services/mongoose.js +++ b/lib/services/mongoose.js @@ -44,7 +44,7 @@ const INDEX_CONFLICT_CODE_NAMES = new Set(['IndexOptionsConflict', 'IndexKeySpec /** * @desc Whether an index-build rejection is a same-name conflict with a * pre-existing index (see {@link INDEX_CONFLICT_CODES}). - * @param {Error} err - rejection from `Model#init()` + * @param {Error & {code?: number, codeName?: string}} err - rejection from `Model#init()` * @returns {boolean} true when the error is an index-name conflict */ const isIndexConflictError = (err) => INDEX_CONFLICT_CODES.has(err?.code) || INDEX_CONFLICT_CODE_NAMES.has(err?.codeName); @@ -57,7 +57,7 @@ const isIndexConflictError = (err) => INDEX_CONFLICT_CODES.has(err?.code) || IND * throws: spec enumeration failures are logged and swallowed, since this runs * on a boot path that must proceed to the migration runner (#4004). * @param {string} modelName - name of the model whose index build conflicted - * @param {Error} err - the conflict rejection from `Model#init()` + * @param {Error & {code?: number, codeName?: string}} err - the conflict rejection from `Model#init()` * @returns {Promise} resolves once the conflict has been logged */ const logIndexConflict = async (modelName, err) => { diff --git a/lib/services/multer.js b/lib/services/multer.js index 73843e783..73f7e8e83 100644 --- a/lib/services/multer.js +++ b/lib/services/multer.js @@ -10,16 +10,19 @@ import gridfsService from './gridfs.js'; /** * @desc File filter * @param {Array} formats - array of accepted mimetype string - * @return {callback} + * @param {number} size - max accepted size in bytes + * @return {Function} multer fileFilter(req, file, cb) */ const fileFilter = (formats, size) => (req, file, cb) => { const fileSize = parseInt(req.headers['content-length'], 10); if (fileSize > size) { + /** @type {Error & {code?: string}} */ const err = new Error(`Only files lower than ${size / (1024 * 1024)}mo are allowed`); err.code = 'SERVICE_ERROR'; return cb(err, false); } if (!formats.includes(file.mimetype)) { + /** @type {Error & {code?: string}} */ const err = new Error(`Only ${formats} files allowed`); err.code = 'SERVICE_ERROR'; return cb(err, false); @@ -29,9 +32,8 @@ const fileFilter = (formats, size) => (req, file, cb) => { /** * @desc file upload middleware - * @param {String} name - key data name in form-data * @param {Object} config - multer config - * @return {callback} + * @return {Function} async Express middleware(req, res, next) */ const create = (config) => async (req, res, next) => { // condif diff --git a/modules/audit/repositories/audit.repository.js b/modules/audit/repositories/audit.repository.js index f7e81b134..56df53233 100644 --- a/modules/audit/repositories/audit.repository.js +++ b/modules/audit/repositories/audit.repository.js @@ -30,6 +30,7 @@ const validate = (data) => AuditSchema.AuditLog.safeParse(data); const create = (data) => { const parsed = validate(data); if (!parsed.success) { + /** @type {Error & {validationErrors?: Object}} */ const err = new Error('AuditLog validation failed'); err.validationErrors = parsed.error.flatten(); throw err; diff --git a/modules/audit/services/audit.service.js b/modules/audit/services/audit.service.js index bcd837028..003004d36 100644 --- a/modules/audit/services/audit.service.js +++ b/modules/audit/services/audit.service.js @@ -7,8 +7,8 @@ import AuditRepository from '../repositories/audit.repository.js'; /** * @function log * @description Record an audit log entry. No-op when audit is disabled. - * @param {Object} params - * @param {string} params.action - Action identifier (e.g. 'auth.login', 'billing.subscribe') + * @param {Object} [params] + * @param {string} [params.action] - Action identifier (no-op when missing) (e.g. 'auth.login', 'billing.subscribe') * @param {string} [params.userId] - ID of the acting user * @param {string} [params.organizationId] - ID of the organization context * @param {string} [params.ip] - IP address of the request diff --git a/modules/billing/lib/billing.stripe-errors.js b/modules/billing/lib/billing.stripe-errors.js index bf4d183d0..7502d7137 100644 --- a/modules/billing/lib/billing.stripe-errors.js +++ b/modules/billing/lib/billing.stripe-errors.js @@ -21,7 +21,7 @@ const NON_TRANSIENT_STRIPE_ERROR_CLASSES = new Set([ * retrying. StripeCardError (402) is intentionally excluded — some decline codes * (processing_error, issuer_unavailable) are transient. * - * @param {unknown} err + * @param {{type?: string, rawType?: string}|null|undefined} err - Stripe SDK error or raw API error object * @returns {boolean} */ export function isNonTransientStripeError(err) { diff --git a/modules/billing/lib/stripe.js b/modules/billing/lib/stripe.js index 7ad6d70c3..9a2b70e53 100644 --- a/modules/billing/lib/stripe.js +++ b/modules/billing/lib/stripe.js @@ -18,6 +18,7 @@ let stripeClient = null; const getStripe = () => { if (stripeClient) return stripeClient; if (!config.stripe?.secretKey) return null; + // @ts-expect-error stripe-node types only accept its latest apiVersion; pinning an older one is supported (stripe-node README) stripeClient = new Stripe(config.stripe.secretKey, { apiVersion: '2026-04-22.dahlia' }); return stripeClient; }; diff --git a/modules/core/repositories/migration.repository.js b/modules/core/repositories/migration.repository.js index 4e7a055a5..160480bb1 100644 --- a/modules/core/repositories/migration.repository.js +++ b/modules/core/repositories/migration.repository.js @@ -23,7 +23,9 @@ const syncIndexes = () => mongoose.model('Migration').syncIndexes(); * still `'running'` (#3992). * @returns {Promise>} Lean records with `name` + `status`. */ -const listExecuted = () => mongoose.model('Migration').find({}, { name: 1, status: 1, _id: 0 }).lean(); +const listExecuted = () => + /** @type {import('mongoose').Model<{name: string, status?: string}>} */ (mongoose.model('Migration')) + .find({}, { name: 1, status: 1, _id: 0 }).lean(); /** * @function listRunning diff --git a/modules/home/repositories/home.repository.js b/modules/home/repositories/home.repository.js index c062b03a6..0bfae2350 100644 --- a/modules/home/repositories/home.repository.js +++ b/modules/home/repositories/home.repository.js @@ -7,7 +7,7 @@ const User = mongoose.model('User'); /** * @desc Function to get all user in db - * @return {Array} All users + * @return {Promise>} All admin users */ const team = () => User.find({ roles: 'admin' }, 'firstName lastName bio position avatar -_id').lean().sort('-createdAt').exec(); diff --git a/modules/organizations/repositories/organizations.membership.repository.js b/modules/organizations/repositories/organizations.membership.repository.js index e9eefe16c..a2bc48ce0 100644 --- a/modules/organizations/repositories/organizations.membership.repository.js +++ b/modules/organizations/repositories/organizations.membership.repository.js @@ -4,6 +4,7 @@ import mongoose from 'mongoose'; import { MEMBERSHIP_STATUSES } from '../lib/constants.js'; +/** @type {import('mongoose').Model>} */ const Membership = mongoose.model('Membership'); const defaultPopulate = [ @@ -21,6 +22,8 @@ const defaultPopulate = [ * @function list * @description Data access operation to fetch all memberships matching a filter. * @param {Object} [filter] - Optional filter to apply to the query. + * @param {number} [page] - Zero-based page index (used with perPage). + * @param {number} [perPage] - Page size; no pagination when absent. * @returns {Promise} An array of memberships. */ const list = (filter, page, perPage) => { diff --git a/modules/organizations/repositories/organizations.repository.js b/modules/organizations/repositories/organizations.repository.js index 8a1918929..83f68bf4b 100644 --- a/modules/organizations/repositories/organizations.repository.js +++ b/modules/organizations/repositories/organizations.repository.js @@ -3,6 +3,7 @@ */ import mongoose from 'mongoose'; +/** @type {import('mongoose').Model>} */ const Organization = mongoose.model('Organization'); const defaultPopulate = [ @@ -16,6 +17,8 @@ const defaultPopulate = [ * @function list * @description Data access operation to fetch all organizations matching an optional filter. * @param {Object} [filter] - Optional filter to apply to the query. + * @param {number} [page] - Zero-based page index (used with perPage). + * @param {number} [perPage] - Page size; no pagination when absent. * @returns {Promise} An array of organizations. */ const list = (filter, page, perPage) => { diff --git a/modules/organizations/services/organizations.membership.service.js b/modules/organizations/services/organizations.membership.service.js index afa167e86..444d19cb2 100644 --- a/modules/organizations/services/organizations.membership.service.js +++ b/modules/organizations/services/organizations.membership.service.js @@ -361,7 +361,7 @@ const findUserByExactEmail = async (email) => { * @param {String} organizationId - The organization to add the user to. * @param {String} userId - The user being invited. * @param {String} [role] - The role to grant on acceptance (defaults to MEMBER). - * @param {String} addedBy - The id of the owner/admin performing the add (provenance). + * @param {String} [addedBy] - The id of the owner/admin performing the add (provenance). * @returns {Promise} The created PENDING owner_add membership. When the * mailer is configured, also notifies the invited user by email (invitation * wording — the membership awaits THEIR acceptance) with a link to their diff --git a/modules/tasks/models/tasks.model.mongoose.js b/modules/tasks/models/tasks.model.mongoose.js index a2d6a0154..fcd80f702 100644 --- a/modules/tasks/models/tasks.model.mongoose.js +++ b/modules/tasks/models/tasks.model.mongoose.js @@ -27,9 +27,9 @@ const TaskMongoose = new Schema( ); /** - * @desc Function to add id (+ _id) to all objects - * @param {Object} task - * @return {Object} Task + * @desc Virtual getter returning the document id as a hex string + * @this {import('mongoose').Document & {_id: import('mongoose').Types.ObjectId}} + * @return {string} id */ function addID() { return this._id.toHexString(); diff --git a/modules/tasks/repositories/tasks.repository.js b/modules/tasks/repositories/tasks.repository.js index 86f458a4a..e5ca94d45 100644 --- a/modules/tasks/repositories/tasks.repository.js +++ b/modules/tasks/repositories/tasks.repository.js @@ -3,6 +3,7 @@ */ import mongoose from 'mongoose'; +/** @type {import('mongoose').Model>} */ const Task = mongoose.model('Task'); const defaultPopulate = [ @@ -16,7 +17,7 @@ const defaultPopulate = [ * @function list * @description Data access operation to fetch all tasks from the database with an optional filter. * @param {Object} [filter] - Optional filter to apply to the query. - * @returns {Array} An array of tasks. + * @returns {Promise>} An array of tasks. */ const list = (filter) => Task.find(filter).populate(defaultPopulate).sort('-createdAt').exec(); @@ -24,7 +25,7 @@ const list = (filter) => Task.find(filter).populate(defaultPopulate).sort('-crea * @function create * @description Data access operation to create a new task in the database. * @param {Object} task - The task object to create. - * @returns {Object} The created task. + * @returns {Promise} The created task. */ const create = (task) => new Task(task).save().then((doc) => doc.populate(defaultPopulate)); @@ -32,7 +33,7 @@ const create = (task) => new Task(task).save().then((doc) => doc.populate(defaul * @function get * @description Data access operation to fetch a single task by its ID. * @param {String} id - The ID of the task to fetch. - * @returns {Object} The retrieved task or null if the ID is not valid. + * @returns {Promise|null} The retrieved task, or null if the ID is not valid. */ const get = (id) => { if (!mongoose.Types.ObjectId.isValid(id)) return null; @@ -43,7 +44,7 @@ const get = (id) => { * @function update * @description Data access operation to update an existing task in the database. * @param {import('mongoose').Document} task - The hydrated Mongoose Task document to update. Must support `.save()`. - * @returns {Object} The updated task. + * @returns {Promise} The updated task. */ const update = (task) => task.save().then((doc) => doc.populate(defaultPopulate)); @@ -51,7 +52,7 @@ const update = (task) => task.save().then((doc) => doc.populate(defaultPopulate) * @function remove * @description Data access operation to delete a single task by its ID. * @param {Object} task - The task object to delete. - * @returns {Object} A confirmation of the deletion. + * @returns {Promise} A confirmation of the deletion. */ const remove = (task) => Task.deleteOne({ _id: task.id }).exec(); @@ -59,7 +60,7 @@ const remove = (task) => Task.deleteOne({ _id: task.id }).exec(); * @function deleteMany * @description Data access operation to delete multiple tasks based on a filter. * @param {Object} filter - The filter to apply to the deletion query. - * @returns {Object} A confirmation of the deletion. + * @returns {Promise|undefined} A confirmation of the deletion, or undefined without a filter. */ const deleteMany = (filter) => { if (filter) return Task.deleteMany(filter).exec(); @@ -78,7 +79,7 @@ const stats = (filter = {}) => Task.countDocuments(filter).exec(); * @description Data access operation to update or insert multiple tasks in the database. * @param {Array} tasks - The array of task objects to update or insert. * @param {Array} filters - The array of property names to use as filters for the update. - * @returns {Object} The result of the bulkWrite operation. + * @returns {Promise} The result of the bulkWrite operation. */ const push = async (tasks, filters) => Task.bulkWrite( diff --git a/modules/uploads/repositories/uploads.repository.js b/modules/uploads/repositories/uploads.repository.js index 5f3220507..aa7d7ff1e 100644 --- a/modules/uploads/repositories/uploads.repository.js +++ b/modules/uploads/repositories/uploads.repository.js @@ -304,17 +304,10 @@ const purgeUnreferenced = async (kind, collection, paths, graceMs) => { }; const referenced = new Set(); - // `noCursorTimeout` — this streams the WHOLE collection at cron/batch - // scale, not request-path scale; without it, MongoDB closes an idle - // cursor after 10 minutes and a slow pass over a large `collection` fails - // mid-run with the counters accumulated so far lost. - const referenceCursor = mongoose.connection.db.collection(collection).aggregate( - [ - { $project: { _id: 0, refs: { $concatArrays: paths.map(toArrayExpr) } } }, - { $match: { 'refs.0': { $exists: true } } }, - ], - { noCursorTimeout: true }, - ); + const referenceCursor = mongoose.connection.db.collection(collection).aggregate([ + { $project: { _id: 0, refs: { $concatArrays: paths.map(toArrayExpr) } } }, + { $match: { 'refs.0': { $exists: true } } }, + ]); for await (const doc of referenceCursor) { for (const filename of doc.refs) { if (typeof filename === 'string') referenced.add(filename); @@ -328,6 +321,10 @@ const purgeUnreferenced = async (kind, collection, paths, graceMs) => { let deleteFailed = 0; let skippedTooYoung = 0; + // `noCursorTimeout` — this streams the WHOLE collection at cron/batch + // scale, not request-path scale; without it, MongoDB closes an idle + // cursor after 10 minutes and a slow pass over a large `collection` fails + // mid-run with the counters accumulated so far lost. const candidateCursor = Uploads.find({ 'metadata.kind': kind }, null, { noCursorTimeout: true }) .select('filename uploadDate') .lean() diff --git a/modules/users/repositories/users.repository.js b/modules/users/repositories/users.repository.js index b0c5815fa..77fd6eb55 100644 --- a/modules/users/repositories/users.repository.js +++ b/modules/users/repositories/users.repository.js @@ -23,14 +23,15 @@ const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); */ const normalizeEmail = (email) => (typeof email === 'string' ? email.toLowerCase().trim() : null); +/** @type {import('mongoose').Model>} */ const User = mongoose.model('User'); /** * @desc Function to get all user in db * @param {String} search - * @param {Int} page - * @param {Int} perPage - * @returns {Array} users selected + * @param {number} page + * @param {number} perPage + * @returns {Promise>} users selected */ const list = (search, page, perPage) => { const filter = search @@ -54,14 +55,14 @@ const list = (search, page, perPage) => { /** * @desc Function to create a user in db * @param {Object} user - * @returns {Object} user + * @returns {Promise} user */ const create = (user) => new User(user).save(); /** * @desc Function to get a user from db by id, email, or token * @param {Object} user - * @returns {Object} user + * @returns {Promise|undefined} user, or undefined when no lookup key is given */ const get = (user = {}) => { if (user.id && mongoose.Types.ObjectId.isValid(user.id)) return User.findOne({ _id: user.id }).exec(); @@ -90,15 +91,15 @@ const get = (user = {}) => { /** * @desc Function to get a search in db request - * @param {Object} mongoose input request - * @returns {Array} users + * @param {Object} input - mongoose filter + * @returns {Promise>} users */ const search = (input) => User.find(input).exec(); /** * @desc Function to update a user in db * @param {Object} user - * @returns {Object} user + * @returns {Promise} user */ const update = (user) => { if (user._id) { @@ -117,7 +118,7 @@ const update = (user) => { * token was already consumed, or a doc with no email (mirrors the previous * controller-level `!user.email` guard), matches no document and returns null. * @param {String} token - The raw emailVerificationToken from the verification link. - * @returns {Object|null} the updated user document, or null when the token is + * @returns {Promise} the updated user document, or null when the token is * missing, unknown, expired, already consumed, or the account has no email. */ const consumeEmailVerificationToken = (token) => { @@ -161,7 +162,7 @@ const setEmailPreference = (userId, kind, value) => { /** * @desc Function to remove a user from db by id or email * @param {Object} user - * @returns {Object} confirmation of delete + * @returns {Promise<{deletedCount: number}>} confirmation of delete */ const remove = async (user) => { if (user && user.id && mongoose.Types.ObjectId.isValid(user.id)) return User.deleteOne({ _id: user.id }).exec(); @@ -188,9 +189,9 @@ const count = (filter = {}) => User.countDocuments(filter).exec(); /** * @desc Function to push list of users in db - * @param {[Object]} users - * @param {[String]} filters - * @returns {Object} locations + * @param {Object[]} users + * @param {String[]} filters + * @returns {Promise} bulkWrite result */ const push = (users, filters) => { if (!Array.isArray(filters) || filters.length === 0) { @@ -220,7 +221,7 @@ const push = (users, filters) => { /** * @desc Function to search users by name or email with a regex * @param {String} search - The search string - * @returns {Array} matching user IDs + * @returns {Promise>} matching users (`_id` only) */ const searchByNameOrEmail = (search) => { const regex = new RegExp(escapeRegex(search), 'i'); @@ -244,7 +245,7 @@ const findByEmail = (email) => { * @desc Function to update a user by ID with a partial update object * @param {String} id - The user ID * @param {Object} data - Fields to update - * @returns {Object} update result + * @returns {Promise} update result */ const updateById = (id, data) => User.updateOne({ _id: id }, data, { runValidators: true }).exec(); @@ -253,7 +254,7 @@ const updateById = (id, data) => User.updateOne({ _id: id }, data, { runValidato * @param {String} id - The user ID * @param {Object} data - Fields to update * @param {String|Array|Object} populateFields - Fields to populate - * @returns {Object} updated user + * @returns {Promise} updated user */ const findByIdAndUpdatePopulated = (id, data, populateFields) => User.findByIdAndUpdate(id, data, { returnDocument: 'after', runValidators: true }).populate(populateFields).exec(); @@ -262,7 +263,7 @@ const findByIdAndUpdatePopulated = (id, data, populateFields) => * @desc Function to find users matching a filter with optional field selection * @param {Object} filter - Mongoose filter * @param {String} [select] - Fields to select - * @returns {Array} matching users + * @returns {Promise>} matching users */ const findWithFilter = (filter, select) => User.find(filter).select(select || '').exec(); @@ -296,7 +297,7 @@ const findPage = (filter, { afterId, limit = 200, select } = {}) => { * @desc Function to update multiple users matching a filter * @param {Object} filter - Mongoose filter * @param {Object} data - Fields to update - * @returns {Object} update result + * @returns {Promise} update result */ const updateMany = (filter, data) => User.updateMany(filter, data, { runValidators: true }).exec(); diff --git a/modules/users/services/users.service.js b/modules/users/services/users.service.js index 0f5d1214e..2ef42c361 100644 --- a/modules/users/services/users.service.js +++ b/modules/users/services/users.service.js @@ -35,8 +35,8 @@ const normalizeEmail = (email) => (typeof email === 'string' ? email.toLowerCase /** * @desc Function to get all users in db * @param {String} search - * @param {Int} page - * @param {Int} perPage + * @param {number} page + * @param {number} perPage * @returns {Promise} users selected */ const list = async (search, page, perPage) => { diff --git a/package-lock.json b/package-lock.json index c5e4cbe18..ea08960eb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -68,7 +68,8 @@ "prettier": "^3.9.10", "semantic-release": "^25.0.9", "supertest": "^7.3.2", - "ts-jest": "^29.4.15" + "ts-jest": "^29.4.15", + "typescript": "5.9.3" }, "engines": { "node": ">=26.0.0", @@ -20505,7 +20506,6 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/package.json b/package.json index 15f2d9b58..ce9a8babe 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "test:unit:coverage": "cross-env NODE_ENV=test NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=4096 --expose-gc\" jest --coverage --maxWorkers=2 --testPathPatterns='unit'", "test:integration:coverage": "cross-env NODE_ENV=test NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=4096 --expose-gc\" jest --coverage --maxWorkers=2 --testPathPatterns='integration'", "lint": "eslint ./modules ./lib ./config ./scripts", + "typecheck": "tsc -p tsconfig.check.json", "seed:dev": "cross-env NODE_ENV=development node scripts/seed.js seed", "seed:prod": "cross-env NODE_ENV=production node scripts/seed.js seed", "seed:user": "node scripts/seed.js seed:user", @@ -109,7 +110,8 @@ "prettier": "^3.9.10", "semantic-release": "^25.0.9", "supertest": "^7.3.2", - "ts-jest": "^29.4.15" + "ts-jest": "^29.4.15", + "typescript": "5.9.3" }, "release": { "branches": [ diff --git a/tsconfig.check.json b/tsconfig.check.json new file mode 100644 index 000000000..c584ca021 --- /dev/null +++ b/tsconfig.check.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "allowJs": true, + "checkJs": true, + "noEmit": true, + "strict": false, + "skipLibCheck": true, + "module": "nodenext", + "moduleResolution": "nodenext", + "target": "es2024" + }, + "include": ["lib", "config", "server.js", "modules/core", "modules/home", "modules/audit", "modules/public", "modules/tasks"], + "exclude": ["node_modules", "**/tests/**", "**/*.tests.js"] +} From 8ca7b4ae77f98e5fd7c9e393064960a19c558861 Mon Sep 17 00:00:00 2001 From: Pierre Brisorgueil Date: Thu, 12 Nov 2026 15:16:19 +0100 Subject: [PATCH 2/2] fix(core): make the last JSDoc type checks true Refs #4269 --- config/index.js | 2 +- lib/services/express.js | 4 ++-- lib/services/logger.js | 19 ++++++++++++++++--- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/config/index.js b/config/index.js index 5144177f6..fc04d94f8 100644 --- a/config/index.js +++ b/config/index.js @@ -154,7 +154,7 @@ const initGlobalConfig = async () => { config = deepMerge(config, environmentConfigVars); // read package.json for project information - const packageJSON = JSON.parse(readFileSync(path.resolve('./package.json'))); + const packageJSON = JSON.parse(readFileSync(path.resolve('./package.json'), 'utf8')); config = deepMerge(config, { package: packageJSON }); // Initialize global globbed files config = deepMerge(config, { files: await configHelper.initGlobalConfigFiles(assets) }); diff --git a/lib/services/express.js b/lib/services/express.js index f75db52f5..81ac86eee 100644 --- a/lib/services/express.js +++ b/lib/services/express.js @@ -276,7 +276,7 @@ const initModulesClientRoutes = (app) => { * Configure the modules ACL policies via auto-discovery. * Each policy file exports named ability builder functions * that are registered with the central policy middleware. - * @type {(app?: import('express').Express) => Promise} + * @returns {Promise} */ const initModulesServerPolicies = async () => { const policyMod = await import('../middlewares/policy.js'); @@ -396,7 +396,7 @@ const init = async () => { // Initialize Modules configuration await initModulesConfiguration(app); // Initialize modules server authorization policies - await initModulesServerPolicies(app); + await initModulesServerPolicies(); // Initialize modules server routes await initModulesServerRoutes(app); // Mount error tracker handler (PostHog Error Tracking) — must be after routes diff --git a/lib/services/logger.js b/lib/services/logger.js index 59fec26af..34f11ee94 100644 --- a/lib/services/logger.js +++ b/lib/services/logger.js @@ -19,11 +19,20 @@ const consoleFormat = useJson ? winston.format.combine(winston.format.timestamp(), winston.format.json()) : winston.format.combine(winston.format.colorize(), winston.format.simple()); +/** + * The winston logger plus the helpers this module attaches to it. + * @typedef {Omit & { + * stream: { write: (msg: string) => void }, + * getLogOptions: () => object | false, + * setupFileLogger: () => boolean, + * getMorganOptions: () => { stream: { write: (msg: string) => void } }, + * getLogFormat: () => string, + * }} AppLogger + */ + // Instantiating the default winston application logger with the Console // transport - -/* eslint new-cap: 0 */ -const logger = new winston.createLogger({ +const winstonLogger = winston.createLogger({ level: logLevel, transports: [ new winston.transports.Console({ @@ -39,6 +48,10 @@ const logger = new winston.createLogger({ exitOnError: false, }); +// The helpers below are attached after creation and `stream` is replaced, +// hence the cast through unknown. +const logger = /** @type {AppLogger} */ (/** @type {unknown} */ (winstonLogger)); + if (config?.analytics?.posthog?.errorTracking === true) { logger.add(new PostHogErrorTransport()); }