A platform for community discussion. Free, open, simple.
DEV: Deprecate Ember native array extensions (#34394)
Sérgio Saquetimc7f6108e060e
diff --git a/app/assets/javascripts/discourse/app/app.js b/app/assets/javascripts/discourse/app/app.jsindex 67c377e91ec..e8d3d9e9e2d 100644--- a/app/assets/javascripts/discourse/app/app.js+++ b/app/assets/javascripts/discourse/app/app.js@@ -1,5 +1,5 @@-import "./array-shim";import "./setup-deprecation-workflow";+import "./array-shim";import "decorator-transforms/globals";import "./loader-shims";import "./discourse-common-loader-shims";diff --git a/app/assets/javascripts/discourse/app/array-shim.js b/app/assets/javascripts/discourse/app/array-shim.jsindex ecf120f3612..12db635aad2 100644--- a/app/assets/javascripts/discourse/app/array-shim.js+++ b/app/assets/javascripts/discourse/app/array-shim.js@@ -1,3 +1,115 @@import { NativeArray } from "@ember/array";+import deprecated, { withSilencedDeprecations } from "discourse/lib/deprecated";+import escapeRegExp from "discourse/lib/escape-regexp";+/**+ * Provides backward compatibility for Ember native array extensions that were deprecated and removed in Ember 6.0.+ *+ * This file shims the array extension methods previously added by Ember to the native Array prototype.+ *+ * It adds deprecation warnings for each method to help identify and track their usage in the codebase.+ *+ * This allows existing code to continue working while providing guidance for migration to native array methods or+ * TrackedArray alternatives.+ **/++const DEPRECATION_ID_PREFIX = "discourse.native-array-extensions";+const SILENCED_ARRAY_DEPRECATIONS = new RegExp(+ `^${escapeRegExp(DEPRECATION_ID_PREFIX)}\..+$`+);+const DEPRECATION_SINCE = "3.6.0.beta1-dev";++/**+ * Display a consistent deprecation warning for array extension usage.+ *+ * @param {string} name+ * @param {"method"|"getter"|"setter"} kind+ */+function warn(name, kind = "method") {+ const qualifiedName =+ kind === "method" ? `array.${name}` : `array["${name}"] ${kind}`;++ deprecated(+ `The ${qualifiedName} is a deprecated Ember native array extension. Use native array methods or a TrackedArray instead.`,+ {+ id: `${DEPRECATION_ID_PREFIX}.${name}`,+ since: DEPRECATION_SINCE,+ }+ );+}++/**+ * Checks if a method is a deprecated Ember native array extension+ *+ * @param {string} methodName - The name of the method to check+ * @returns {boolean} True if the method is deprecated, false otherwise+ */+function isDeprecatedMethod(methodName) {+ return (+ NativeArray._without.indexOf(methodName) === -1 &&+ Array.prototype[methodName] &&+ methodName !== "[]" // [] is a special case - a getter/setter property added by Ember's NativeArray+ );+}++/**+ * Wraps an Array.prototype method with a deprecation warning+ *+ * @param {string} methodName - The name of the method to deprecate+ */+function deprecateArrayMethod(methodName) {+ const original = Array.prototype[methodName];++ // eslint-disable-next-line no-extend-native+ Array.prototype[methodName] = function (...args) {+ warn(methodName);++ return withSilencedDeprecations(SILENCED_ARRAY_DEPRECATIONS, () =>+ original.apply(this, args)+ );+ };+}++/**+ * Wraps the special case '[]' property descriptor with deprecation warnings+ * for both getter and setter+ */+function wrapSquareBracketDescriptor() {+ const propertyName = "[]";+ const squareBracketDescriptor = Object.getOwnPropertyDescriptor(+ Array.prototype,+ propertyName+ );+ if (!squareBracketDescriptor) {+ return;+ }++ // eslint-disable-next-line no-extend-native+ Object.defineProperty(Array.prototype, propertyName, {+ get() {+ warn(propertyName, "getter");++ return withSilencedDeprecations(SILENCED_ARRAY_DEPRECATIONS, () =>+ squareBracketDescriptor.get.bind(this)()+ );+ },+ set(value) {+ warn(propertyName, "setter");++ withSilencedDeprecations(SILENCED_ARRAY_DEPRECATIONS, () => {+ squareBracketDescriptor.set.bind(this)(value);+ });+ },+ });+}++// Apply the shim to the native Array prototype to mantain compatibility with existing code.NativeArray.apply(Array.prototype, true);++// Wrap all applicable native array extension methods with deprecations+Array.from(NativeArray.keys())+ .filter(isDeprecatedMethod)+ .forEach((methodName) => deprecateArrayMethod(methodName));++// Apply the special-case wrapper+wrapSquareBracketDescriptor();diff --git a/app/assets/javascripts/discourse/app/deprecation-workflow.js b/app/assets/javascripts/discourse/app/deprecation-workflow.jsindex 67166ec66db..99a59f4fc8e 100644--- a/app/assets/javascripts/discourse/app/deprecation-workflow.js+++ b/app/assets/javascripts/discourse/app/deprecation-workflow.js@@ -1,4 +1,249 @@-const DEPRECATION_WORKFLOW = [+/**+ * Valid environment names for deprecation workflows.+ * @type {string[]}+ */+const VALID_ENVS = [+ "development",+ "qunit-test",+ "rails-test",+ "test",+ "production",+ "unset",+];++/**+ * Valid handler types specifically for Ember CLI workflows.+ * @type {string[]}+ */+const VALID_EMBER_CLI_WORKFLOW_HANDLERS = ["silence", "log", "throw"];++/**+ * Valid handler types for deprecation workflows.+ * @type {string[]}+ */+const VALID_HANDLERS = [...VALID_EMBER_CLI_WORKFLOW_HANDLERS, "counter"];++/**+ * Handles deprecation workflows in Discourse.+ * @class+ */+export class DiscourseDeprecationWorkflow {+ #environment;+ #workflows;+ #activeWorkflows;++ /**+ * Creates a new DiscourseDeprecationWorkflow instance.+ * @param {Object[]} workflows - Array of workflow configurations+ * @param {(string|string[])} workflows[].handler - Handler type(s) for the workflow+ * @param {(string|RegExp)} workflows[].matchId - ID or pattern to match deprecations+ * @param {(string|string[])} [workflows[].env] - Environment(s) where the workflow applies+ */+ constructor(workflows) {+ workflows.forEach((workflow) => {+ // validate the deprecation handlers+ workflow.handler ||= [];+ workflow.handler = Array.isArray(workflow.handler)+ ? workflow.handler+ : [workflow.handler];++ // throw an error if handler contains an item that is not in VALID_HANDLERS+ workflow.handler.forEach((handler) => {+ if (!VALID_HANDLERS.includes(handler)) {+ throw new Error(+ `Deprecation Workflow: \`handler\` ${handler} must be one of ${VALID_HANDLERS.join(", ")}`+ );+ }+ });++ // we also need to ensure that `log` and `silence` are not used together+ if (+ workflow.handler.includes("log") &&+ workflow.handler.includes("silence")+ ) {+ throw new Error(+ `Deprecation Workflow: \`handler\` ${workflow.handler} must not include both \`log\` and \`silence\``+ );+ }++ // validate the deprecation matchIds+ if (+ typeof workflow.matchId !== "string" &&+ !(workflow.matchId instanceof RegExp)+ ) {+ throw new Error(+ `Deprecation Workflow: \`matchId\` ${workflow.matchId} must be a string or a regex`+ );+ }++ // validate the deprecation envs+ workflow.env ||= [];+ workflow.env = Array.isArray(workflow.env)+ ? workflow.env+ : [workflow.env];++ // throw an error if env contains an item that is not in VALID_ENVS+ workflow.env.forEach((env) => {+ if (!VALID_ENVS.includes(env)) {+ throw new Error(+ `Deprecation Workflow: \`env\` ${env} must be one of ${VALID_ENVS.join(", ")}`+ );+ }+ });+ });++ this.#workflows = workflows;+ this.#updateActiveWorkflows();+ }++ /**+ * Gets the list of active workflows.+ * @return {Object[]} Array of active workflow configurations+ */+ get list() {+ return this.#activeWorkflows;+ }++ /**+ * Gets Ember-specific workflows formatted for Ember CLI.+ * @return {Object[]} Array of formatted Ember workflow configurations+ */+ get emberWorkflowList() {+ return this.#activeWorkflows+ .flatMap((workflow) => {+ return workflow.handler.map((handler) => ({+ matchId: workflow.matchId,+ handler,+ env: workflow.env,+ }));+ })+ .filter((workflow) =>+ VALID_EMBER_CLI_WORKFLOW_HANDLERS.includes(workflow.handler)+ );+ }++ /**+ * Sets the current environment and updates active workflows.+ * @param {Object} environment - Environment object+ */+ setEnvironment(environment) {+ this.#environment = environment;+ this.#updateActiveWorkflows();+ }++ /**+ * Checks if a deprecation should be logged.+ * @param {string} deprecationId - ID of the deprecation+ * @return {boolean} True if deprecation should be logged+ */+ shouldLog(deprecationId) {+ const workflow = this.#find(deprecationId);+ return !workflow || workflow.handler.includes("log");+ }++ /**+ * Checks if a deprecation should be silenced.+ * @param {string} deprecationId - ID of the deprecation+ * @return {boolean} True if deprecation should be silenced+ */+ shouldSilence(deprecationId) {+ const workflow = this.#find(deprecationId);+ return !!workflow?.handler?.includes("silence");+ }++ /**+ * Checks if a deprecation should be counted.+ * @param {string} deprecationId - ID of the deprecation+ * @return {boolean} True if deprecation should be counted+ */+ shouldCount(deprecationId) {+ const workflow = this.#find(deprecationId);+ if (!workflow) {+ return true;+ }++ const silenced = workflow.handler?.includes("silence") ?? false;+ const count = workflow.handler?.includes("counter") ?? false;++ return !silenced || count;+ }++ /**+ * Checks if a deprecation should throw an error.+ * @param {string} deprecationId - ID of the deprecation+ * @param {boolean} [includeUnhandled=false] - Whether to throw for unhandled deprecations+ * @return {boolean} True if deprecation should throw+ */+ shouldThrow(deprecationId, includeUnhandled = false) {+ const workflow = this.#find(deprecationId);+ return (+ (!workflow && includeUnhandled) || !!workflow?.handler?.includes("throw")+ );+ }++ /**+ * Finds the workflow matching a deprecation ID.+ * @param {string} deprecationId - ID of the deprecation+ * @return {Object|undefined} Matching workflow configuration if found+ * @private+ */+ #find(deprecationId) {+ return this.#activeWorkflows.find((workflow) => {+ if (workflow.matchId instanceof RegExp) {+ return workflow.matchId.test(deprecationId);+ }++ return workflow.matchId === deprecationId;+ });+ }++ /**+ * Updates the list of active workflows based on current environment.+ * @private+ */+ #updateActiveWorkflows() {+ const environment = this.#environment;++ this.#activeWorkflows = this.#workflows.filter((workflow) => {+ let targetEnvs = workflow.env;++ if (targetEnvs.length === 0) {+ return true;+ }++ if (!environment) {+ return targetEnvs.includes("unset");+ }++ if (environment.isProduction()) {+ return targetEnvs.includes("production");+ }++ if (environment.isTesting()) {+ return targetEnvs.includes("qunit-test") || targetEnvs.includes("test");+ }++ if (environment.isRailsTesting()) {+ return targetEnvs.includes("rails-test") || targetEnvs.includes("test");+ }++ return targetEnvs.includes("development");+ });+ }+}++/**+ * Singleton DiscourseDeprecationWorkflow instance containing the current deprecation handling rules+ *+ * IMPORTANT: The first match wins, so the order of the workflows is relevant.+ *+ * Each workflow config item should have:+ * @property {(string|string[])} handler - Handler type(s): "silence", "log", "throw", and/or "counter"+ * @property {(string|RegExp)} matchId - ID or pattern to match deprecations+ * @property {(string|string[])} [env] - Optional environment(s): "development", "qunit-test", "rails-test", "test", "production", "unset"+ *+ */+const DeprecationWorkflow = new DiscourseDeprecationWorkflow([{ handler: "silence", matchId: "template-action" }, // will be removed in Ember 6.0{ handler: "silence", matchId: "discourse.select-kit" },{@@ -9,6 +254,16 @@ const DEPRECATION_WORKFLOW = [handler: "silence",matchId: "deprecate-import-meta-from-ember",},-];+ {+ handler: ["silence", "counter"],+ matchId: /^discourse\.native-array-extensions\..+$/,+ env: ["test"],+ },+ {+ handler: "silence",+ matchId: /^discourse\.native-array-extensions\..+$/,+ env: ["development", "production"],+ },+]);-export default DEPRECATION_WORKFLOW;+export default DeprecationWorkflow;diff --git a/app/assets/javascripts/discourse/app/initializers/discourse-bootstrap.js b/app/assets/javascripts/discourse/app/initializers/discourse-bootstrap.jsindex 71eb3cf706e..09c0cf539bf 100644--- a/app/assets/javascripts/discourse/app/initializers/discourse-bootstrap.js+++ b/app/assets/javascripts/discourse/app/initializers/discourse-bootstrap.js@@ -1,10 +1,6 @@import RSVP from "rsvp";-import {- isDevelopment,- isProduction,- isTesting,- setEnvironment,-} from "discourse/lib/environment";+import DeprecationWorkflow from "discourse/deprecation-workflow";+import * as environment from "discourse/lib/environment";import { setDefaultOwner } from "discourse/lib/get-owner";import { setupS3CDN, setupURL } from "discourse/lib/get-url";import { setIconList } from "discourse/lib/icon-library";@@ -16,6 +12,9 @@ import I18n from "discourse-i18n";export default {// The very first initializer to runinitialize(app) {+ const { isDevelopment, isProduction, isTesting, setEnvironment } =+ environment;+setURLContainer(app.__container__);setDefaultOwner(app.__container__);@@ -52,6 +51,8 @@ export default {setupURL(setupData.cdn, setupData.baseUrl, setupData.baseUri);setEnvironment(setupData.environment);+ DeprecationWorkflow.setEnvironment(environment);+I18n.defaultLocale = setupData.defaultLocale;window.Logster = window.Logster || {};diff --git a/app/assets/javascripts/discourse/app/lib/deprecated.js b/app/assets/javascripts/discourse/app/lib/deprecated.jsindex f17094d57a7..5e49c663f4d 100644--- a/app/assets/javascripts/discourse/app/lib/deprecated.js+++ b/app/assets/javascripts/discourse/app/lib/deprecated.js@@ -1,7 +1,7 @@-import DEPRECATION_WORKFLOW from "../deprecation-workflow";+import DeprecationWorkflow from "../deprecation-workflow";const handlers = [];-const disabledDeprecations = new Set();+const disabledDeprecations = [];let emberDeprecationSilencer;@@ -19,7 +19,7 @@ let emberDeprecationSilencer;export default function deprecated(msg, options = {}) {const { id, since, dropFrom, url, raiseError, source } = options;- if (id && disabledDeprecations.has(id)) {+ if (isDeprecationSilenced(id)) {return;}@@ -48,17 +48,17 @@ export default function deprecated(msg, options = {}) {handlers.forEach((h) => h(msg, options));- const matchedWorkflow = DEPRECATION_WORKFLOW.find((w) => w.matchId === id);-if (raiseError ||- matchedWorkflow?.handler === "throw" ||- (!matchedWorkflow && globalThis.EmberENV?.RAISE_ON_DEPRECATION)+ DeprecationWorkflow.shouldThrow(+ id,+ globalThis.EmberENV?.RAISE_ON_DEPRECATION+ )) {throw msg;}- if (matchedWorkflow?.handler !== "silence") {+ if (!DeprecationWorkflow.shouldSilence(id)) {console.warn(...[consolePrefix, msg].filter(Boolean)); //eslint-disable-line no-console}}@@ -73,14 +73,14 @@ export function registerDeprecationHandler(callback) {/*** Silence one or more deprecations while running `callback`- * @param {(string|string[])} deprecationIds A single id, or an array of ids, of deprecations to silence+ * @param {(string|RegExp|Array<string|RegExp>)} deprecationIds A single id, regex pattern, or an array containing a mix of ids and regex patterns to silence* @param {function} callback The function to call while deprecations are silenced.*/export function withSilencedDeprecations(deprecationIds, callback) {ensureEmberDeprecationSilencer();const idArray = [].concat(deprecationIds);try {- idArray.forEach((id) => disabledDeprecations.add(id));+ idArray.forEach((id) => disabledDeprecations.push(id));const result = callback();if (result instanceof Promise) {throw new Error(@@ -89,24 +89,24 @@ export function withSilencedDeprecations(deprecationIds, callback) {}return result;} finally {- idArray.forEach((id) => disabledDeprecations.delete(id));+ idArray.forEach(() => disabledDeprecations.pop());}}/*** Silence one or more deprecations while running an async `callback`* @async- * @param {(string|string[])} deprecationIds A single id, or an array of ids, of deprecations to silence+ * @param {(string|RegExp|Array<string|RegExp>)} deprecationIds A single id, regex pattern, or an array containing a mix of ids and regex patterns to silence* @param {function} callback The asynchronous function to call while deprecations are silenced.*/export async function withSilencedDeprecationsAsync(deprecationIds, callback) {ensureEmberDeprecationSilencer();const idArray = [].concat(deprecationIds);try {- idArray.forEach((id) => disabledDeprecations.add(id));+ idArray.forEach((id) => disabledDeprecations.push(id));return await callback();} finally {- idArray.forEach((id) => disabledDeprecations.delete(id));+ idArray.forEach(() => disabledDeprecations.pop());}}@@ -116,7 +116,17 @@ export async function withSilencedDeprecationsAsync(deprecationIds, callback) {* @returns {boolean} True if the deprecation is silenced, false otherwise*/export function isDeprecationSilenced(id) {- return id && disabledDeprecations.has(id);+ return (+ id &&+ disabledDeprecations.length &&+ disabledDeprecations.find((disabledId) => {+ if (disabledId instanceof RegExp) {+ return disabledId.test(id);+ }++ return disabledId === id;+ })+ );}function ensureEmberDeprecationSilencer() {@@ -125,9 +135,7 @@ function ensureEmberDeprecationSilencer() {}emberDeprecationSilencer = (message, options, next) => {- if (options?.id && disabledDeprecations.has(options.id)) {- return;- } else {+ if (!isDeprecationSilenced(options?.id)) {next(message, options);}};diff --git a/app/assets/javascripts/discourse/app/lib/source-identifier.js b/app/assets/javascripts/discourse/app/lib/source-identifier.jsindex 88cd4d3495a..a1f6461d0f6 100644--- a/app/assets/javascripts/discourse/app/lib/source-identifier.js+++ b/app/assets/javascripts/discourse/app/lib/source-identifier.js@@ -28,7 +28,7 @@ export default function identifySource(error) {"");- if (BROWSER_EXTENSION_PROTOCOLS.any((p) => stack.includes(p))) {+ if (BROWSER_EXTENSION_PROTOCOLS.some((p) => stack.includes(p))) {return {type: "browser-extension",};diff --git a/app/assets/javascripts/discourse/app/services/deprecation-warning-handler.js b/app/assets/javascripts/discourse/app/services/deprecation-warning-handler.jsindex 66d33022324..1eef063b798 100644--- a/app/assets/javascripts/discourse/app/services/deprecation-warning-handler.js+++ b/app/assets/javascripts/discourse/app/services/deprecation-warning-handler.js@@ -2,7 +2,7 @@ import { DEBUG } from "@glimmer/env";import { registerDeprecationHandler } from "@ember/debug";import Service, { service } from "@ember/service";import { addGlobalNotice } from "discourse/components/global-notice";-import DEPRECATION_WORKFLOW from "discourse/deprecation-workflow";+import DeprecationWorkflow from "discourse/deprecation-workflow";import { bind } from "discourse/lib/decorators";import { registerDeprecationHandler as registerDiscourseDeprecationHandler } from "discourse/lib/deprecated";import identifySource from "discourse/lib/source-identifier";@@ -71,11 +71,7 @@ export default class DeprecationWarningHandler extends Service {@bindhandle(message, opts) {- const matchingConfig = DEPRECATION_WORKFLOW.find(- (config) => config.matchId === opts.id- );-- if (matchingConfig?.handler === "silence") {+ if (DeprecationWorkflow.shouldSilence(opts.id)) {return;}diff --git a/app/assets/javascripts/discourse/app/setup-deprecation-workflow.js b/app/assets/javascripts/discourse/app/setup-deprecation-workflow.jsindex 01b5af2960e..2eefb81ac35 100644--- a/app/assets/javascripts/discourse/app/setup-deprecation-workflow.js+++ b/app/assets/javascripts/discourse/app/setup-deprecation-workflow.js@@ -1,4 +1,4 @@import setupDeprecationWorkflow from "ember-cli-deprecation-workflow";-import DEPRECATION_WORKFLOW from "./deprecation-workflow";+import DeprecationWorkflow from "./deprecation-workflow";-setupDeprecationWorkflow({ workflow: DEPRECATION_WORKFLOW });+setupDeprecationWorkflow({ workflow: DeprecationWorkflow.emberWorkflowList });diff --git a/app/assets/javascripts/discourse/public/assets/scripts/discourse-test-listen-boot.js b/app/assets/javascripts/discourse/public/assets/scripts/discourse-test-listen-boot.jsindex 2027f3163bc..079bcf71711 100644--- a/app/assets/javascripts/discourse/public/assets/scripts/discourse-test-listen-boot.js+++ b/app/assets/javascripts/discourse/public/assets/scripts/discourse-test-listen-boot.js@@ -1,2 +1,6 @@-require("discourse/lib/environment").setEnvironment("qunit-testing");+const environment = require("discourse/lib/environment");++environment.setEnvironment("qunit-testing");+require("discourse/deprecation-workflow").default.setEnvironment(environment);+require("discourse/tests/test-boot-ember-cli");diff --git a/app/assets/javascripts/discourse/tests/helpers/deprecation-counter.js b/app/assets/javascripts/discourse/tests/helpers/deprecation-counter.jsindex 21e0a800126..537c700255c 100644--- a/app/assets/javascripts/discourse/tests/helpers/deprecation-counter.js+++ b/app/assets/javascripts/discourse/tests/helpers/deprecation-counter.js@@ -1,30 +1,29 @@import { registerDeprecationHandler } from "@ember/debug";-import DEPRECATION_WORKFLOW from "discourse/deprecation-workflow";+import DeprecationWorkflow from "discourse/deprecation-workflow";import { bind } from "discourse/lib/decorators";-import { registerDeprecationHandler as registerDiscourseDeprecationHandler } from "discourse/lib/deprecated";+import {+ isDeprecationSilenced,+ registerDeprecationHandler as registerDiscourseDeprecationHandler,+} from "discourse/lib/deprecated";export default class DeprecationCounter {counts = new Map();- #configById = new Map();-- constructor(config) {- for (const c of config) {- this.#configById.set(c.matchId, c.handler);- }- }start() {registerDeprecationHandler(this.handleEmberDeprecation);registerDiscourseDeprecationHandler(this.handleDiscourseDeprecation);}+ shouldCount(id) {+ return !isDeprecationSilenced(id) && DeprecationWorkflow.shouldCount(id);+ }+@bindhandleEmberDeprecation(message, options, next) {const { id } = options;- const matchingConfig = this.#configById.get(id);- if (matchingConfig !== "silence") {- this.incrementDeprecation(id);+ if (this.shouldCount(id)) {+ this.incrementCount(id);}next(message, options);@@ -32,21 +31,18 @@ export default class DeprecationCounter {@bindhandleDiscourseDeprecation(message, options) {- let { id } = options;- id ||= "discourse.(unknown)";-- const matchingConfig = this.#configById.get(id);+ const id = options?.id || "discourse.(unknown)";- if (matchingConfig !== "silence") {- this.incrementDeprecation(id);+ if (this.shouldCount(id)) {+ this.incrementCount(id);}}- incrementDeprecation(id) {+ incrementCount(id) {const existingCount = this.counts.get(id) || 0;this.counts.set(id, existingCount + 1);if (window.Testem) {- reportToTestem(id);+ reportDeprecationToTestem(id);}}@@ -55,23 +51,33 @@ export default class DeprecationCounter {}generateTable() {+ const idColumn = "id";+ const countColumn = "count";+const maxIdLength = Math.max(- ...Array.from(this.counts.keys()).map((k) => k.length)+ ...Array.from(this.counts.keys())+ .concat(idColumn)+ .map((k) => k.length));- let msg = `| ${"id".padEnd(maxIdLength)} | count |\n`;- msg += `| ${"".padEnd(maxIdLength, "-")} | ----- |\n`;+ let msg = `| ${idColumn.padEnd(maxIdLength)} | ${countColumn} |\n`;+ msg += `| ${"".padEnd(maxIdLength, "-")} | -------- |\n`;- for (const [id, count] of this.counts.entries()) {+ for (const [id, count] of Array.from(this.counts.entries()).sort(+ ([id1], [id2]) => {+ // sort id alphabetically+ return id1.localeCompare(id2);+ }+ )) {const countString = count.toString();- msg += `| ${id.padEnd(maxIdLength)} | ${countString.padStart(5)} |\n`;+ msg += `| ${id.padEnd(maxIdLength)} | ${countString.padStart(8)} |\n`;}return msg;}}-function reportToTestem(id) {+function reportDeprecationToTestem(id) {window.Testem.useCustomAdapter(function (socket) {socket.emit("test-metadata", "increment-deprecation", {id,@@ -80,7 +86,7 @@ function reportToTestem(id) {}export function setupDeprecationCounter(qunit) {- const deprecationCounter = new DeprecationCounter(DEPRECATION_WORKFLOW);+ const deprecationCounter = new DeprecationCounter();qunit.begin(() => deprecationCounter.start());diff --git a/app/assets/javascripts/discourse/tests/helpers/raise-on-deprecation.js b/app/assets/javascripts/discourse/tests/helpers/raise-on-deprecation.jsindex 83f84ff840f..2a2e8aac71c 100644--- a/app/assets/javascripts/discourse/tests/helpers/raise-on-deprecation.js+++ b/app/assets/javascripts/discourse/tests/helpers/raise-on-deprecation.js@@ -1,6 +1,6 @@import { registerDeprecationHandler } from "@ember/debug";import QUnit from "qunit";-import DEPRECATION_WORKFLOW from "discourse/deprecation-workflow";+import DeprecationWorkflow from "discourse/deprecation-workflow";import { registerDeprecationHandler as registerDiscourseDeprecationHandler } from "discourse/lib/deprecated";let disabled = false;@@ -13,7 +13,8 @@ export function configureRaiseOnDeprecation() {registerDeprecationHandler((message, options, next) => {if (disabled ||- DEPRECATION_WORKFLOW.find((w) => w.matchId === options.id)+ !DeprecationWorkflow.shouldThrow(options.id) ||+ options.id.startsWith("ember-metal.")) {return next(message, options);}@@ -21,10 +22,7 @@ export function configureRaiseOnDeprecation() {});registerDiscourseDeprecationHandler((message, options) => {- if (- disabled ||- DEPRECATION_WORKFLOW.find((w) => w.matchId === options?.id)- ) {+ if (disabled || !DeprecationWorkflow.shouldThrow(options?.id)) {return;}raiseDeprecationError(message, options);diff --git a/app/assets/javascripts/discourse/tests/setup-tests.js b/app/assets/javascripts/discourse/tests/setup-tests.jsindex ddcf4e110e2..8f01457e3ac 100644--- a/app/assets/javascripts/discourse/tests/setup-tests.js+++ b/app/assets/javascripts/discourse/tests/setup-tests.js@@ -105,10 +105,15 @@ function createApplication(config, settings) {function setupToolbar() {// Most default toolbar items aren't useful for Discourse- QUnit.config.urlConfig = QUnit.config.urlConfig.reject((c) =>- ["noglobals", "nolint", "devmode", "dockcontainer", "nocontainer"].includes(- c.id- )+ QUnit.config.urlConfig = QUnit.config.urlConfig.filter(+ (c) =>+ ![+ "noglobals",+ "nolint",+ "devmode",+ "dockcontainer",+ "nocontainer",+ ].includes(c.id));const pluginNames = new Set();diff --git a/app/assets/javascripts/discourse/tests/unit/deprecation-workflow-test.js b/app/assets/javascripts/discourse/tests/unit/deprecation-workflow-test.jsnew file mode 100644index 00000000000..83a1c5e3df7--- /dev/null+++ b/app/assets/javascripts/discourse/tests/unit/deprecation-workflow-test.js@@ -0,0 +1,346 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import { DiscourseDeprecationWorkflow } from "discourse/deprecation-workflow";++module("Unit | deprecation-workflow", function (hooks) {+ setupTest(hooks);++ function makeEnv({+ production = false,+ testing = false,+ railsTesting = false,+ } = {}) {+ return {+ isProduction() {+ return production;+ },+ isTesting() {+ return testing;+ },+ isRailsTesting() {+ return railsTesting;+ },+ };+ }++ module("constructor validations", function () {+ test("validates matchId types", function (assert) {+ assert.throws(+ () =>+ new DiscourseDeprecationWorkflow([+ { handler: "silence", matchId: 123 },+ ]),+ /matchId.*must be a string or a regex/,+ "throws when matchId is not string or RegExp"+ );++ assert.throws(+ () =>+ new DiscourseDeprecationWorkflow([+ { handler: "silence", matchId: { bad: true } },+ ]),+ /matchId.*must be a string or a regex/,+ "throws when matchId is an object"+ );+ });++ test("normalizes env and validates allowed values", function (assert) {+ // env as string should be accepted (normalized to array)+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "silence", matchId: "x", env: "production" },+ ]);+ assert.strictEqual(+ wf.list.length,+ 0,+ "no environment set so production-only is not active"+ );++ // invalid env should throw+ assert.throws(+ () =>+ new DiscourseDeprecationWorkflow([+ { handler: "silence", matchId: "y", env: "staging" },+ ]),+ /env.*must be one of/,+ "throws on invalid env value"+ );+ });++ test("normalizes handler array and validates allowed handlers and combinations", function (assert) {+ // handler as string -> normalized to array on list+ const wf1 = new DiscourseDeprecationWorkflow([+ { handler: "silence", matchId: "one" },+ ]);+ assert.deepEqual(+ wf1.list.find((w) => w.matchId === "one")?.handler,+ ["silence"],+ "handler is normalized to an array on list"+ );++ // invalid handler throws+ assert.throws(+ () =>+ new DiscourseDeprecationWorkflow([+ { handler: "nope", matchId: "two" },+ ]),+ /handler.*must be one of/,+ "throws on invalid handler"+ );++ // both log and silence together throws+ assert.throws(+ () =>+ new DiscourseDeprecationWorkflow([+ { handler: ["log", "silence"], matchId: "three" },+ ]),+ /must not include both `log` and `silence`/,+ "throws if both log and silence are present"+ );++ // empty handler array is allowed (defaults to []), should still match for counting/silence checks+ const wf2 = new DiscourseDeprecationWorkflow([{ matchId: "four" }]);+ assert.true(+ wf2.shouldCount("four"),+ "empty handler is accepted and should count"+ );+ });+ });++ module("environment activation", function () {+ test("active workflows when environment is not set", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "log", matchId: "empty-env" }, // env: []+ { handler: "log", matchId: "unset-env", env: ["unset"] },+ { handler: "log", matchId: "dev-only", env: ["development"] },+ ]);++ const ids = wf.list.map((w) => w.matchId);+ assert.deepEqual(+ ids.sort(),+ ["empty-env", "unset-env"].sort(),+ "includes empty env and unset env only when environment is not set"+ );+ });++ test("active workflows in production", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "log", matchId: "always" }, // always included+ { handler: "log", matchId: "prod", env: ["production"] },+ { handler: "log", matchId: "dev", env: ["development"] },+ { handler: "log", matchId: "test", env: ["test"] },+ { handler: "log", matchId: "unset", env: ["unset"] },+ ]);++ wf.setEnvironment(makeEnv({ production: true }));++ const ids = wf.list.map((w) => w.matchId);+ assert.deepEqual(+ ids.sort(),+ ["always", "prod"].sort(),+ "includes always and production only"+ );+ });++ test("active workflows in qunit/test environment", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "log", matchId: "always" },+ { handler: "log", matchId: "qunit", env: ["qunit-test"] },+ { handler: "log", matchId: "generic-test", env: ["test"] },+ { handler: "log", matchId: "rails-test-only", env: ["rails-test"] },+ { handler: "log", matchId: "production", env: ["production"] },+ { handler: "log", matchId: "development", env: ["development"] },+ ]);++ wf.setEnvironment(makeEnv({ testing: true }));++ const ids = wf.list.map((w) => w.matchId);+ assert.deepEqual(+ ids.sort(),+ ["always", "qunit", "generic-test"].sort(),+ "includes always, qunit-test, and test only"+ );+ });++ test("active workflows in rails test environment", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "log", matchId: "always" },+ { handler: "log", matchId: "rails-test", env: ["rails-test"] },+ { handler: "log", matchId: "generic-test", env: ["test"] },+ { handler: "log", matchId: "qunit", env: ["qunit-test"] },+ { handler: "log", matchId: "production", env: ["production"] },+ { handler: "log", matchId: "development", env: ["development"] },+ ]);++ wf.setEnvironment(makeEnv({ railsTesting: true }));++ const ids = wf.list.map((w) => w.matchId);+ assert.deepEqual(+ ids.sort(),+ ["always", "rails-test", "generic-test"].sort(),+ "includes always, rails-test, and test only"+ );+ });++ test("active workflows in development-like env", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "log", matchId: "always" },+ { handler: "log", matchId: "development", env: ["development"] },+ { handler: "log", matchId: "test", env: ["test"] },+ { handler: "log", matchId: "production", env: ["production"] },+ { handler: "log", matchId: "unset", env: ["unset"] },+ ]);++ // environment that returns false for prod/testing/railsTesting falls back to development+ wf.setEnvironment(makeEnv());++ const ids = wf.list.map((w) => w.matchId);+ assert.deepEqual(+ ids.sort(),+ ["always", "development"].sort(),+ "includes always and development only"+ );+ });++ test("setEnvironment updates active workflows", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "log", matchId: "always" },+ { handler: "log", matchId: "prod-only", env: ["production"] },+ { handler: "log", matchId: "dev-only", env: ["development"] },+ ]);++ // initially no env: prod-only not active, always active+ assert.deepEqual(+ wf.list.map((w) => w.matchId).sort(),+ ["always"].sort(),+ "initial list only includes env-agnostic workflows"+ );++ wf.setEnvironment(makeEnv({ production: true }));+ assert.deepEqual(+ wf.list.map((w) => w.matchId).sort(),+ ["always", "prod-only"].sort(),+ "after setting production, prod-only becomes active"+ );++ wf.setEnvironment(makeEnv()); // dev-like+ assert.deepEqual(+ wf.list.map((w) => w.matchId).sort(),+ ["always", "dev-only"].sort(),+ "after switching to development-like env, dev-only becomes active"+ );+ });+ });++ module("behavior helpers", function () {+ test("helpers work with exact match and regex match", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "silence", matchId: "bar.deprecated" },+ { handler: "silence", matchId: /^foo\..+$/ },+ ]);++ // exact match+ assert.true(+ wf.shouldSilence("bar.deprecated"),+ "silences exact-match id"+ );++ // regex match+ assert.true(+ wf.shouldSilence("foo.deprecated"),+ "silences regex-matched id"+ );++ // non-match+ assert.false(+ wf.shouldSilence("no.match"),+ "does not silence when no workflow matches"+ );+ });++ test("shouldLog respects workflow presence and handlers", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "log", matchId: "a" },+ { handler: "silence", matchId: "b" },+ { handler: "counter", matchId: "c" }, // no log -> false+ { handler: ["silence", "counter"], matchId: "d" }, // still no log -> false+ ]);++ assert.true(+ wf.shouldLog("no-config"),+ "unhandled deprecations should log"+ );+ assert.true(wf.shouldLog("a"), "handler with log should log");+ assert.false(wf.shouldLog("b"), "silence handler should not log");+ assert.false(wf.shouldLog("c"), "counter-only should not log");+ assert.false(wf.shouldLog("d"), "silence+counter should not log");+ });++ test("shouldSilence reflects presence of silence handler", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "silence", matchId: "s1" },+ { handler: ["silence", "counter"], matchId: "s2" },+ { handler: "log", matchId: "l" },+ { handler: "counter", matchId: "c" },+ ]);++ assert.true(wf.shouldSilence("s1"), "silence -> true");+ assert.true(wf.shouldSilence("s2"), "silence+counter -> true");+ assert.false(wf.shouldSilence("l"), "log -> false");+ assert.false(wf.shouldSilence("c"), "counter -> false");+ assert.false(wf.shouldSilence("unhandled"), "unhandled -> false");+ });++ test("shouldCount defaults to true and is true with counter even if silenced", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "silence", matchId: "s" },+ { handler: "counter", matchId: "c" },+ { handler: ["silence", "counter"], matchId: "sc" },+ { handler: "log", matchId: "l" },+ { handler: [], matchId: "empty" },+ ]);++ assert.true(wf.shouldCount("unhandled"), "unhandled -> count");+ assert.false(wf.shouldCount("s"), "silence -> do not count");+ assert.true(wf.shouldCount("c"), "counter -> count");+ assert.true(wf.shouldCount("sc"), "silence+counter -> count");+ assert.true(wf.shouldCount("l"), "log only -> count");+ assert.true(wf.shouldCount("empty"), "empty handler -> count");+ });++ test("shouldThrow handles throw and includeUnhandled", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: "throw", matchId: "t" },+ { handler: "log", matchId: "l" },+ ]);++ assert.true(wf.shouldThrow("t"), "throw handler -> true");+ assert.false(wf.shouldThrow("l"), "non-throw handler -> false");+ assert.false(+ wf.shouldThrow("unhandled"),+ "unhandled without includeUnhandled -> false"+ );+ assert.true(+ wf.shouldThrow("unhandled", true),+ "unhandled with includeUnhandled -> true"+ );+ });+ });++ test("emberWorkflowList flattens handlers and filters to Ember CLI-compatible ones", function (assert) {+ const wf = new DiscourseDeprecationWorkflow([+ { handler: ["silence", "counter"], matchId: "x" },+ { handler: ["log", "throw"], matchId: "y" },+ ]);++ const flattened = wf.emberWorkflowList+ .map((w) => `${w.matchId}:${w.handler}`)+ .sort();++ // "counter" is not included in Ember CLI workflow output; others are+ assert.deepEqual(+ flattened,+ ["x:silence", "y:log", "y:throw"].sort(),+ "outputs one entry per allowed handler and excludes counter"+ );+ });+});diff --git a/app/assets/javascripts/discourse/tests/unit/lib/deprecated-test.js b/app/assets/javascripts/discourse/tests/unit/lib/deprecated-test.jsindex fb2e1bdbcdf..7d17f14da35 100644--- a/app/assets/javascripts/discourse/tests/unit/lib/deprecated-test.js+++ b/app/assets/javascripts/discourse/tests/unit/lib/deprecated-test.js@@ -20,7 +20,7 @@ module("Unit | Utility | deprecated", function (hooks) {this.warnStub = Sinon.stub(console, "warn");this.counterStub = Sinon.stub(DeprecationCounter.prototype,- "incrementDeprecation"+ "incrementCount");});@@ -43,12 +43,12 @@ module("Unit | Utility | deprecated", function (hooks) {assert.strictEqual(this.counterStub.callCount,1,- "incrementDeprecation was called once"+ "incrementCount was called once");assert.deepEqual(this.counterStub.args[0],["discourse.(unknown)"],- "incrementDeprecation is called with the correct arguments"+ "incrementCount is called with the correct arguments");});@@ -69,12 +69,12 @@ module("Unit | Utility | deprecated", function (hooks) {assert.strictEqual(this.counterStub.callCount,1,- "incrementDeprecation was called once"+ "incrementCount was called once");assert.deepEqual(this.counterStub.args[0],["discourse.my_deprecation_id"],- "incrementDeprecation is called with the correct arguments"+ "incrementCount is called with the correct arguments");});@@ -100,12 +100,12 @@ module("Unit | Utility | deprecated", function (hooks) {assert.strictEqual(this.counterStub.callCount,1,- "incrementDeprecation was called once"+ "incrementCount was called once");assert.deepEqual(this.counterStub.args[0],["discourse.my_deprecation_id"],- "incrementDeprecation is called with the correct arguments"+ "incrementCount is called with the correct arguments");});@@ -121,12 +121,12 @@ module("Unit | Utility | deprecated", function (hooks) {assert.strictEqual(this.counterStub.callCount,1,- "incrementDeprecation was called once"+ "incrementCount was called once");assert.deepEqual(this.counterStub.args[0],["discourse.my_deprecation_id"],- "incrementDeprecation is called with the correct arguments"+ "incrementCount is called with the correct arguments");});@@ -189,6 +189,43 @@ module("Unit | Utility | deprecated", function (hooks) {);});+ test("can use Regex to silence deprecations", function (assert) {+ withSilencedDeprecations(/discourse\..+/, () => {+ deprecated("message", { id: "discourse.one" });+ deprecated("message", { id: "discourse.two" });+ });+ assert.strictEqual(+ this.warnStub.callCount,+ 0,+ "console.warn is not called"+ );+ assert.strictEqual(+ this.counterStub.callCount,+ 0,+ "counter is not incremented"+ );++ withSilencedDeprecations(+ [/.+method.+/, /.+property/, "discourse.other-deprecation"],+ () => {+ deprecated("message", { id: "discourse.array-method1" });+ deprecated("message", { id: "discourse.array-method2" });+ deprecated("message", { id: "discourse.array-property" });+ deprecated("message", { id: "discourse.other-deprecation" });+ }+ );+ assert.strictEqual(+ this.warnStub.callCount,+ 0,+ "console.warn is not called"+ );+ assert.strictEqual(+ this.counterStub.callCount,+ 0,+ "counter is not incremented"+ );+ });+test("can silence deprecations with async callback in tests", async function (assert) {await withSilencedDeprecationsAsync("discourse.one", async () => {await Promise.resolve();@@ -218,6 +255,45 @@ module("Unit | Utility | deprecated", function (hooks) {);});+ test("can use Regex to silence deprecations with async callbacks", async function (assert) {+ await withSilencedDeprecationsAsync(/discourse\..+/, async () => {+ await Promise.resolve();+ deprecated("message", { id: "discourse.one" });+ deprecated("message", { id: "discourse.two" });+ });+ assert.strictEqual(+ this.warnStub.callCount,+ 0,+ "console.warn is not called"+ );+ assert.strictEqual(+ this.counterStub.callCount,+ 0,+ "counter is not incremented"+ );++ await withSilencedDeprecationsAsync(+ [/.+method.+/, /.+property/, "discourse.other-deprecation"],+ async () => {+ await Promise.resolve();+ deprecated("message", { id: "discourse.array-method1" });+ deprecated("message", { id: "discourse.array-method2" });+ deprecated("message", { id: "discourse.array-property" });+ deprecated("message", { id: "discourse.other-deprecation" });+ }+ );+ assert.strictEqual(+ this.warnStub.callCount,+ 0,+ "console.warn is not called"+ );+ assert.strictEqual(+ this.counterStub.callCount,+ 0,+ "counter is not incremented"+ );+ });+test("can silence Ember deprecations", function (assert) {withSilencedDeprecations("fake-ember-deprecation", () => {emberDeprecate("fake ember deprecation message", false, {@@ -238,4 +314,40 @@ module("Unit | Utility | deprecated", function (hooks) {"counter is not incremented");});++ test("can use Regex to silence Ember deprecations", function (assert) {+ withSilencedDeprecations(+ [/.+-deprecation.+/, "fake-ember-property"],+ () => {+ emberDeprecate("fake ember deprecation message", false, {+ id: "fake-ember-deprecation1",+ for: "not-ember-source",+ since: "v0",+ until: "v999",+ });+ emberDeprecate("fake ember deprecation message", false, {+ id: "fake-ember-deprecation2",+ for: "not-ember-source",+ since: "v0",+ until: "v999",+ });+ emberDeprecate("fake ember deprecation message", false, {+ id: "fake-ember-property",+ for: "not-ember-source",+ since: "v0",+ until: "v999",+ });+ }+ );+ assert.strictEqual(+ this.warnStub.callCount,+ 0,+ "console.warn is not called"+ );+ assert.strictEqual(+ this.counterStub.callCount,+ 0,+ "counter is not incremented"+ );+ });});