Skip to content

A platform for community discussion. Free, open, simple.

DEV: Extract theme script tags into their own JS files (#33647)

David Taylorf4b70c746dba
diff --git a/app/assets/javascripts/theme-transpiler/transpiler.js b/app/assets/javascripts/theme-transpiler/transpiler.js
index 229d36f1327..dea3ba62b6a 100644
--- a/app/assets/javascripts/theme-transpiler/transpiler.js
+++ b/app/assets/javascripts/theme-transpiler/transpiler.js
@@ -54,7 +54,8 @@ function buildTemplateCompilerBabelPlugins({ extension, themeId }) {
}
globalThis.transpile = function (source, options = {}) {
- const { moduleId, filename, extension, skipModule, themeId } = options;
+ const { moduleId, filename, extension, skipModule, themeId, generateMap } =
+ options;
if (extension === "gjs") {
const preprocessor = new Preprocessor();
@@ -69,7 +70,7 @@ globalThis.transpile = function (source, options = {}) {
plugins.push([DecoratorTransforms, { runEarly: true }]);
try {
- return babelTransform(source, {
+ const result = babelTransform(source, {
moduleId,
filename,
ast: false,
@@ -85,7 +86,16 @@ globalThis.transpile = function (source, options = {}) {
},
],
],
- }).code;
+ sourceMaps: generateMap,
+ });
+ if (generateMap) {
+ return {
+ code: result.code,
+ map: JSON.stringify(result.map),
+ };
+ } else {
+ return result.code;
+ }
} catch (error) {
// Workaround for https://github.com/rubyjs/mini_racer/issues/262
error.message = JSON.stringify(error.message);
diff --git a/app/models/javascript_cache.rb b/app/models/javascript_cache.rb
index e1409f6a857..876b14752c6 100644
--- a/app/models/javascript_cache.rb
+++ b/app/models/javascript_cache.rb
@@ -45,12 +45,13 @@ end
# updated_at :datetime not null
# theme_id :bigint
# source_map :text
+# name :string
#
# Indexes
#
-# index_javascript_caches_on_digest (digest)
-# index_javascript_caches_on_theme_field_id (theme_field_id) UNIQUE
-# index_javascript_caches_on_theme_id (theme_id) UNIQUE
+# index_javascript_caches_on_digest (digest)
+# index_javascript_caches_on_theme_field_id_and_name (theme_field_id,name) UNIQUE WHERE (theme_field_id IS NOT NULL)
+# index_javascript_caches_on_theme_id (theme_id) UNIQUE
#
# Foreign Keys
#
diff --git a/app/models/theme.rb b/app/models/theme.rb
index 6fa937d78e2..908c038aeaf 100644
--- a/app/models/theme.rb
+++ b/app/models/theme.rb
@@ -6,7 +6,7 @@ require "json_schemer"
class Theme < ActiveRecord::Base
include GlobalPath
- BASE_COMPILER_VERSION = 91
+ BASE_COMPILER_VERSION = 92
CORE_THEMES = { "foundation" => -1, "horizon" => -2 }
EDITABLE_SYSTEM_ATTRIBUTES = %w[
child_theme_ids
diff --git a/app/models/theme_field.rb b/app/models/theme_field.rb
index de1ddb59d0a..05fb31fbea0 100644
--- a/app/models/theme_field.rb
+++ b/app/models/theme_field.rb
@@ -8,7 +8,12 @@ class ThemeField < ActiveRecord::Base
CSP_NONCE_PLACEHOLDER = "__CSP__NONCE__PLACEHOLDER__f72bff1b1768168a34ee092ce759f192__"
belongs_to :upload
- has_one :javascript_cache, dependent: :destroy
+ has_one :javascript_cache, -> { where(name: nil) }, dependent: :destroy, autosave: true
+ has_many :raw_javascript_caches,
+ -> { where.not(name: nil) },
+ class_name: "JavascriptCache",
+ dependent: :destroy,
+ autosave: true
has_one :upload_reference, as: :target, dependent: :destroy
has_one :theme_settings_migration
@@ -119,8 +124,6 @@ class ThemeField < ActiveRecord::Base
def process_html(html)
errors = []
- javascript_cache || build_javascript_cache
-
errors << I18n.t("themes.errors.optimized_link") if contains_optimized_link?(html)
js_compiler = ThemeJavascriptCompiler.new(theme_id, self.theme.name)
@@ -225,31 +228,52 @@ class ThemeField < ActiveRecord::Base
node.remove
end
+ unused_raw_caches = Set.new raw_javascript_caches.to_a
+
doc
.css("script")
+ .select { |node| inline_javascript?(node) }
.each_with_index do |node, index|
- if inline_javascript?(node)
- js_compiler.append_raw_script(
- "_html/#{Theme.targets[self.target_id]}/#{name}_#{index + 1}.js",
+ unique_name =
+ "theme-#{theme_id}-inline-#{Theme.targets[self.target_id]}-#{name}#{"-#{index + 1}" if index > 0}"
+
+ cache =
+ raw_javascript_caches.find { |c| c.name == unique_name } ||
+ raw_javascript_caches.build(name: unique_name)
+ transpiled =
+ DiscourseJsProcessor::Transpiler.new(skip_module: true).perform(
node.inner_html,
+ nil,
+ "theme-#{theme_id}/#{unique_name}.js",
+ generate_map: true,
)
- node.remove
- else
- node["nonce"] = CSP_NONCE_PLACEHOLDER
- end
+ cache.content = transpiled["code"]
+ cache.source_map = transpiled["map"]
+ cache.save!
+ unused_raw_caches.delete(cache)
+
+ node.replace "<script defer src='#{cache.url}' data-theme-id='#{theme_id}'></script>"
end
- settings_hash = theme.build_settings_hash
- if js_compiler.has_content? && settings_hash.present?
- js_compiler.prepend_settings(settings_hash)
+ doc.css("script").each { |node| node["nonce"] = CSP_NONCE_PLACEHOLDER }
+
+ unused_raw_caches.each(&:destroy!)
+
+ if js_compiler.has_content?
+ javascript_cache || build_javascript_cache
+ settings_hash = theme.build_settings_hash
+ js_compiler.prepend_settings(settings_hash) if settings_hash.present?
+ javascript_cache.content = js_compiler.content
+ javascript_cache.source_map = js_compiler.source_map
+ javascript_cache.save!
+
+ doc.add_child(<<~HTML.html_safe) if javascript_cache.content.present?
+ <script defer src='#{javascript_cache.url}' data-theme-id='#{theme_id}' nonce="#{CSP_NONCE_PLACEHOLDER}"></script>
+ HTML
+ else
+ javascript_cache&.destroy!
end
- javascript_cache.content = js_compiler.content
- javascript_cache.source_map = js_compiler.source_map
- javascript_cache.save!
- doc.add_child(<<~HTML.html_safe) if javascript_cache.content.present?
- <script defer src='#{javascript_cache.url}' data-theme-id='#{theme_id}' nonce="#{CSP_NONCE_PLACEHOLDER}"></script>
- HTML
[doc.to_s, errors&.join("\n")]
end
diff --git a/db/migrate/20250715094001_update_javascript_cache.rb b/db/migrate/20250715094001_update_javascript_cache.rb
new file mode 100644
index 00000000000..17d29bf890e
--- /dev/null
+++ b/db/migrate/20250715094001_update_javascript_cache.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+class UpdateJavascriptCache < ActiveRecord::Migration[7.2]
+ def change
+ remove_index :javascript_caches,
+ column: :theme_field_id,
+ name: :index_javascript_caches_on_theme_field_id,
+ unique: true
+ add_column :javascript_caches, :name, :string
+ add_index :javascript_caches,
+ %i[theme_field_id name],
+ unique: true,
+ nulls_not_distinct: true,
+ where: "theme_field_id IS NOT NULL"
+ end
+end
diff --git a/lib/discourse_js_processor.rb b/lib/discourse_js_processor.rb
index fdfa68626fb..51e81c9a0e4 100644
--- a/lib/discourse_js_processor.rb
+++ b/lib/discourse_js_processor.rb
@@ -109,7 +109,14 @@ class DiscourseJsProcessor
@skip_module = skip_module
end
- def perform(source, root_path = nil, logical_path = nil, theme_id: nil, extension: nil)
+ def perform(
+ source,
+ root_path = nil,
+ logical_path = nil,
+ theme_id: nil,
+ extension: nil,
+ generate_map: false
+ )
self.class.v8_call(
"transpile",
source,
@@ -119,6 +126,7 @@ class DiscourseJsProcessor
filename: logical_path || "unknown",
extension: extension,
themeId: theme_id,
+ generateMap: generate_map,
},
)
end
diff --git a/spec/models/theme_field_spec.rb b/spec/models/theme_field_spec.rb
index 4e19a322c49..40cfd5ece28 100644
--- a/spec/models/theme_field_spec.rb
+++ b/spec/models/theme_field_spec.rb
@@ -59,7 +59,7 @@ RSpec.describe ThemeField do
expect(theme_field.error).to eq(nil)
end
- it "only extracts inline javascript to an external file" do
+ it "extracts inline javascript to an external file" do
html = <<~HTML
<script type="text/discourse-plugin" version="0.8">
var a = "inline discourse plugin";
@@ -81,31 +81,22 @@ RSpec.describe ThemeField do
theme_field = ThemeField.create!(theme_id: -1, target_id: 0, name: "header", value: html)
theme_field.ensure_baked!
- expect(theme_field.value_baked).to include(
- "<script defer=\"\" src=\"#{theme_field.javascript_cache.url}\" data-theme-id=\"-1\" nonce=\"#{ThemeField::CSP_NONCE_PLACEHOLDER}\"></script>",
- )
- expect(theme_field.value_baked).to include("external-script.js")
- expect(theme_field.value_baked).to include('<script type="text/template"')
- expect(theme_field.javascript_cache.content).to include('a = "inline discourse plugin"')
- expect(theme_field.javascript_cache.content).to include('b = "inline raw script"')
- expect(theme_field.javascript_cache.content).to include('c = "text/javascript"')
- expect(theme_field.javascript_cache.content).to include('d = "application/javascript"')
- end
- it "adds newlines between the extracted javascripts" do
- html = <<~HTML
- <script>var a = 10</script>
- <script>var b = 10</script>
- HTML
+ baked_doc = Nokogiri::HTML5.fragment(theme_field.value_baked)
- extracted = <<~JS
- var a = 10
- var b = 10
- JS
+ extracted_scripts = baked_doc.css("script[src^='/theme-javascripts/']")
+ expect(extracted_scripts.length).to eq(4)
- theme_field = ThemeField.create!(theme_id: -1, target_id: 0, name: "header", value: html)
- theme_field.ensure_baked!
- expect(theme_field.javascript_cache.content).to include(extracted)
+ expect(theme_field.javascript_cache.content).to include("inline discourse plugin")
+
+ raw_js_cache_contents = theme_field.raw_javascript_caches.map(&:content)
+ expect(raw_js_cache_contents).to contain_exactly(
+ 'var b = "inline raw script";',
+ 'var c = "text/javascript";',
+ 'var d = "application/javascript";',
+ )
+
+ expect(baked_doc.css("script[type='text/template']").length).to eq(1)
end
it "correctly extracts and generates errors for transpiled js" do
@@ -797,7 +788,7 @@ HTML
theme.set_field(
target: :common,
name: "head_tag",
- value: "<script>let c = 'd';</script>",
+ value: "<script type='text/discourse-plugin' version='0.1'>let c = 'd';</script>",
type: :html,
)
diff --git a/spec/requests/admin/themes_controller_spec.rb b/spec/requests/admin/themes_controller_spec.rb
index 5836b44a805..723f32ea14d 100644
--- a/spec/requests/admin/themes_controller_spec.rb
+++ b/spec/requests/admin/themes_controller_spec.rb
@@ -1188,18 +1188,18 @@ RSpec.describe Admin::ThemesController do
)
theme.save!
- javascript_cache =
+ javascript_caches =
theme
.theme_fields
.find_by(target_id: Theme.targets[:common], name: :header)
- .javascript_cache
- expect(javascript_cache).to_not eq(nil)
+ .raw_javascript_caches
+ expect(javascript_caches.length).to eq(1)
delete "/admin/themes/#{theme.id}.json"
expect(response.status).to eq(204)
expect { theme.reload }.to raise_error(ActiveRecord::RecordNotFound)
- expect { javascript_cache.reload }.to raise_error(ActiveRecord::RecordNotFound)
+ expect { javascript_caches[0].reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end