Merge remote-tracking branch 'upstream/stable-4.7', removing Mastodon-Modern folder.
This commit is contained in:
commit
8eabb7ea31
959 files changed
+29430
-9565
No files matched your search
@@ -0,0 +1,96 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
# Originally written by ViaCelestia
|
||||
# https://github.com/dryruby/json-canonicalization/pull/6
|
||||
|
||||
class Numeric
|
||||
# This is intended to be compliant with ECMA-262, version 6.0 (ES6)
|
||||
#
|
||||
# See https://262.ecma-international.org/6.0/#sec-tostring-applied-to-the-number-type
|
||||
#
|
||||
# JSON does not permit NaN or infinite values, so those raise an error
|
||||
def to_json_c14n
|
||||
raise RangeError if self.is_a?(Float) && !self.finite?
|
||||
return '0' if self.zero?
|
||||
|
||||
# We may or may not be using scientific notation (see https://en.wikipedia.org/wiki/Scientific_notation)
|
||||
# at this point, but the terminology is the same. Numbers are represented as a significand
|
||||
# (also known as a mantissa) multiplied by 10 raised to an exponent. A number like 1701 may be represented
|
||||
# as 1701 * 10^0, 170.1 * 10^1, 17.01 * 10^2, or (in scientific notation) 1.701 * 10^3. ES6 and Ruby don't
|
||||
# always agree on when to use scientific notation, but if Ruby has done the conversion, we can use the
|
||||
# exponent below when reproducing the behavior in the ES6 spec.
|
||||
significand_digits, exponent_digits = self.abs.to_s.split('e', 2)
|
||||
|
||||
integer_digits, fraction_digits = significand_digits.split('.', 2)
|
||||
|
||||
|
||||
# From the ES6 spec:
|
||||
#
|
||||
# "The abstract operation ToString converts a Number m to String format as follows ...
|
||||
# let n, k, and s be integers such that k ≥ 1, 10k−1 ≤ s < 10k, the Number value for s × 10n−k is m,
|
||||
# and k is as small as possible. Note that k is the number of digits in the decimal representation of s,
|
||||
# that s is not divisible by 10, and that the least significant digit of s is not necessarily uniquely
|
||||
# determined by these criteria."
|
||||
#
|
||||
# This is just a different sort of exponential notation, but instead of preferring 0 < s < 10 as in
|
||||
# scientific notation, here we want s to be an integer, and not divisible by 10. Since we're relying
|
||||
# on ruby's existing #to_s, s is just the significand without the decimal or any leading or trailing
|
||||
# zeroes
|
||||
s = significand_digits.sub('.', '').sub(/^-?0*/, '').sub(/0*$/, '')
|
||||
|
||||
# Once we know s, k is easy
|
||||
k = s.length
|
||||
|
||||
# If n is positive, it represents the number of digits (including trailing zeroes) to the left of the
|
||||
# decimal. If n is negative or zero, it represents the number of zeroes to the right of the decimal.
|
||||
# n-1 is also equal to the exponent used in scientific notation represenations of m, so if we already
|
||||
# have that representation, we can use that rather than try to recalculate where the decimal would be
|
||||
# If we don't already have an exponent, we just do digit counting rather than using Math.log10(self) or
|
||||
# the slightly more precise Math.log2(self)/Math.log2(10) since that can lose precision for values very
|
||||
# close to n = 22, like the Integer value 999999999999999700000
|
||||
n = if exponent_digits
|
||||
exponent_digits.to_i + 1
|
||||
elsif integer_digits.to_i > 0
|
||||
integer_digits.length
|
||||
else
|
||||
-fraction_digits.index(/[1-9]/)
|
||||
end
|
||||
|
||||
exponent = n - 1
|
||||
|
||||
# Per the spec, positive numbers do not include a sign, but exponents always do
|
||||
sign = self.negative? ? '-' : ''
|
||||
exponent_sign = exponent.negative? ? '-' : '+'
|
||||
|
||||
if k <= n && n <= 21 # Whole numbers, possibly with trailing zeroes, and < 10^21
|
||||
# return the String consisting of the code units of the k digits of the decimal representation of s
|
||||
# (in order, with no leading zeroes), followed by n−k occurrences of the code unit 0x0030 (DIGIT ZERO).
|
||||
[sign, s, '0' * (n - k)].join
|
||||
elsif 0 < n && n <= 21 # Numbers with an integer component < 10^21
|
||||
# return the String consisting of the code units of the most significant n digits of the decimal
|
||||
# representation of s, followed by the code unit 0x002E (FULL STOP), followed by the code units of the
|
||||
# remaining k−n digits of the decimal representation of s.
|
||||
[sign, s[0..(n-1)], '.', s[n..-1]].join
|
||||
elsif -6 < n && n <= 0 # Fractional numbers to no more than 6 decimal places
|
||||
# return the String consisting of the code unit 0x0030 (DIGIT ZERO), followed by the code unit 0x002E
|
||||
# (FULL STOP), followed by −n occurrences of the code unit 0x0030 (DIGIT ZERO), followed by the code
|
||||
# units of the k digits of the decimal representation of s
|
||||
[sign, '0.', '0' * (-n), s].join
|
||||
elsif k == 1 # single significant digit outside of -6 < n <= 21
|
||||
# return the String consisting of the code unit of the single digit of s, followed by code unit 0x0065
|
||||
# (LATIN SMALL LETTER E), followed by the code unit 0x002B (PLUS SIGN) or the code unit 0x002D
|
||||
# (HYPHEN-MINUS) according to whether n−1 is positive or negative, followed by the code units of the decimal
|
||||
# representation of the integer abs(n−1) (with no leading zeroes).
|
||||
#
|
||||
# This produces "1e-18", rather than Ruby's default "1.0e-18"
|
||||
[sign, s, 'e', exponent_sign, exponent.abs].join
|
||||
else # multiple significant digits outside of -6 < n <= 21
|
||||
# Return the String consisting of the code units of the most significant digit of the decimal representation
|
||||
# of s, followed by code unit 0x002E (FULL STOP), followed by the code units of the remaining k−1 digits of
|
||||
# the decimal representation of s, followed by code unit 0x0065 (LATIN SMALL LETTER E), followed by code unit
|
||||
# 0x002B (PLUS SIGN) or the code unit 0x002D (HYPHEN-MINUS) according to whether n−1 is positive or negative,
|
||||
# followed by the code units of the decimal representation of the integer abs(n−1) (with no leading zeroes).
|
||||
[sign, s[0], '.', s[1..-1], 'e', exponent_sign, exponent.abs].join
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -100,7 +100,8 @@ module Mastodon::CLI
|
||||
end
|
||||
|
||||
account.suspended_at = nil
|
||||
user.account = account
|
||||
account.requested_deletion_at = nil
|
||||
user.account = account
|
||||
|
||||
if user.save
|
||||
if options[:confirmed]
|
||||
@@ -124,6 +125,7 @@ module Mastodon::CLI
|
||||
option :enable, type: :boolean
|
||||
option :disable, type: :boolean
|
||||
option :disable_2fa, type: :boolean
|
||||
option :disable_sign_in_token, type: :boolean
|
||||
option :approve, type: :boolean
|
||||
option :reset_password, type: :boolean
|
||||
desc 'modify USERNAME', 'Modify a user account'
|
||||
@@ -145,6 +147,16 @@ module Mastodon::CLI
|
||||
With the --disable-2fa option, the two-factor authentication
|
||||
requirement for the user can be removed.
|
||||
|
||||
With the --disable-sign-in-token option, an account that has been
|
||||
inactive for a long time won't have to introduce a security code that
|
||||
has been sent to their email when trying to log in. This option
|
||||
only disables the security code check for a limited amount of time
|
||||
(up to 92 hours)
|
||||
|
||||
With the --enable-sign-in-token option, ensure that the account
|
||||
generates a security code challenge if it has been inactive for too
|
||||
long.
|
||||
|
||||
With the --reset-password option, the user's password is replaced by
|
||||
a randomly-generated one, printed in the output.
|
||||
LONG_DESC
|
||||
@@ -168,6 +180,8 @@ module Mastodon::CLI
|
||||
user.disabled = true if options[:disable]
|
||||
user.approved = true if options[:approve]
|
||||
user.disable_two_factor! if options[:disable_2fa]
|
||||
user.disable_sign_in_token! if options[:disable_sign_in_token]
|
||||
user.enable_sign_in_token! if options[:enable_sign_in_token]
|
||||
|
||||
# Password changes are a little different, as we also need to ensure
|
||||
# sessions, subscriptions, and access tokens are revoked after changing:
|
||||
@@ -253,20 +267,11 @@ module Mastodon::CLI
|
||||
desc 'fix-duplicates', 'Find duplicate remote accounts and merge them'
|
||||
option :dry_run, type: :boolean
|
||||
long_desc <<-LONG_DESC
|
||||
Merge known remote accounts sharing an ActivityPub actor identifier.
|
||||
|
||||
Such duplicates can occur when a remote server admin misconfigures their
|
||||
domain configuration.
|
||||
This command is deprecated as of Mastodon v4.7.0.
|
||||
LONG_DESC
|
||||
def fix_duplicates
|
||||
Account.remote.duplicate_uris.pluck(:uri).each do |uri|
|
||||
say("Duplicates found for #{uri}")
|
||||
begin
|
||||
ActivityPub::FetchRemoteAccountService.new.call(uri) unless dry_run?
|
||||
rescue => e
|
||||
say("Error processing #{uri}: #{e}", :red)
|
||||
end
|
||||
end
|
||||
# TODO: remove this after 4.7.0
|
||||
say('This command is deprecated as Mastodon v4.7.0 migrations enforce ActivityPub actor identifier uniqueness', :yellow)
|
||||
end
|
||||
|
||||
desc 'backup USERNAME', 'Request a backup for a user'
|
||||
@@ -612,10 +617,22 @@ module Mastodon::CLI
|
||||
def rotate_keys_for_account(account, delay = 0)
|
||||
fail_with_message 'No such account' if account.nil?
|
||||
|
||||
old_key = account.private_key
|
||||
old_key = account.keypair
|
||||
new_key = OpenSSL::PKey::RSA.new(2048)
|
||||
account.update(private_key: new_key.to_pem, public_key: new_key.public_key.to_pem)
|
||||
ActivityPub::UpdateDistributionWorker.perform_in(delay, account.id, { 'sign_with' => old_key })
|
||||
|
||||
account.update(private_key: nil, public_key: '', keypairs: [account.keypairs.build(local_fragment: '#main-key', type: :rsa, public_key: new_key.public_key.to_pem, private_key: new_key.to_pem)])
|
||||
|
||||
ActivityPub::UpdateDistributionWorker.perform_in(
|
||||
delay,
|
||||
account.id,
|
||||
{
|
||||
'sign_with' => {
|
||||
'private_key' => old_key.private_key,
|
||||
'local_fragment' => old_key.local_fragment,
|
||||
'type' => old_key.type,
|
||||
},
|
||||
}
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -255,7 +255,7 @@ module Mastodon::CLI
|
||||
media_attachment.save
|
||||
end
|
||||
|
||||
media_attachment.file_file_size + (media_attachment.thumbnail_file_size || 0)
|
||||
(media_attachment.file_file_size || 0) + (media_attachment.thumbnail_file_size || 0)
|
||||
end
|
||||
|
||||
say("Downloaded #{processed} media attachments (approx. #{number_to_human_size(aggregate)})#{dry_run_mode_suffix}", :green, true)
|
||||
|
||||
@@ -9,11 +9,11 @@ module Mastodon
|
||||
end
|
||||
|
||||
def minor
|
||||
6
|
||||
7
|
||||
end
|
||||
|
||||
def patch
|
||||
11
|
||||
5
|
||||
end
|
||||
|
||||
def default_prerelease
|
||||
|
||||
@@ -6,7 +6,6 @@ module Paperclip
|
||||
class ColorExtractor < Paperclip::Processor
|
||||
MIN_CONTRAST = 3.0
|
||||
ACCENT_MIN_CONTRAST = 2.0
|
||||
FREQUENCY_THRESHOLD = 0.01
|
||||
BINS = 10
|
||||
|
||||
def make
|
||||
@@ -215,18 +214,6 @@ module Paperclip
|
||||
ColorDiff::Color::RGB.new(*hsl_to_rgb(hue, saturation, light))
|
||||
end
|
||||
|
||||
def palette_from_im_histogram(result, quantity)
|
||||
frequencies = result.scan(/([0-9]+):/).flatten.map(&:to_f)
|
||||
hex_values = result.scan(/\#([0-9A-Fa-f]{6,8})/).flatten
|
||||
total_frequencies = frequencies.sum.to_f
|
||||
|
||||
frequencies.map.with_index { |f, i| [f / total_frequencies, hex_values[i]] }
|
||||
.sort_by { |r| -r[0] }
|
||||
.reject { |r| r[1].size == 8 && r[1].end_with?('00') }
|
||||
.map { |r| ColorDiff::Color::RGB.new(*r[1][0..5].scan(/../).map { |c| c.to_i(16) }) }
|
||||
.slice(0, quantity)
|
||||
end
|
||||
|
||||
def rgb_to_hex(rgb)
|
||||
format('#%02x%02x%02x', rgb.r, rgb.g, rgb.b) # rubocop:disable Style/FormatStringToken
|
||||
end
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Paperclip
|
||||
module MediaTypeSpoofDetectorExtensions
|
||||
MARCEL_MIME_TYPES = %w(audio/mpeg image/avif).freeze
|
||||
|
||||
def calculated_content_type
|
||||
return @calculated_content_type if defined?(@calculated_content_type)
|
||||
|
||||
@calculated_content_type = type_from_file_command.chomp
|
||||
|
||||
# The `file` command fails to recognize some MP3 files as such
|
||||
@calculated_content_type = type_from_marcel if @calculated_content_type == 'application/octet-stream' && type_from_marcel.in?(MARCEL_MIME_TYPES)
|
||||
@calculated_content_type
|
||||
end
|
||||
|
||||
def type_from_marcel
|
||||
@type_from_marcel ||= Marcel::MimeType.for Pathname.new(@file.path),
|
||||
name: @file.path
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Paperclip::MediaTypeSpoofDetector.prepend(Paperclip::MediaTypeSpoofDetectorExtensions)
|
||||
@@ -2,16 +2,16 @@
|
||||
|
||||
module PremailerBundledAssetStrategy
|
||||
def load(url)
|
||||
if ViteRuby.instance.dev_server_running?
|
||||
if Rails.env.development? && Vite.dev_server.running?
|
||||
# Request from the dev server
|
||||
return unless url.start_with?("/#{ViteRuby.config.public_output_dir}/")
|
||||
return unless url.start_with?(Vite.config.base_path)
|
||||
|
||||
headers = {}
|
||||
# Vite dev server wants this header for CSS files, otherwise it will respond with a JS file that inserts the CSS (to support hot reloading)
|
||||
headers['Accept'] = 'text/css' if url.end_with?('.scss', '.css')
|
||||
|
||||
Net::HTTP.get(
|
||||
URI("#{ViteRuby.config.origin}#{url}"),
|
||||
URI("#{Vite.config.backend}#{url}"),
|
||||
headers
|
||||
).presence
|
||||
else
|
||||
@@ -22,7 +22,7 @@ module PremailerBundledAssetStrategy
|
||||
|
||||
path.read
|
||||
end
|
||||
rescue ViteRuby::MissingEntrypointError
|
||||
rescue Vite::Manifest::MissingEntryError
|
||||
# If the path is not in the manifest, ignore it
|
||||
end
|
||||
|
||||
|
||||
@@ -14,9 +14,16 @@ end
|
||||
|
||||
if Rake::Task.task_defined?('assets:precompile')
|
||||
Rake::Task['assets:precompile'].enhance do
|
||||
# Vite integration
|
||||
Vite.tasks.precompile
|
||||
|
||||
Rake::Task['assets:generate_static_pages'].invoke
|
||||
end
|
||||
end
|
||||
|
||||
# We don't want vite_ruby to run yarn, we do that in a separate step
|
||||
Rake::Task['vite:install_dependencies'].clear
|
||||
if Rake::Task.task_defined?('assets:clobber')
|
||||
Rake::Task['assets:clobber'].enhance do
|
||||
# Vite integration
|
||||
Vite.tasks.clobber
|
||||
end
|
||||
end
|
||||
+3
-3
@@ -66,9 +66,9 @@ namespace :db do
|
||||
abort 'This version of Mastodon requires PostgreSQL 14.0 or newer. Please update PostgreSQL before updating Mastodon.' if pg_version < 140_000
|
||||
|
||||
schema_version = ActiveRecord::Migrator.current_version
|
||||
abort <<~MESSAGE if ENV['SKIP_POST_DEPLOYMENT_MIGRATIONS'] && schema_version < 2023_09_07_150100
|
||||
Zero-downtime migrations from Mastodon versions earlier than 4.2.0 are not supported.
|
||||
Please update to Mastodon 4.2.x first or upgrade by stopping all services and running migrations without `SKIP_POST_DEPLOYMENT_MIGRATIONS`.
|
||||
abort <<~MESSAGE if ENV['SKIP_POST_DEPLOYMENT_MIGRATIONS'] && schema_version < 2024_10_07_071624
|
||||
Zero-downtime migrations from Mastodon versions earlier than 4.3.0 are not supported.
|
||||
Please update to Mastodon 4.3.x first or upgrade by stopping all services and running migrations without `SKIP_POST_DEPLOYMENT_MIGRATIONS`.
|
||||
MESSAGE
|
||||
end
|
||||
|
||||
|
||||
@@ -549,6 +549,12 @@ namespace :mastodon do
|
||||
require_relative '../../config/environment'
|
||||
disable_log_stdout!
|
||||
|
||||
ActiveRecord::Encryption.configure(
|
||||
primary_key: ENV.fetch('ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY'),
|
||||
deterministic_key: ENV.fetch('ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY'),
|
||||
key_derivation_salt: ENV.fetch('ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT')
|
||||
)
|
||||
|
||||
username = prompt.ask('Username:') do |q|
|
||||
q.required true
|
||||
q.default 'admin'
|
||||
|
||||
+70
-17
@@ -51,11 +51,16 @@ namespace :tests do
|
||||
exit(1)
|
||||
end
|
||||
|
||||
if Account.find(Account::INSTANCE_ACTOR_ID).private_key.blank?
|
||||
if Account.find(Account::INSTANCE_ACTOR_ID).keypair.blank?
|
||||
puts 'Instance actor does not have a private key'
|
||||
exit(1)
|
||||
end
|
||||
|
||||
if Account.local.where.not(private_key: nil).exists?
|
||||
puts 'Private keys not properly migrated'
|
||||
exit(1)
|
||||
end
|
||||
|
||||
unless Account.find_by(username: 'user', domain: nil).custom_filters.map { |filter| filter.keywords.pluck(:keyword) } == [['test'], ['take']]
|
||||
puts 'CustomFilterKeyword records not created as expected'
|
||||
exit(1)
|
||||
@@ -112,6 +117,21 @@ namespace :tests do
|
||||
exit(1)
|
||||
end
|
||||
|
||||
unless Account.find_by(username: 'suspended', domain: nil).suspended?
|
||||
puts 'Unexpected value for Account#suspended? for user @suspended'
|
||||
exit(1)
|
||||
end
|
||||
|
||||
if Account.find_by(username: 'deleted', domain: nil).suspended?
|
||||
puts 'Unexpected value for Account#suspended? for user @deleted'
|
||||
exit(1)
|
||||
end
|
||||
|
||||
unless Account.find_by(username: 'deleted', domain: nil).deleted?
|
||||
puts 'Unexpected value for Account#deleted? for user @deleted'
|
||||
exit(1)
|
||||
end
|
||||
|
||||
unless Identity.where(provider: 'foo', uid: 0).one?
|
||||
puts 'Identities not deduplicated as expected'
|
||||
exit(1)
|
||||
@@ -159,11 +179,23 @@ namespace :tests do
|
||||
exit(1)
|
||||
end
|
||||
|
||||
unless Account.find_by(uri: 'https://social.example.com/alice').domain == 'example.com'
|
||||
puts 'Duplicate accounts with same URI incorrectly deduplicated'
|
||||
exit(1)
|
||||
end
|
||||
|
||||
if Account.exists?(domain: 'example.com', username: %w(bogus1 bogus2 bogus3))
|
||||
puts 'Bogus remote accounts not correctly purged'
|
||||
exit(1)
|
||||
end
|
||||
|
||||
puts 'No errors found. Database state is consistent with a successful migration process.'
|
||||
end
|
||||
|
||||
desc 'Populate the database with test data for 3.3.0'
|
||||
task populate_v3_3_0: :environment do # rubocop:disable Naming/VariableNumber
|
||||
user_public_key = ActiveRecord::Base.connection.quote(OpenSSL::PKey::RSA.new(2048).public_key.to_pem)
|
||||
|
||||
ActiveRecord::Base.connection.execute(<<~SQL.squish)
|
||||
INSERT INTO "webauthn_credentials"
|
||||
(user_id, nickname, external_id, public_key, created_at, updated_at)
|
||||
@@ -202,6 +234,19 @@ namespace :tests do
|
||||
(token, application_id, scopes, resource_owner_id, created_at)
|
||||
VALUES
|
||||
('secret', 2, 'write:accounts read:me', 4, now());
|
||||
|
||||
/* Duplicate remote accounts
|
||||
Before Mastodon v4.7.0, we had no uniqueness constraint on account `uri`, which lead to issues.
|
||||
Furthermore, older tests caused remote accounts without protocol identifiers.
|
||||
*/
|
||||
INSERT INTO "accounts"
|
||||
(id, username, domain, uri, private_key, public_key, created_at, updated_at, last_webfingered_at)
|
||||
VALUES
|
||||
(14, 'alice', 'social.example.com', 'https://social.example.com/alice', NULL, #{user_public_key}, '2021-01-01'::date, now(), '2021-01-09'::date),
|
||||
(15, 'alice', 'example.com', 'https://social.example.com/alice', NULL, #{user_public_key}, '2021-01-10'::date, now(), '2021-01-11'::date),
|
||||
(16, 'bogus1', 'example.com', '', NULL, '', now(), now(), now()),
|
||||
(17, 'bogus2', 'example.com', '', NULL, '', now(), now(), now()),
|
||||
(18, 'bogus3', 'example.com', '', NULL, '', now(), now(), now());
|
||||
SQL
|
||||
end
|
||||
|
||||
@@ -262,20 +307,20 @@ namespace :tests do
|
||||
INSERT INTO "accounts"
|
||||
(id, username, domain, private_key, public_key, created_at, updated_at)
|
||||
VALUES
|
||||
(10, 'kmruser', NULL, #{user_private_key}, #{user_public_key}, now(), now()),
|
||||
(11, 'qcuser', NULL, #{user_private_key}, #{user_public_key}, now(), now());
|
||||
(12, 'kmruser', NULL, #{user_private_key}, #{user_public_key}, now(), now()),
|
||||
(13, 'qcuser', NULL, #{user_private_key}, #{user_public_key}, now(), now());
|
||||
|
||||
INSERT INTO "users"
|
||||
(id, account_id, email, created_at, updated_at, admin, locale, chosen_languages)
|
||||
VALUES
|
||||
(4, 10, 'kmruser@localhost', now(), now(), false, 'ku', '{en,kmr,ku,ckb}');
|
||||
(5, 12, 'kmruser@localhost', now(), now(), false, 'ku', '{en,kmr,ku,ckb}');
|
||||
|
||||
INSERT INTO "users"
|
||||
(id, account_id, email, created_at, updated_at, locale,
|
||||
encrypted_otp_secret, encrypted_otp_secret_iv, encrypted_otp_secret_salt,
|
||||
otp_required_for_login)
|
||||
VALUES
|
||||
(5, 11, 'qcuser@localhost', now(), now(), 'fr-QC',
|
||||
(6, 13, 'qcuser@localhost', now(), now(), 'fr-QC',
|
||||
E'Fttsy7QAa0edaDfdfSz094rRLAxc8cJweDQ4BsWH/zozcdVA8o9GLqcKhn2b\nGi/V\n',
|
||||
'rys3THICkr60BoWC',
|
||||
'_LMkAGvdg7a+sDIKjI3mR2Q==',
|
||||
@@ -284,7 +329,7 @@ namespace :tests do
|
||||
INSERT INTO "settings"
|
||||
(id, thing_type, thing_id, var, value, created_at, updated_at)
|
||||
VALUES
|
||||
(5, 'User', 4, 'default_language', E'--- kmr\n', now(), now()),
|
||||
(5, 'User', 5, 'default_language', E'--- kmr\n', now(), now()),
|
||||
(6, 'User', 1, 'interactions', E'--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\nmust_be_follower: false\nmust_be_following: true\nmust_be_following_dm: false\n', now(), now());
|
||||
|
||||
INSERT INTO "identities"
|
||||
@@ -332,19 +377,19 @@ namespace :tests do
|
||||
(2, 'user', NULL, #{user_private_key}, #{user_public_key}, now(), now());
|
||||
|
||||
INSERT INTO "accounts"
|
||||
(id, username, domain, private_key, public_key, created_at, updated_at, remote_url, salmon_url)
|
||||
(id, username, domain, uri, private_key, public_key, created_at, updated_at, remote_url, salmon_url)
|
||||
VALUES
|
||||
(3, 'remote', 'remote.com', NULL, #{remote_public_key}, now(), now(),
|
||||
(3, 'remote', 'remote.com', 'https://remote.com/remote', NULL, #{remote_public_key}, now(), now(),
|
||||
'https://remote.com/@remote', 'https://remote.com/salmon/1'),
|
||||
(4, 'Remote', 'remote.com', NULL, #{remote_public_key}, now(), now(),
|
||||
(4, 'Remote', 'remote.com', 'https://remote.com/Remote', NULL, #{remote_public_key}, now(), now(),
|
||||
'https://remote.com/@Remote', 'https://remote.com/salmon/1'),
|
||||
(5, 'REMOTE', 'Remote.com', NULL, #{remote_public_key2}, now() - interval '1 year', now() - interval '1 year',
|
||||
(5, 'REMOTE', 'Remote.com', 'https://remote.com/stale/remote', NULL, #{remote_public_key2}, now() - interval '1 year', now() - interval '1 year',
|
||||
'https://remote.com/stale/@REMOTE', 'https://remote.com/stale/salmon/1');
|
||||
|
||||
INSERT INTO "accounts"
|
||||
(id, username, domain, private_key, public_key, created_at, updated_at, protocol, inbox_url, outbox_url, followers_url)
|
||||
(id, username, domain, uri, private_key, public_key, created_at, updated_at, protocol, inbox_url, outbox_url, followers_url)
|
||||
VALUES
|
||||
(6, 'bob', 'ActivityPub.com', NULL, #{remote_public_key_ap}, now(), now(),
|
||||
(6, 'bob', 'ActivityPub.com', 'https://activitypub.com/users/bob', NULL, #{remote_public_key_ap}, now(), now(),
|
||||
1, 'https://activitypub.com/users/bob/inbox', 'https://activitypub.com/users/bob/outbox', 'https://activitypub.com/users/bob/followers');
|
||||
|
||||
INSERT INTO "accounts"
|
||||
@@ -354,24 +399,32 @@ namespace :tests do
|
||||
(8, 'pt_user', NULL, #{user_private_key}, #{user_public_key}, now(), now());
|
||||
|
||||
INSERT INTO "accounts"
|
||||
(id, username, domain, private_key, public_key, created_at, updated_at, protocol, inbox_url, outbox_url, followers_url, suspended)
|
||||
(id, username, domain, uri, private_key, public_key, created_at, updated_at, protocol, inbox_url, outbox_url, followers_url, suspended)
|
||||
VALUES
|
||||
(9, 'evil', 'activitypub.com', NULL, #{remote_public_key_ap}, now(), now(),
|
||||
1, 'https://activitypub.com/users/evil/inbox', 'https://activitypub.com/users/evil/outbox',
|
||||
(9, 'evil', 'activitypub.com', 'https://activitypub.com/users/evil', NULL,
|
||||
#{remote_public_key_ap}, now(), now(), 1,
|
||||
'https://activitypub.com/users/evil/inbox', 'https://activitypub.com/users/evil/outbox',
|
||||
'https://activitypub.com/users/evil/followers', true);
|
||||
|
||||
INSERT INTO "accounts"
|
||||
(id, username, domain, private_key, public_key, created_at, updated_at, suspended)
|
||||
VALUES
|
||||
(10, 'suspended', NULL, #{admin_private_key}, #{admin_public_key}, now(), now(), true),
|
||||
(11, 'deleted', NULL, #{user_private_key}, #{user_public_key}, now(), now(), true);
|
||||
|
||||
-- users
|
||||
|
||||
INSERT INTO "users"
|
||||
(id, account_id, email, created_at, updated_at, admin)
|
||||
VALUES
|
||||
(1, 1, 'admin@localhost', now(), now(), true),
|
||||
(2, 2, 'user@localhost', now(), now(), false);
|
||||
(2, 2, 'user@localhost', now(), now(), false),
|
||||
(3, 10, 'suspended@localhost', now(), now(), false);
|
||||
|
||||
INSERT INTO "users"
|
||||
(id, account_id, email, created_at, updated_at, admin, locale)
|
||||
VALUES
|
||||
(3, 8, 'ptuser@localhost', now(), now(), false, 'pt');
|
||||
(4, 8, 'ptuser@localhost', now(), now(), false, 'pt');
|
||||
|
||||
-- conversations
|
||||
INSERT INTO "conversations" (id, created_at, updated_at) VALUES (1, now(), now());
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
# Integration library between Mastodon backend and Vite
|
||||
module Vite
|
||||
autoload :Builder, 'vite/builder'
|
||||
autoload :Config, 'vite/config'
|
||||
autoload :DevServer, 'vite/dev_server'
|
||||
autoload :Manifest, 'vite/manifest'
|
||||
autoload :NameResolver, 'vite/name_resolver'
|
||||
autoload :Proxy, 'vite/proxy'
|
||||
autoload :Tagger, 'vite/tagger'
|
||||
autoload :TagsHelper, 'vite/tags_helper'
|
||||
autoload :Tasks, 'vite/tasks'
|
||||
|
||||
def self.setup
|
||||
yield config if block_given?
|
||||
end
|
||||
|
||||
def self.config
|
||||
@config ||= Config.new
|
||||
end
|
||||
|
||||
def self.logger
|
||||
@logger ||= config.logger
|
||||
end
|
||||
|
||||
def self.dev_server
|
||||
@dev_server ||= DevServer.new(config:)
|
||||
end
|
||||
|
||||
def self.tagger
|
||||
@tagger ||= Tagger.new(config:, manifest:, dev_server:)
|
||||
end
|
||||
|
||||
def self.manifest
|
||||
@manifest ||= Manifest.new(config:, logger:)
|
||||
end
|
||||
|
||||
def self.tasks
|
||||
@tasks ||= Vite::Tasks.new(config:)
|
||||
end
|
||||
|
||||
def self.preload
|
||||
manifest.load
|
||||
rescue Vite::Manifest::MissingManifestError => e
|
||||
logger.error { e.message }
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,50 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Vite
|
||||
# Execute the configured build command and log its output
|
||||
# @see Vite::Config#build_command
|
||||
class Builder
|
||||
class BuildError < StandardError
|
||||
def initialize(command, exit_status)
|
||||
super("Vite build command '#{command}' failed with status: #{exit_status}")
|
||||
end
|
||||
end
|
||||
|
||||
attr_reader :config, :logger
|
||||
|
||||
def initialize(config:, logger:)
|
||||
@config = config
|
||||
@logger = logger
|
||||
end
|
||||
|
||||
def build
|
||||
logger.info { "Build: Building assets with vite with command: '#{config.build_command}'" }
|
||||
Open3.popen3(config.build_command) do |_stdin, stdout, stderr, wait_thread|
|
||||
read_pipe(stdout) do |line|
|
||||
logger.info { line.strip }
|
||||
end
|
||||
read_pipe(stderr) do |line|
|
||||
logger.error { line.strip }
|
||||
end
|
||||
|
||||
wait_thread.value
|
||||
end
|
||||
end
|
||||
|
||||
def build!
|
||||
status = build
|
||||
|
||||
raise(BuildError.new(config.build_command, status.exitstatus)) unless status.success?
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def read_pipe(io)
|
||||
while (line = io.gets)
|
||||
next if line.blank?
|
||||
|
||||
yield line
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,88 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Vite
|
||||
# Main configuration options to integrate with Vite:
|
||||
# - host: Main host for Vite's dev server. Default: localhost
|
||||
# - port: Main port for Vite's dev server. Default: 5173
|
||||
# - https: Whether to use HTTPS to connect to the dev server or not. Default: false
|
||||
# - base_path: The prefix path added to the assets. Default: /packs-dev/
|
||||
# - tag_strategies: How to generate javascript and stylesheet tags in views. Possible values are:
|
||||
# * dev_server: Generate tags linking directly to the dev server through an internal proxy
|
||||
# * manifest: Generate tags using assets listed in Vite's manifest files
|
||||
# Default: [:dev_server, :manifest]
|
||||
# - manifest_path: Where the manifest file is located. Default: public/packs-dev/.vite/manifest.json
|
||||
# - manifest_assets_path: Where the manifest-assets file is located. Default: public/packs-dev/.vite/manifest-assets.json
|
||||
# - auto_build: Whether to automatically build assets or not. This is useful for tess. Default: false
|
||||
# - build_command: How to build assets when auto_build is enabled. Default: 'yarn build:development'
|
||||
# - out_dir: Output dir for built assets. Default: 'public/packs-dev'
|
||||
# - cache_dir: Vite's build cache path. Default: 'node_modules/.vite'
|
||||
# - logger: Main logger instance for other Vite classes. Default: Logger.new($stdout)
|
||||
class Config
|
||||
attr_accessor :host,
|
||||
:port,
|
||||
:https,
|
||||
:base_path,
|
||||
:tag_strategies,
|
||||
:manifest_path,
|
||||
:manifest_assets_path,
|
||||
:auto_build,
|
||||
:build_command,
|
||||
:out_dir,
|
||||
:cache_dir,
|
||||
:logger
|
||||
|
||||
def initialize(cnf = nil)
|
||||
@host = 'localhost'
|
||||
@port = 5173
|
||||
@https = false
|
||||
@base_path = '/packs-dev/'
|
||||
|
||||
@tag_strategies = [:dev_server, :manifest]
|
||||
@manifest_path = 'public/packs-dev/.vite/manifest.json'
|
||||
@manifest_assets_path = 'public/packs-dev/.vite/manifest-assets.json'
|
||||
|
||||
@auto_build = false
|
||||
@build_command = 'yarn build:development'
|
||||
|
||||
@out_dir = 'public/packs-dev'
|
||||
@cache_dir = 'node_modules/.vite'
|
||||
|
||||
@logger = Logger.new($stdout)
|
||||
|
||||
copy_from(cnf) unless cnf.nil?
|
||||
end
|
||||
|
||||
def https?
|
||||
https
|
||||
end
|
||||
|
||||
def protocol
|
||||
https? ? 'https' : 'http'
|
||||
end
|
||||
|
||||
def backend
|
||||
"#{protocol}://#{host}:#{port}"
|
||||
end
|
||||
|
||||
def auto_build?
|
||||
auto_build
|
||||
end
|
||||
|
||||
def copy_from(other)
|
||||
self.host = other[:host] unless other[:host].nil?
|
||||
self.port = other[:port] unless other[:port].nil?
|
||||
self.https = other[:https] unless other[:https].nil?
|
||||
self.base_path = other[:base_path] unless other[:base_path].nil?
|
||||
|
||||
self.tag_strategies = other[:tag_strategies].map(&:to_sym) unless other[:tag_strategies].nil?
|
||||
self.manifest_path = other[:manifest_path] unless other[:manifest_path].nil?
|
||||
self.manifest_assets_path = other[:manifest_assets_path] unless other[:manifest_assets_path].nil?
|
||||
|
||||
self.out_dir = other[:out_dir] unless other[:out_dir].nil?
|
||||
self.cache_dir = other[:cache_dir] unless other[:cache_dir].nil?
|
||||
|
||||
self.auto_build = other[:auto_build] unless other[:auto_build].nil?
|
||||
self.build_command = other[:build_command] unless other[:build_command].nil?
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,25 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Vite
|
||||
# Check the status of Vite's dev server
|
||||
class DevServer
|
||||
WAIT_TIME = 5 # seconds
|
||||
attr_reader :config
|
||||
|
||||
def initialize(config:)
|
||||
@config = config
|
||||
end
|
||||
|
||||
# Original idea from vite_ruby gem
|
||||
def running?
|
||||
return @running if defined?(@running) && Time.now.to_i - @running_checked_at < WAIT_TIME
|
||||
|
||||
Socket.tcp(config.host, config.port).close
|
||||
@running = true
|
||||
rescue
|
||||
@running = false
|
||||
ensure
|
||||
@running_checked_at = Time.now.to_i
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,192 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Vite
|
||||
# We use two manifest files to list the assets loaded in our backend:
|
||||
# - manifest.json: This is the main file that lists all the javascript and stylesheets our frontend app uses
|
||||
# - manifest-assets.json: This only lists media assets linked directly from our backend, mainly images
|
||||
#
|
||||
# Not all the assets listed in the manifest.json file are linked or used by the app view, so we don't need to
|
||||
# keep track of those. The idea behind this class is to keep track only of the main entrypoints and all their
|
||||
# subsequent imports. Imports in this case include other javascript modules and stylesheets generated by Vite.
|
||||
#
|
||||
# This class focuses on reducing the amount of data we keep per entrypoint and making fast lookups. To do so
|
||||
# it keeps two main datastructures:
|
||||
# - entries: A Hash with references to each main entrypoint (including media assets)
|
||||
# - pool: An Array with all the referenced imports and stylesheets
|
||||
#
|
||||
# Each entrypoint has a list of IDs for each import and stylesheet that it needs to load, this ID is
|
||||
# an index to the main pool. With this the referenced asset is stored only once and referenced across
|
||||
# entries with a unique ID. In the original manifest files references are also nested, if an entrypoint
|
||||
# imports a javascript module, this first module can import other modules and stylesheet and so on. To keep
|
||||
# fetching entrypoints fast, the final list of modules and stylesheets to load per entrypoint
|
||||
# is expanded when loading the manifest data and not when rendering views. Each entrypoint has the final
|
||||
# list of IDs of imports and stylesheets it will need to link in the backend, without further recursive
|
||||
# checks.
|
||||
class Manifest
|
||||
class MissingManifestError < StandardError; end
|
||||
|
||||
class MissingEntryError < StandardError
|
||||
def initialize(entry)
|
||||
super("Failed to find entry '#{entry}' in manifest files")
|
||||
end
|
||||
end
|
||||
|
||||
Entrypoint = Struct.new(:file, :integrity, :import_ids, :stylesheet_ids)
|
||||
Asset = Struct.new(:file, :integrity)
|
||||
|
||||
attr_reader :config, :entries, :pool, :logger
|
||||
|
||||
def initialize(config:, logger:)
|
||||
@config = config
|
||||
@virtual = {}
|
||||
@entries = {}
|
||||
@pool = []
|
||||
@loaded = false
|
||||
@logger = logger
|
||||
end
|
||||
|
||||
def reload
|
||||
@loaded = false
|
||||
load
|
||||
end
|
||||
|
||||
def load
|
||||
return if @loaded
|
||||
|
||||
retries = 0
|
||||
|
||||
begin
|
||||
build if retries.positive?
|
||||
load_manifest
|
||||
@loaded = true
|
||||
rescue Errno::ENOENT => e
|
||||
if retries.zero? && config.auto_build?
|
||||
retries = 1
|
||||
retry
|
||||
else
|
||||
raise MissingManifestError, e.message
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def fetch(name, type: nil)
|
||||
load
|
||||
|
||||
key = type == :virtual ? @virtual[name] : name
|
||||
|
||||
entries[key]
|
||||
end
|
||||
|
||||
def fetch!(name, type: nil)
|
||||
fetch(name, type:) || raise(MissingEntryError, name)
|
||||
end
|
||||
|
||||
def imports_for(entry)
|
||||
find_entries(entry[:import_ids] || [])
|
||||
end
|
||||
|
||||
def stylesheets_for(entry)
|
||||
find_entries(entry[:stylesheet_ids] || [])
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def load_manifest
|
||||
@virtual = {}
|
||||
@entries = {}
|
||||
@pool = []
|
||||
# intermediate Hash for fast lookups while parsing the manifest
|
||||
@lookup = {}
|
||||
|
||||
logger.debug { "loading manifest file: #{config.manifest_path}" }
|
||||
json = JSON.load_file(config.manifest_path)
|
||||
json.each do |key, raw|
|
||||
# Only select main entrypoints and locales
|
||||
next unless raw['isEntry'] || key.start_with?('mastodon/locales/')
|
||||
|
||||
import_ids, stylesheet_ids = resolve_relations(json, raw)
|
||||
|
||||
@virtual[raw['name']] = key
|
||||
@entries[key] = Entrypoint.new(
|
||||
raw['file'],
|
||||
raw['integrity'],
|
||||
import_ids,
|
||||
stylesheet_ids
|
||||
)
|
||||
end
|
||||
|
||||
logger.debug { "loading manifest file: #{config.manifest_assets_path}" }
|
||||
assets = JSON.load_file(config.manifest_assets_path)
|
||||
assets.each do |key, raw|
|
||||
@entries[key] = Asset.new(
|
||||
raw['file'],
|
||||
raw['integrity']
|
||||
)
|
||||
end
|
||||
ensure
|
||||
@lookup = {}
|
||||
end
|
||||
|
||||
def build
|
||||
logger.debug { 'AutoBuild enabled' }
|
||||
builder.build
|
||||
end
|
||||
|
||||
def builder
|
||||
@builder ||= Vite::Builder.new(config:, logger:)
|
||||
end
|
||||
|
||||
def resolve_relations(manifest, raw)
|
||||
# NOTE: By using Set we make sure we add each asset only once
|
||||
imports = Set.new
|
||||
stylesheets = Set.new
|
||||
|
||||
raw['imports']&.each do |import|
|
||||
raw_import = manifest[import]
|
||||
next unless raw_import
|
||||
|
||||
id, deps = lookup(file: raw_import['file'], integrity: raw_import['integrity']) do
|
||||
resolve_relations(manifest, raw_import)
|
||||
end
|
||||
|
||||
imports.merge(deps[0])
|
||||
stylesheets.merge(deps[1])
|
||||
imports.add id
|
||||
end
|
||||
|
||||
raw['css']&.each do |stylesheet|
|
||||
# the css field includes the file names of the stylesheets and not
|
||||
# the src names which are the ones used as keys in the manifest
|
||||
raw_style = manifest.values.find { |value| value['file'] == stylesheet }
|
||||
# some listed CSS files are not included as a entry in the manifest,
|
||||
# but they are among the generated assets. We can still link to them
|
||||
# but without the integrity field
|
||||
raw_style = { 'file' => stylesheet } if raw_style.nil?
|
||||
|
||||
id, = lookup(file: raw_style['file'], integrity: raw_style['integrity'])
|
||||
stylesheets.add id
|
||||
end
|
||||
|
||||
[imports, stylesheets]
|
||||
end
|
||||
|
||||
# Lookup in the internal cache if an entry has been processed
|
||||
# If not, yield and save the result of the block as the entry deps
|
||||
def lookup(file:, integrity:)
|
||||
id, deps = @lookup[file] || []
|
||||
|
||||
if id.nil?
|
||||
@pool << Asset.new(file, integrity)
|
||||
id = @pool.size - 1 # last ID
|
||||
deps = yield if block_given?
|
||||
@lookup[file] = [id, deps]
|
||||
end
|
||||
|
||||
[id, deps]
|
||||
end
|
||||
|
||||
def find_entries(ids)
|
||||
ids.filter_map { |id| pool[id] }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,49 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Vite
|
||||
# When using assets in frontend views, we need to have an actual path that serves the asset.
|
||||
# This path needs to include:
|
||||
# - Vite's base_path, this is where the bundle is generated
|
||||
# - If the asset needs to be included inside the main entrypoints path or not
|
||||
#
|
||||
# For convenience assets that are single file names (i.e: application.ts) are considered to
|
||||
# be entrypoints. To make them work with Vite the `entrypoints/` prefix needs to be added.
|
||||
# If an asset is referenced with a relative path like `styles/application.scss`, that path
|
||||
# is used as is given.
|
||||
#
|
||||
# Examples:
|
||||
# resolver = Vite::NameResolver.new(config: Vite.config)
|
||||
# resolver.full_path('application.ts')
|
||||
# # => '/packs-dev/entrypoints/application.ts'
|
||||
# resolver.full_path('styles/application.scss')
|
||||
# # => '/packs-dev/styles/application.scss'
|
||||
#
|
||||
# The #full_path is useful when working with Vite's dev server.
|
||||
# When serving asssets from a manifest, it is necessary to resolve first the #entrypoint_path
|
||||
# to have a proper reference of the asset inside the manifest file and then generate the
|
||||
# #bundle_path of the asset's real file name defined in the manifest
|
||||
class NameResolver
|
||||
attr_reader :config
|
||||
|
||||
def initialize(config:)
|
||||
@config = config
|
||||
end
|
||||
|
||||
# Full path to the given asset
|
||||
def full_path(name)
|
||||
bundle_path(entrypoint_path(name))
|
||||
end
|
||||
|
||||
# Determines if an asset name should be considered an entrypoint and builds
|
||||
# the path accordingly
|
||||
def entrypoint_path(name)
|
||||
# If the name is a single file we assume it is inside app/javascripts/entrypoints
|
||||
name.include?('/') ? name : "entrypoints/#{name}"
|
||||
end
|
||||
|
||||
# Asset's bundle path that includes Vite's base_path as a prefix
|
||||
def bundle_path(name)
|
||||
"#{config.base_path}#{name}"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,25 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'rack/proxy'
|
||||
|
||||
module Vite
|
||||
# Simple proxy that redirects asset requests to the running Vite dev server
|
||||
class Proxy < Rack::Proxy
|
||||
attr_reader :config, :dev_server
|
||||
|
||||
def initialize(app, config:, dev_server:, **)
|
||||
@config = config
|
||||
@dev_server = dev_server
|
||||
|
||||
super(app, backend: config.backend, ssl_verify_none: !config.https?, **)
|
||||
end
|
||||
|
||||
def perform_request(env)
|
||||
if dev_server.running? && env['PATH_INFO'].start_with?(config.base_path)
|
||||
super
|
||||
else
|
||||
@app.call(env)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,241 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Vite
|
||||
# This class generates the HTML tags needed to load assets in the app views
|
||||
#
|
||||
# It does it by following different strategies:
|
||||
# - dev_server: If Vite's dev server is running, it generates a simple tag
|
||||
# for an asset that the server will know how to handle
|
||||
# - manifest: When using a manifest, each asset is expanded in a collection
|
||||
# of tags that include the main asset and all of their dependencies.
|
||||
# For example a javascript asset includes an include tag for the main
|
||||
# javascript file, preload tags for each of their dependencies and
|
||||
# stylesheet links for each css module file generated by Vite
|
||||
#
|
||||
# When both :dev_server and :manifest strategies are defined, it will first
|
||||
# try to use the :dev_server and if it's not running it will fallback to :manifest
|
||||
class Tagger
|
||||
SKIP = Object.new
|
||||
|
||||
module Common
|
||||
def vite_preload_tag(helper, *sources, crossorigin:, **options)
|
||||
url_options = options.extract!(:host, :protocol)
|
||||
asset_paths = sources.map { |source| helper.path_to_asset(source, **url_options) }
|
||||
helper.try(:request).try(
|
||||
:send_early_hints,
|
||||
'Link' => asset_paths.map do |href|
|
||||
%(<#{href}>; rel=modulepreload; as=script; crossorigin=#{crossorigin})
|
||||
end.join(',')
|
||||
)
|
||||
|
||||
tags = asset_paths.map do |href|
|
||||
helper.tag.link(rel: 'modulepreload', href:, as: 'script', crossorigin:, **options)
|
||||
end
|
||||
|
||||
helper.safe_join(tags)
|
||||
end
|
||||
end
|
||||
|
||||
# When Vite's dev server is running we just need to generate tags
|
||||
# linking to the main assets (javascript, stylesheets, etc) and the
|
||||
# dev server will do the rest
|
||||
class DevServerStrategy
|
||||
include Common
|
||||
|
||||
attr_reader :config, :resolver, :dev_server
|
||||
|
||||
def initialize(config:, dev_server:)
|
||||
@config = config
|
||||
@dev_server = dev_server || DevServer.new(config:)
|
||||
@resolver = NameResolver.new(config:)
|
||||
end
|
||||
|
||||
def vite_client_tag(helper, crossorigin: 'anonymous', **)
|
||||
return SKIP unless dev_server.running?
|
||||
|
||||
src = resolver.bundle_path('@vite/client')
|
||||
helper.javascript_include_tag(src, type: 'module', extname: false, crossorigin:, **)
|
||||
end
|
||||
|
||||
def vite_react_refresh_tag(helper, **options)
|
||||
return SKIP unless dev_server.running?
|
||||
|
||||
options[:nonce] = true unless options.key?(:nonce)
|
||||
|
||||
react_refresh = resolver.bundle_path('@react-refresh')
|
||||
|
||||
preamble = <<~REACT_PREAMBLE_CODE.html_safe # rubocop:disable Rails/OutputSafety
|
||||
import RefreshRuntime from '#{react_refresh}'
|
||||
RefreshRuntime.injectIntoGlobalHook(window)
|
||||
window.$RefreshReg$ = () => {}
|
||||
window.$RefreshSig$ = () => (type) => type
|
||||
window.__vite_plugin_react_preamble_installed__ = true
|
||||
REACT_PREAMBLE_CODE
|
||||
|
||||
helper.javascript_tag(preamble, type: :module, **options)
|
||||
end
|
||||
|
||||
def vite_javascript_tag(helper, *names, type: 'module', crossorigin: '', asset_type: '', **) # rubocop:disable Lint/UnusedMethodArgument
|
||||
return SKIP unless dev_server.running?
|
||||
|
||||
scripts = names.map { |name| resolver.full_path(name) }
|
||||
|
||||
helper.javascript_include_tag(*scripts, crossorigin:, type:, extname: false, **)
|
||||
end
|
||||
|
||||
def vite_stylesheet_tag(helper, *names, type: :stylesheet, **options) # rubocop:disable Lint/UnusedMethodArgument
|
||||
return SKIP unless dev_server.running?
|
||||
|
||||
style_paths = names.map { |name| resolver.full_path(name) }
|
||||
|
||||
options[:extname] = false
|
||||
|
||||
helper.stylesheet_link_tag(*style_paths, **options)
|
||||
end
|
||||
|
||||
def vite_asset_path(helper, name, **_options)
|
||||
return SKIP unless dev_server.running?
|
||||
|
||||
helper.path_to_asset resolver.full_path(name)
|
||||
end
|
||||
|
||||
def vite_polyfills_tag(*)
|
||||
return SKIP unless dev_server.running?
|
||||
|
||||
''
|
||||
end
|
||||
|
||||
def vite_preload_file_tag(helper, name, crossorigin: 'anonymous', **)
|
||||
return SKIP unless dev_server.running?
|
||||
|
||||
vite_preload_tag(helper, resolver.full_path(name), crossorigin:, **)
|
||||
end
|
||||
end
|
||||
|
||||
class ManifestStrategy
|
||||
include Common
|
||||
|
||||
attr_reader :config, :manifest, :resolver
|
||||
|
||||
def initialize(config:, manifest: nil)
|
||||
@config = config
|
||||
@manifest = manifest || Manifest.new(config:, logger: config.logger)
|
||||
@resolver = NameResolver.new(config:)
|
||||
end
|
||||
|
||||
def vite_client_tag(*)
|
||||
''
|
||||
end
|
||||
|
||||
def vite_react_refresh_tag(*)
|
||||
''
|
||||
end
|
||||
|
||||
def vite_javascript_tag(helper, *names, type: 'module', crossorigin: '', asset_type: '', media: nil, **)
|
||||
names = names.map { |name| resolver.entrypoint_path(name) }
|
||||
|
||||
scripts = []
|
||||
preloads = []
|
||||
stylesheets = []
|
||||
entries = names.map { |name| manifest.fetch!(name, type: asset_type) }
|
||||
|
||||
entries.each do |entry|
|
||||
scripts << helper.javascript_include_tag(
|
||||
resolver.bundle_path(entry[:file]),
|
||||
integrity: entry[:integrity],
|
||||
crossorigin:,
|
||||
type:,
|
||||
extname: false,
|
||||
**
|
||||
)
|
||||
|
||||
preloads = manifest.imports_for(entry).map do |import|
|
||||
vite_preload_tag(
|
||||
helper,
|
||||
resolver.bundle_path(import[:file]),
|
||||
integrity: import[:integrity],
|
||||
crossorigin:,
|
||||
**
|
||||
)
|
||||
end
|
||||
|
||||
stylesheets = manifest.stylesheets_for(entry).map do |stylesheet|
|
||||
helper.stylesheet_link_tag(
|
||||
resolver.bundle_path(stylesheet[:file]),
|
||||
integrity: stylesheet[:integrity],
|
||||
crossorigin:,
|
||||
media:,
|
||||
**
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
helper.safe_join(scripts + preloads + stylesheets)
|
||||
end
|
||||
|
||||
def vite_stylesheet_tag(helper, *names, type: :stylesheet, **options)
|
||||
options[:extname] = false
|
||||
|
||||
stylesheets = names.map do |name|
|
||||
entry = manifest.fetch!(resolver.entrypoint_path(name), type:)
|
||||
helper.stylesheet_link_tag(
|
||||
resolver.bundle_path(entry[:file]),
|
||||
integrity: entry[:integrity],
|
||||
**options
|
||||
)
|
||||
end
|
||||
|
||||
helper.safe_join(stylesheets)
|
||||
end
|
||||
|
||||
def vite_asset_path(helper, name, type: nil, **)
|
||||
entry = manifest.fetch!(resolver.entrypoint_path(name), type:)
|
||||
helper.path_to_asset resolver.bundle_path(entry[:file])
|
||||
end
|
||||
|
||||
def vite_polyfills_tag(helper, crossorigin: 'anonymous', **)
|
||||
entry = manifest.fetch!('polyfills', type: :virtual)
|
||||
|
||||
helper.javascript_include_tag(
|
||||
resolver.bundle_path(entry[:file]),
|
||||
type: 'module',
|
||||
integrity: entry[:integrity],
|
||||
crossorigin:,
|
||||
**
|
||||
)
|
||||
end
|
||||
|
||||
def vite_preload_file_tag(helper, name, crossorigin: 'anonymous', **)
|
||||
entry = manifest.fetch(resolver.entrypoint_path(name))
|
||||
return SKIP unless entry
|
||||
|
||||
vite_preload_tag(helper, resolver.bundle_path(entry[:file]), integrity: entry[:integrity], crossorigin:, **)
|
||||
end
|
||||
end
|
||||
|
||||
attr_reader :strategies
|
||||
|
||||
def initialize(config:, manifest: nil, dev_server: nil)
|
||||
@strategies = config.tag_strategies.filter_map do |name|
|
||||
case name
|
||||
when :dev_server
|
||||
DevServerStrategy.new(config:, dev_server:)
|
||||
when :manifest
|
||||
ManifestStrategy.new(config:, manifest:)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def method_missing(method, ...)
|
||||
return super unless method.to_s.start_with?('vite_')
|
||||
|
||||
strategies.lazy.map { |s| s.__send__(method, ...) }.find { |result| result != SKIP } || ''
|
||||
end
|
||||
|
||||
def respond_to_missing?(method, include_private = false)
|
||||
return super unless method.to_s.start_with?('vite_')
|
||||
|
||||
strategies.all? { |s| s.respond_to?(method, include_private) }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,41 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Vite
|
||||
module TagsHelper
|
||||
def vite_javascript_tag(*names, type: 'module', crossorigin: '', **)
|
||||
Vite.tagger.vite_javascript_tag(self, *names, type:, crossorigin:, **)
|
||||
end
|
||||
|
||||
def vite_typescript_tag(*names, **)
|
||||
vite_javascript_tag(*names, asset_type: :typescript, **)
|
||||
end
|
||||
|
||||
def vite_stylesheet_tag(*names, type: :stylesheet, **)
|
||||
Vite.tagger.vite_stylesheet_tag(self, *names, type:, **)
|
||||
end
|
||||
|
||||
def vite_client_tag(crossorigin: 'anonymous', **)
|
||||
Vite.tagger.vite_client_tag(self, crossorigin:, **)
|
||||
end
|
||||
|
||||
def vite_react_refresh_tag(**)
|
||||
Vite.tagger.vite_react_refresh_tag(self, **)
|
||||
end
|
||||
|
||||
def vite_asset_path(name, **)
|
||||
Vite.tagger.vite_asset_path(self, name, **)
|
||||
end
|
||||
|
||||
def vite_polyfills_tag(crossorigin: 'anonymous', **)
|
||||
Vite.tagger.vite_polyfills_tag(self, crossorigin:, **)
|
||||
end
|
||||
|
||||
def vite_preload_file_tag(name, crossorigin: 'anonymous', **)
|
||||
Vite.tagger.vite_preload_file_tag(self, name, crossorigin:, **)
|
||||
end
|
||||
|
||||
def vite_preload_tag(*sources, crossorigin:, **)
|
||||
Vite.tagger.vite_preload_tag(self, *sources, crossorigin:, **)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,33 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Vite
|
||||
class Tasks
|
||||
attr_reader :config, :logger
|
||||
|
||||
def initialize(config:)
|
||||
@config = config
|
||||
# We want tasks to always log out to STDOUT
|
||||
@logger = ActiveSupport::TaggedLogging.new(
|
||||
ActiveSupport::Logger.new($stdout)
|
||||
).tagged('vite')
|
||||
end
|
||||
|
||||
# Intended to run within assets:precompile task
|
||||
def precompile
|
||||
Vite::Builder.new(config:, logger:).build!
|
||||
end
|
||||
|
||||
# Intended to run within assets:clobber task
|
||||
def clobber
|
||||
[config.out_dir, config.cache_dir].each do |path|
|
||||
dir = Rails.root.join(path)
|
||||
if dir.exist?
|
||||
logger.info { "Deleting directory '#{dir}'" }
|
||||
dir.rmtree
|
||||
else
|
||||
logger.info { "Directory '#{dir}' doesn't exist, nothing to delete" }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,153 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module ViteRuby::ManifestIntegrityExtension
|
||||
def path_and_integrity_for(name, **)
|
||||
entry = lookup!(name, **)
|
||||
|
||||
{ path: entry.fetch('file'), integrity: entry.fetch('integrity', nil) }
|
||||
end
|
||||
|
||||
def load_manifest
|
||||
# Invalidate the name lookup cache when reloading manifest
|
||||
@name_lookup_cache = nil unless dev_server_running?
|
||||
|
||||
super
|
||||
end
|
||||
|
||||
def load_name_lookup_cache
|
||||
JSON.load_file(config.build_output_dir.join('.vite/manifest-lookup.json'))
|
||||
end
|
||||
|
||||
# Upstream's `virtual` type is a hack, re-implement it with efficient exact name lookup
|
||||
def resolve_virtual_entry(name)
|
||||
return name if dev_server_running?
|
||||
|
||||
@name_lookup_cache ||= load_name_lookup_cache
|
||||
|
||||
@name_lookup_cache.fetch(name)
|
||||
end
|
||||
|
||||
# Find a manifest entry by the *final* file name
|
||||
def integrity_hash_for_file(file_name)
|
||||
@integrity_cache ||= {}
|
||||
@integrity_cache[file_name] ||= begin
|
||||
entry = manifest.find { |_key, entry| entry['file'] == file_name }
|
||||
|
||||
entry[1].fetch('integrity', nil) if entry
|
||||
end
|
||||
end
|
||||
|
||||
def resolve_entries_with_integrity(*names, **options)
|
||||
entries = names.map { |name| lookup!(name, **options) }
|
||||
script_paths = entries.map do |entry|
|
||||
{
|
||||
file: entry.fetch('file'),
|
||||
# TODO: Secure this so we require the integrity hash outside of dev
|
||||
integrity: entry['integrity'],
|
||||
}
|
||||
end
|
||||
|
||||
imports = dev_server_running? ? [] : entries.flat_map { |entry| import_chunks_for(entry) }
|
||||
|
||||
{
|
||||
scripts: script_paths,
|
||||
imports: imports.filter_map { |entry| { file: entry.fetch('file'), integrity: entry.fetch('integrity') } }.uniq,
|
||||
stylesheets: dev_server_running? ? [] : (entries + imports).flat_map { |entry| entry['css'] }.compact.uniq,
|
||||
}
|
||||
end
|
||||
|
||||
# We need to override this method to not include the manifest, as in our case it is too large and will cause a JSON max nesting error rather than raising the expected exception
|
||||
def missing_entry_error(name, **)
|
||||
raise ViteRuby::MissingEntrypointError.new(
|
||||
file_name: resolve_entry_name(name, **),
|
||||
last_build: builder.last_build_metadata,
|
||||
manifest: '',
|
||||
config: config
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
ViteRuby::Manifest.prepend ViteRuby::ManifestIntegrityExtension
|
||||
|
||||
module ViteRails::TagHelpers::IntegrityExtension
|
||||
def vite_javascript_tag(*names,
|
||||
type: 'module',
|
||||
asset_type: :javascript,
|
||||
skip_preload_tags: false,
|
||||
skip_style_tags: false,
|
||||
crossorigin: '',
|
||||
media: 'screen',
|
||||
**options)
|
||||
entries = vite_manifest.resolve_entries_with_integrity(*names, type: asset_type)
|
||||
|
||||
''.html_safe.tap do |tags|
|
||||
entries.fetch(:scripts).each do |script|
|
||||
tags << javascript_include_tag(
|
||||
script[:file],
|
||||
integrity: script[:integrity],
|
||||
crossorigin: crossorigin,
|
||||
type: type,
|
||||
extname: false,
|
||||
**options
|
||||
)
|
||||
end
|
||||
|
||||
unless skip_preload_tags
|
||||
entries.fetch(:imports).each do |import|
|
||||
tags << vite_preload_tag(import[:file], integrity: import[:integrity], crossorigin: crossorigin, **options)
|
||||
end
|
||||
end
|
||||
|
||||
options[:extname] = false if Rails::VERSION::MAJOR >= 7
|
||||
|
||||
unless skip_style_tags
|
||||
entries.fetch(:stylesheets).each do |stylesheet|
|
||||
# This is for stylesheets imported from Javascript. The entry for the JS entrypoint only contains the final CSS file name, so we need to look it up in the manifest
|
||||
tags << stylesheet_link_tag(
|
||||
stylesheet,
|
||||
integrity: vite_manifest.integrity_hash_for_file(stylesheet),
|
||||
media: media,
|
||||
crossorigin: crossorigin,
|
||||
**options
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def vite_stylesheet_tag(*names, type: :stylesheet, **options)
|
||||
''.html_safe.tap do |tags|
|
||||
names.each do |name|
|
||||
entry = vite_manifest.path_and_integrity_for(name, type:)
|
||||
|
||||
options[:extname] = false if Rails::VERSION::MAJOR >= 7
|
||||
|
||||
tags << stylesheet_link_tag(entry[:path], integrity: entry[:integrity], **options)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def vite_preload_file_tag(name,
|
||||
asset_type: :javascript,
|
||||
crossorigin: 'anonymous', **options)
|
||||
''.html_safe.tap do |tags|
|
||||
entries = vite_manifest.resolve_entries_with_integrity(name, type: asset_type)
|
||||
|
||||
entries.fetch(:scripts).each do |script|
|
||||
tags << vite_preload_tag(script[:file], integrity: script[:integrity], crossorigin: crossorigin, **options)
|
||||
end
|
||||
end
|
||||
rescue ViteRuby::MissingEntrypointError
|
||||
# Ignore this error, it is not critical if the file is not preloaded
|
||||
end
|
||||
|
||||
def vite_polyfills_tag(crossorigin: 'anonymous', **)
|
||||
return if ViteRuby.instance.dev_server_running?
|
||||
|
||||
entry = vite_manifest.path_and_integrity_for('polyfills', type: :virtual)
|
||||
|
||||
javascript_include_tag(entry[:path], type: 'module', integrity: entry[:integrity], crossorigin: crossorigin, **)
|
||||
end
|
||||
end
|
||||
|
||||
ViteRails::TagHelpers.prepend ViteRails::TagHelpers::IntegrityExtension
|
||||
Reference in new issue
Block a user