Compare commits
15
Commits
39f6f97707
...
v0.3.8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d15bf00512 | ||
|
|
5398036d3b
|
||
|
|
2ab8482359
|
||
|
|
91f0141b86
|
||
|
|
af76458da0
|
||
|
|
81f57566a7
|
||
|
|
adffc1efeb
|
||
|
|
4c7adcb58a
|
||
|
|
1fec94cda8
|
||
|
|
c3a42b935e
|
||
|
|
3f7604d4c8
|
||
|
|
2c48d247b8
|
||
|
|
fea6ec56fc
|
||
|
|
9755e18087 | ||
|
|
f6688ce573 |
No files matched your search
@@ -0,0 +1,124 @@
|
|||||||
|
name: Publish NuGet packages
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
env:
|
||||||
|
NUGET_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
|
||||||
|
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: '1'
|
||||||
|
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||||
|
LD_LIBRARY_PATH: /opt/dotnet-libs/usr/lib/x86_64-linux-gnu
|
||||||
|
SSL_CERT_FILE: /opt/ca-certificates.crt
|
||||||
|
steps:
|
||||||
|
- name: Fetch exact tagged source
|
||||||
|
env:
|
||||||
|
GITEA_REF: ${{ gitea.ref }}
|
||||||
|
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
tag="${GITEA_REF#refs/tags/}"
|
||||||
|
case "$tag" in
|
||||||
|
v[0-9]*) ;;
|
||||||
|
*) echo "Expected a version tag ref, got: $GITEA_REF" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
export SHRINKSDK_ARCHIVE_URL="https://git.crash.work/${GITEA_REPOSITORY}/archive/${tag}.tar.gz"
|
||||||
|
node --input-type=module <<'NODE'
|
||||||
|
import { writeFile } from 'node:fs/promises';
|
||||||
|
|
||||||
|
const response = await fetch(process.env.SHRINKSDK_ARCHIVE_URL);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Release archive download failed: ${response.status} ${response.statusText}`);
|
||||||
|
}
|
||||||
|
await writeFile('release.tar.gz', new Uint8Array(await response.arrayBuffer()));
|
||||||
|
NODE
|
||||||
|
mkdir release
|
||||||
|
tar -xzf release.tar.gz --strip-components=1 -C release
|
||||||
|
rm -f release.tar.gz
|
||||||
|
printf '%s' "$tag" > release/.shrink-sdk-release-tag
|
||||||
|
|
||||||
|
- name: Install .NET 8 SDK
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
node --input-type=module <<'NODE'
|
||||||
|
import { writeFile } from 'node:fs/promises';
|
||||||
|
import { rootCertificates } from 'node:tls';
|
||||||
|
|
||||||
|
await writeFile('/opt/ca-certificates.crt', rootCertificates.join('\n'));
|
||||||
|
|
||||||
|
const metadataResponse = await fetch('https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/8.0/releases.json');
|
||||||
|
if (!metadataResponse.ok) throw new Error(`Release metadata download failed: ${metadataResponse.status}`);
|
||||||
|
const metadata = await metadataResponse.json();
|
||||||
|
const sdkVersion = metadata['latest-sdk'];
|
||||||
|
const release = metadata.releases.find(item => item.sdk?.version === sdkVersion);
|
||||||
|
const file = release?.sdk?.files?.find(item => item.rid === 'linux-x64' && item.name.endsWith('.tar.gz'));
|
||||||
|
if (!file) throw new Error(`Linux x64 SDK archive not found for ${sdkVersion}`);
|
||||||
|
const archiveUrl = `https://dotnetcli.blob.core.windows.net/dotnet/Sdk/${sdkVersion}/dotnet-sdk-${sdkVersion}-linux-x64.tar.gz`;
|
||||||
|
const archiveResponse = await fetch(archiveUrl);
|
||||||
|
if (!archiveResponse.ok) throw new Error(`SDK download failed: ${archiveResponse.status}`);
|
||||||
|
await writeFile('/tmp/dotnet-sdk.tar.gz', new Uint8Array(await archiveResponse.arrayBuffer()));
|
||||||
|
|
||||||
|
const poolUrl = 'https://deb.debian.org/debian-security/pool/updates/main/o/openssl/';
|
||||||
|
const poolResponse = await fetch(poolUrl);
|
||||||
|
if (!poolResponse.ok) throw new Error(`OpenSSL package index download failed: ${poolResponse.status}`);
|
||||||
|
const poolIndex = await poolResponse.text();
|
||||||
|
const packages = [...poolIndex.matchAll(/href="(libssl3_[^"]+_amd64\.deb)"/g)].map(match => match[1]).sort();
|
||||||
|
const packageName = packages.at(-1);
|
||||||
|
if (!packageName) throw new Error('Debian libssl3 package was not found');
|
||||||
|
const packageResponse = await fetch(poolUrl + packageName);
|
||||||
|
if (!packageResponse.ok) throw new Error(`OpenSSL package download failed: ${packageResponse.status}`);
|
||||||
|
await writeFile('/tmp/libssl3.deb', new Uint8Array(await packageResponse.arrayBuffer()));
|
||||||
|
NODE
|
||||||
|
mkdir -p /opt/dotnet
|
||||||
|
tar -xzf /tmp/dotnet-sdk.tar.gz -C /opt/dotnet
|
||||||
|
mkdir -p /opt/dotnet-libs
|
||||||
|
dpkg-deb -x /tmp/libssl3.deb /opt/dotnet-libs
|
||||||
|
rm -f /tmp/dotnet-sdk.tar.gz
|
||||||
|
rm -f /tmp/libssl3.deb
|
||||||
|
/opt/dotnet/dotnet --info
|
||||||
|
|
||||||
|
- name: Validate, pack and publish
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
: "${NUGET_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
|
||||||
|
export PATH="/opt/dotnet:$PATH"
|
||||||
|
cd release
|
||||||
|
tag="$(cat .shrink-sdk-release-tag)"
|
||||||
|
projects=()
|
||||||
|
if [[ -d DotNet~ ]]; then
|
||||||
|
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find DotNet~ -type f -name '*.csproj' -print0)
|
||||||
|
fi
|
||||||
|
if [[ -d Godot~ ]]; then
|
||||||
|
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find Godot~ -type f -name '*.csproj' -print0)
|
||||||
|
fi
|
||||||
|
if [[ "${#projects[@]}" -eq 0 ]]; then
|
||||||
|
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find . -maxdepth 1 -type f -name '*.csproj' -print0)
|
||||||
|
fi
|
||||||
|
test "${#projects[@]}" -gt 0
|
||||||
|
if [[ -f package.json ]]; then
|
||||||
|
version="$(node -p "require('./package.json').version")"
|
||||||
|
else
|
||||||
|
version="$(dotnet msbuild "${projects[0]}" -getProperty:Version -nologo)"
|
||||||
|
fi
|
||||||
|
test "$tag" = "v$version"
|
||||||
|
mkdir -p packages
|
||||||
|
for project in "${projects[@]}"; do
|
||||||
|
dotnet restore "$project" --configfile NuGet.Config
|
||||||
|
dotnet pack "$project" --configuration Release --no-restore --output "$PWD/packages" --include-symbols --include-source
|
||||||
|
done
|
||||||
|
find packages -maxdepth 1 -name '*.nupkg' -type f | grep -q .
|
||||||
|
dotnet nuget push 'packages/*.nupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
|
||||||
|
if compgen -G 'packages/*.snupkg' > /dev/null; then
|
||||||
|
dotnet nuget push 'packages/*.snupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
|
||||||
|
fi
|
||||||
@@ -8,3 +8,11 @@
|
|||||||
/Tools~/**/[Oo]bj/
|
/Tools~/**/[Oo]bj/
|
||||||
*.user
|
*.user
|
||||||
*.DotSettings.user
|
*.DotSettings.user
|
||||||
|
/DotNet~/**/[Bb]in/
|
||||||
|
/DotNet~/**/[Oo]bj/
|
||||||
|
/Godot~/**/[Bb]in/
|
||||||
|
/Godot~/**/[Oo]bj/
|
||||||
|
/artifacts/
|
||||||
|
/packages/
|
||||||
|
!DotNet~/**/*.csproj
|
||||||
|
!Godot~/**/*.csproj
|
||||||
@@ -6,3 +6,9 @@ Tools~/
|
|||||||
*.sln
|
*.sln
|
||||||
*.user
|
*.user
|
||||||
*.DotSettings.user
|
*.DotSettings.user
|
||||||
|
DotNet~/
|
||||||
|
Godot~/
|
||||||
|
NuGet.Config
|
||||||
|
Directory.Build.props
|
||||||
|
NuGet.Config.meta
|
||||||
|
Directory.Build.props.meta
|
||||||
@@ -2,6 +2,47 @@
|
|||||||
|
|
||||||
本文件记录 `ShrinkModFramework` 在当前工作区中的包内变更。
|
本文件记录 `ShrinkModFramework` 在当前工作区中的包内变更。
|
||||||
|
|
||||||
|
## [0.3.8] - 2026-11-10
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- 公开 `ShrinkModComponentDiscovery.Discover`,从显式授权 DLL 列表生成延迟组件源,保留 SHA-256 revision;发现不运行生命周期或提交当前 revision。
|
||||||
|
- 新增 `ShrinkModLoader.LoadComposed` 与 `ShrinkModCordisRuntime.ApplyComposedAsync`,复用 ContextHost 可逆生命周期、依赖排序、热替换和失败恢复。
|
||||||
|
- 新增源的 `WithMetadata` / `CreateDataOnly` 和 `IShrinkModWrapper.PublicInstance`,支持清单依赖、无入口数据包及真实实例句柄。
|
||||||
|
- 公开 `TryAttachEventBusInstance`;组合加载自动绑定公开实例,失败、替换及卸载时释放。
|
||||||
|
- 依赖支持 Maven 风格版本区间、并集及 None/Before/After 排序;保留 minimumVersion 和原三参数构造函数。
|
||||||
|
- 新增 `AssemblyResolvePolicy`,按请求程序集、请求名称和授权候选路径限制解析。
|
||||||
|
- 新增宿主组合回归测试与 `Tools~/HostTests` 独立 .NET harness。
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- 清单元数据或排序前驱变化会重新协调对应组件;宿主组合由宿主重新提交,内置 watcher 不覆盖清单。
|
||||||
|
- 恢复旧组件前先恢复程序集解析 revision,保证回滚实例使用旧解析集合。
|
||||||
|
- UPM 与共享 NuGet 升级至 0.3.8;Godot 适配 NuGet 升至 0.1.7,以发布新的共享依赖引用。
|
||||||
|
|
||||||
|
## [0.2.4] - 2026-08-28
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- 精确依赖 `ShrinkEventBus 2.0.1`。
|
||||||
|
|
||||||
|
## [0.2.3] - 2026-08-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- 新增 `ShrinkModLoader.LoadAuthorized(settings, authorizedDllPaths)`,只从调用方提交的精确 DLL 白名单加载外部模组。
|
||||||
|
- 恢复公共入口 `ShrinkModRuntimeBootstrap.InitializeDriver(...)`,供安全启动链显式初始化运行时驱动。
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- ContextHost 与旧加载路径不再递归扫描外部模组目录;revision 刷新只复用已授权路径。
|
||||||
|
- `autoLoadOnStartup`、`enableExternalDllMods`、`watchExternalModsDirectory` 默认关闭。
|
||||||
|
- `ShrinkModFrameworkSettings` 优先从标准 ShrinkSDK 资源目录加载,创建菜单同步写入该目录。
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- 授权 DLL 替换失败时继续恢复此前已提交的 SHA-256 revision 与模组组合。
|
||||||
|
|
||||||
## [0.2.1] - 2026-08-26
|
## [0.2.1] - 2026-08-26
|
||||||
|
|
||||||
- 将 EventBus 生成器源码和 fixture builder 收敛到各自 UPM 包的 `Tools~`,并为独立包导出提供随包分析器回退。
|
- 将 EventBus 生成器源码和 fixture builder 收敛到各自 UPM 包的 `Tools~`,并为独立包导出提供随包分析器回退。
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<LangVersion>latest</LangVersion>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<Deterministic>true</Deterministic>
|
||||||
|
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
|
||||||
|
<Authors>ShrinkSDK</Authors>
|
||||||
|
<Company>ShrinkSDK</Company>
|
||||||
|
<RepositoryUrl>https://git.crash.work/ShrinkSDK</RepositoryUrl>
|
||||||
|
<IncludeSymbols>true</IncludeSymbols>
|
||||||
|
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 5d818c0b172f0114a85be0e1886f5b04
|
||||||
|
DefaultImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#nullable enable
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace ShrinkModFramework;
|
||||||
|
|
||||||
|
public sealed class ShrinkModContext
|
||||||
|
{
|
||||||
|
private readonly Dictionary<Type, object> _services = new();
|
||||||
|
public ShrinkModContext(string modDirectory) => ModDirectory = modDirectory ?? throw new ArgumentNullException(nameof(modDirectory));
|
||||||
|
public string ModDirectory { get; }
|
||||||
|
public void RegisterService<T>(T service) where T : class => _services[typeof(T)] = service ?? throw new ArgumentNullException(nameof(service));
|
||||||
|
public bool TryGetService<T>(out T? service) where T : class
|
||||||
|
{
|
||||||
|
service = _services.TryGetValue(typeof(T), out var value) ? value as T : null;
|
||||||
|
return service != null;
|
||||||
|
}
|
||||||
|
public T GetRequiredService<T>() where T : class => TryGetService<T>(out var value) ? value! : throw new InvalidOperationException($"Service is not registered: {typeof(T).FullName}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public interface IShrinkModUnload
|
||||||
|
{
|
||||||
|
void OnUnload(ShrinkModContext context);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>netstandard2.1</TargetFramework>
|
||||||
|
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||||
|
<AssemblyName>ShrinkModFramework.Runtime</AssemblyName>
|
||||||
|
<RootNamespace>ShrinkModFramework</RootNamespace>
|
||||||
|
<PackageId>ShrinkSDK.ModFramework</PackageId>
|
||||||
|
<Version>0.3.8</Version>
|
||||||
|
<Description>Engine-neutral ShrinkSDK mod contracts and lifecycle.</Description>
|
||||||
|
<Nullable>disable</Nullable>
|
||||||
|
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="Runtime\ShrinkModContext.cs" />
|
||||||
|
<Compile Include="..\Runtime\Core\IShrinkMod.cs" />
|
||||||
|
<Compile Include="..\Runtime\Core\ShrinkModBase.cs" />
|
||||||
|
<Compile Include="..\Runtime\Core\ShrinkModHandle.cs" />
|
||||||
|
<Compile Include="..\Runtime\Metadata\*.cs" />
|
||||||
|
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.2.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
#if UNITY_EDITOR
|
||||||
|
using UnityEditor;
|
||||||
|
using UnityEngine;
|
||||||
|
|
||||||
|
namespace ShrinkModFramework.Editor
|
||||||
|
{
|
||||||
|
public static class ShrinkModFrameworkSettingsMenu
|
||||||
|
{
|
||||||
|
private const string SettingsDirectory =
|
||||||
|
"Assets/Resources/GameAssets/Runtime/Data/ShrinkSDK";
|
||||||
|
private const string SettingsAssetPath =
|
||||||
|
SettingsDirectory + "/ShrinkModFrameworkSettings.asset";
|
||||||
|
|
||||||
|
[MenuItem("ShrinkSDK/模组/创建设置")]
|
||||||
|
public static void CreateSettingsAsset()
|
||||||
|
{
|
||||||
|
EnsureFolder(SettingsDirectory);
|
||||||
|
|
||||||
|
var existing = AssetDatabase.LoadAssetAtPath<ShrinkModFrameworkSettings>(SettingsAssetPath);
|
||||||
|
if (existing != null)
|
||||||
|
{
|
||||||
|
Selection.activeObject = existing;
|
||||||
|
EditorGUIUtility.PingObject(existing);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var asset = ScriptableObject.CreateInstance<ShrinkModFrameworkSettings>();
|
||||||
|
AssetDatabase.CreateAsset(asset, SettingsAssetPath);
|
||||||
|
AssetDatabase.SaveAssets();
|
||||||
|
Selection.activeObject = asset;
|
||||||
|
EditorGUIUtility.PingObject(asset);
|
||||||
|
Debug.Log("[ShrinkModFramework] 已创建 ShrinkModFrameworkSettings.asset");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EnsureFolder(string path)
|
||||||
|
{
|
||||||
|
var segments = path.Split('/');
|
||||||
|
var current = segments[0];
|
||||||
|
for (var i = 1; i < segments.Length; i++)
|
||||||
|
{
|
||||||
|
var next = current + "/" + segments[i];
|
||||||
|
if (!AssetDatabase.IsValidFolder(next))
|
||||||
|
AssetDatabase.CreateFolder(current, segments[i]);
|
||||||
|
current = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 400ef5e3613144f9b9f248d259b84a22
|
||||||
|
MonoImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
serializedVersion: 2
|
||||||
|
defaultReferences: []
|
||||||
|
executionOrder: 0
|
||||||
|
icon: {instanceID: 0}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
#nullable enable
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.Loader;
|
||||||
|
|
||||||
|
namespace ShrinkModFramework.Godot;
|
||||||
|
|
||||||
|
public sealed class ShrinkGodotModLoader : IDisposable
|
||||||
|
{
|
||||||
|
private sealed record LoadedMod(AssemblyLoadContext LoadContext, WeakReference UnloadReference,
|
||||||
|
ShrinkModContext Context, IReadOnlyList<IShrinkMod> Instances);
|
||||||
|
private readonly Dictionary<string, LoadedMod> _loaded = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
public IReadOnlyCollection<string> LoadedAssemblyPaths => _loaded.Keys;
|
||||||
|
|
||||||
|
public IReadOnlyList<IShrinkMod> Load(string assemblyPath)
|
||||||
|
{
|
||||||
|
assemblyPath = Path.GetFullPath(assemblyPath);
|
||||||
|
if (_loaded.ContainsKey(assemblyPath)) throw new InvalidOperationException($"Mod assembly is already loaded: {assemblyPath}");
|
||||||
|
var loadContext = new AssemblyLoadContext($"ShrinkMod:{Path.GetFileNameWithoutExtension(assemblyPath)}", true);
|
||||||
|
loadContext.Resolving += (_, name) => ResolveDependency(loadContext, Path.GetDirectoryName(assemblyPath)!, name);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var assembly = loadContext.LoadFromAssemblyPath(assemblyPath);
|
||||||
|
var entries = assembly.GetTypes().Where(type => !type.IsAbstract && typeof(IShrinkMod).IsAssignableFrom(type) &&
|
||||||
|
type.GetCustomAttribute<ShrinkModAttribute>() != null).OrderBy(type => type.GetCustomAttribute<ShrinkModAttribute>()!.LoadOrder).ToArray();
|
||||||
|
var context = new ShrinkModContext(Path.GetDirectoryName(assemblyPath)!);
|
||||||
|
var instances = entries.Select(type => (IShrinkMod)(Activator.CreateInstance(type) ??
|
||||||
|
throw new InvalidOperationException($"Failed to create mod entry: {type.FullName}"))).ToArray();
|
||||||
|
foreach (var mod in instances) mod.OnConstruct(context);
|
||||||
|
foreach (var mod in instances) mod.OnRegisterContent(context);
|
||||||
|
foreach (var mod in instances) mod.OnInitialize(context);
|
||||||
|
foreach (var mod in instances) mod.OnReady(context);
|
||||||
|
_loaded[assemblyPath] = new LoadedMod(loadContext, new WeakReference(loadContext), context, instances);
|
||||||
|
return instances;
|
||||||
|
}
|
||||||
|
catch { loadContext.Unload(); throw; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Unload(string assemblyPath)
|
||||||
|
{
|
||||||
|
assemblyPath = Path.GetFullPath(assemblyPath);
|
||||||
|
if (!_loaded.Remove(assemblyPath, out var loaded)) return false;
|
||||||
|
for (var index = loaded.Instances.Count - 1; index >= 0; index--)
|
||||||
|
if (loaded.Instances[index] is IShrinkModUnload unload) unload.OnUnload(loaded.Context);
|
||||||
|
loaded.LoadContext.Unload();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
foreach (var path in _loaded.Keys.ToArray()) Unload(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Assembly? ResolveDependency(AssemblyLoadContext context, string directory, AssemblyName name)
|
||||||
|
{
|
||||||
|
var shared = AssemblyLoadContext.Default.Assemblies.FirstOrDefault(assembly => assembly.GetName().Name == name.Name);
|
||||||
|
if (shared != null) return shared;
|
||||||
|
var path = Path.Combine(directory, name.Name + ".dll");
|
||||||
|
return File.Exists(path) ? context.LoadFromAssemblyPath(path) : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<AssemblyName>ShrinkModFramework.Godot</AssemblyName>
|
||||||
|
<RootNamespace>ShrinkModFramework.Godot</RootNamespace>
|
||||||
|
<PackageId>ShrinkSDK.ModFramework.Godot</PackageId>
|
||||||
|
<Version>0.1.7</Version>
|
||||||
|
<Description>Collectible AssemblyLoadContext host for ShrinkSDK mods in Godot.</Description>
|
||||||
|
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\DotNet~\ShrinkSDK.ModFramework.csproj" />
|
||||||
|
<PackageReference Include="ShrinkSDK.Godot" Version="0.2.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<configuration>
|
||||||
|
<packageSources>
|
||||||
|
<clear />
|
||||||
|
<add key="ShrinkSDK" value="https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json" />
|
||||||
|
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
|
||||||
|
</packageSources>
|
||||||
|
</configuration>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: d2250189e7eded943a13c62da92db2d3
|
||||||
|
PluginImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
serializedVersion: 2
|
||||||
|
iconMap: {}
|
||||||
|
executionOrder: {}
|
||||||
|
defineConstraints: []
|
||||||
|
isPreloaded: 0
|
||||||
|
isOverridable: 0
|
||||||
|
isExplicitlyReferenced: 0
|
||||||
|
validateReferences: 1
|
||||||
|
platformData:
|
||||||
|
- first:
|
||||||
|
Any:
|
||||||
|
second:
|
||||||
|
enabled: 0
|
||||||
|
settings: {}
|
||||||
|
- first:
|
||||||
|
Editor: Editor
|
||||||
|
second:
|
||||||
|
enabled: 0
|
||||||
|
settings:
|
||||||
|
DefaultValueInitialized: true
|
||||||
|
- first:
|
||||||
|
Windows Store Apps: WindowsStoreApps
|
||||||
|
second:
|
||||||
|
enabled: 1
|
||||||
|
settings: {}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
# ShrinkModFramework
|
# ShrinkModFramework
|
||||||
|
|
||||||
一个面向 Unity 的轻量模组框架,目标是给 `Shrink` 系列提供接近 Forge 的核心能力:
|
一个面向 Unity 与 Godot C# 的轻量模组框架,目标是给 `Shrink` 系列提供接近 Forge 的核心能力:
|
||||||
|
|
||||||
|
共享模组合同和加载规则位于 `DotNet~`,Godot `AssemblyLoadContext` 适配与打包工程位于 `Godot~`。Godot 项目安装 `ShrinkSDK.ModFramework.Godot`,会同时取得共享核心包。
|
||||||
|
|
||||||
- 模组声明
|
- 模组声明
|
||||||
- 模组发现
|
- 模组发现
|
||||||
- 依赖解析
|
- 依赖解析
|
||||||
- 生命周期阶段
|
- 生命周期阶段
|
||||||
- 内容注册表
|
- 内容注册表
|
||||||
- 自动启动
|
- 可选显式启动
|
||||||
- 外部 DLL 模组热加载
|
- 外部 DLL 模组热加载
|
||||||
- Harmony 热补丁接入
|
- Harmony 热补丁接入
|
||||||
- 网络同步通道
|
- 网络同步通道
|
||||||
@@ -31,17 +33,19 @@
|
|||||||
- 内置的资源包系统、命令系统、配方编辑器
|
- 内置的资源包系统、命令系统、配方编辑器
|
||||||
- 内置的具体联网实现
|
- 内置的具体联网实现
|
||||||
|
|
||||||
## 自动启动
|
## 启动
|
||||||
|
|
||||||
现在默认**不需要**把 `ShrinkModBootstrap` 挂到场景里。
|
安全默认值不会自动启动或扫描外部 DLL。需要装载工程内模组时,可以显式调用
|
||||||
|
`ShrinkModLoader.LoadAll(settings)`;需要外部代码模组时,调用方必须先完成自己的清单、
|
||||||
框架会通过:
|
启用状态和哈希校验,再提交精确白名单:
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
|
ShrinkModRuntimeBootstrap.InitializeDriver(settings);
|
||||||
|
ShrinkModLoader.LoadAuthorized(settings, authorizedDllPaths);
|
||||||
```
|
```
|
||||||
|
|
||||||
自动读取 `ShrinkModFrameworkSettings` 并调用装载流程。
|
只有显式打开 `autoLoadOnStartup` 时,`AfterAssembliesLoaded` 入口才会装载工程内模组;
|
||||||
|
该自动入口仍不加载任何未授权外部 DLL。
|
||||||
|
|
||||||
相关入口:
|
相关入口:
|
||||||
|
|
||||||
@@ -50,14 +54,124 @@
|
|||||||
|
|
||||||
`ShrinkModBootstrap` 仍然保留,作为手动覆盖或调试入口,但不是必需品。
|
`ShrinkModBootstrap` 仍然保留,作为手动覆盖或调试入口,但不是必需品。
|
||||||
|
|
||||||
|
## 宿主清单组合(0.3.8)
|
||||||
|
|
||||||
|
Unity 宿主可以先发现授权 DLL,再用清单替换元数据和生命周期工厂,最后提交完整组合。
|
||||||
|
`Discover` 不构造模组、不运行生命周期、不改变已提交的 current revision;DLL 会进入 AppDomain,
|
||||||
|
外部源的 `Revision` 仍为 `SHA-256:入口类型全名`。工程内源仍按 `assemblyNamePrefixes` 筛选。
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var discovered = ShrinkModComponentDiscovery.Discover(settings, authorizedDllPaths);
|
||||||
|
var original = discovered.Single(source => source.Info.ModId == "demo.code");
|
||||||
|
var info = new ShrinkModInfo("demo.code", "代码包", "1.2.0", 0,
|
||||||
|
original.Info.EntryType, original.Info.AutoApplyHarmonyPatches,
|
||||||
|
new[] { new ShrinkModDependency("demo.data", "1.0", optional: false) });
|
||||||
|
var code = original.WithMetadata(info, original.Revision,
|
||||||
|
() => new PackageWrapper(original.Factory()));
|
||||||
|
var dataInfo = new ShrinkModInfo("demo.data", "数据包", "1.0", 0,
|
||||||
|
entryType: null, autoApplyHarmonyPatches: false,
|
||||||
|
dependencies: Array.Empty<ShrinkModDependency>());
|
||||||
|
var data = ShrinkModComponentSource.CreateDataOnly(dataInfo, "manifest-sha256");
|
||||||
|
ShrinkModLoader.LoadComposed(settings, new[] { code, data });
|
||||||
|
|
||||||
|
sealed class PackageWrapper : ShrinkModBase, IShrinkModWrapper
|
||||||
|
{
|
||||||
|
public PackageWrapper(IShrinkMod instance) => PublicInstance = instance;
|
||||||
|
public IShrinkMod PublicInstance { get; }
|
||||||
|
public override void OnConstruct(ShrinkModContext ctx) => PublicInstance.OnConstruct(ctx);
|
||||||
|
public override void OnRegisterContent(ShrinkModContext ctx) => PublicInstance.OnRegisterContent(ctx);
|
||||||
|
public override void OnInitialize(ShrinkModContext ctx) => PublicInstance.OnInitialize(ctx);
|
||||||
|
public override void OnReady(ShrinkModContext ctx) => PublicInstance.OnReady(ctx);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
包装器可以在各阶段加入宿主作用域、数据注册和 `EffectInverse`。`Handle.Instance` 保持原有
|
||||||
|
`IShrinkMod` 类型,返回 `IShrinkModWrapper.PublicInstance`,自动 EventBus 绑定也使用这个真实实例。
|
||||||
|
`CreateDataOnly` 的默认工厂不执行业务,公开实例为 null;传入自定义 `Func<IShrinkMod>` 可处理数据注册。
|
||||||
|
数据包的 `EntryType` 必须为 null,框架不会尝试为它应用 Harmony 补丁。
|
||||||
|
|
||||||
|
`LoadComposed` 始终使用可逆 ContextHost,与 `useContextHost` 的旧 Loader 开关无关。每个模组按
|
||||||
|
依赖/排序关系执行 Construct → RegisterContent → Initialize → Ready;成功后设置 `IsLoaded`,
|
||||||
|
对新建或重建的 handle 发送 `OnModReady`,再发送 `OnAllModsReady`。失败恢复旧组合及 DLL revision。
|
||||||
|
相同 revision、元数据和排序前驱保持幂等;工厂行为或清单数据改变时,宿主应更新 revision。
|
||||||
|
`WithMetadata` 保留发现快照,修改外部源时应使用它。不要把不同扫描中同一路径的不同 revision 混进一次提交。
|
||||||
|
|
||||||
|
热更新时重新发现、重新按清单组合,再调用 `LoadComposed`;删除源即卸载,空列表卸载全部实例。
|
||||||
|
宿主组合模式下 `LoadNewExternalMods` 保留当前组合,内置 watcher 不会丢弃清单元数据;宿主负责触发重组。
|
||||||
|
已有 `LoadAuthorized`、普通 ContextHost 和旧 Loader 的入口保持可用,不混用旧 Loader 实例与宿主组合。
|
||||||
|
高级异步宿主可调用 `ShrinkModCordisRuntime.ApplyComposedAsync(settings, sources)`,它与既有
|
||||||
|
`ApplyDiscoveredAsync` 一样仅负责根事务;需要 Loader 状态与静态通知时使用 `LoadComposed`。
|
||||||
|
|
||||||
|
### 依赖区间和排序
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
[ShrinkModDependency("demo.core", optional: false,
|
||||||
|
VersionRange = "[1.0,2.0)", Ordering = ShrinkModDependencyOrdering.After)]
|
||||||
|
[ShrinkModDependency("demo.ui", optional: true,
|
||||||
|
Ordering = ShrinkModDependencyOrdering.Before)]
|
||||||
|
public sealed class MyMod : ShrinkModBase { }
|
||||||
|
|
||||||
|
var dependency = new ShrinkModDependency("demo.core", minimumVersion: null,
|
||||||
|
optional: true, ordering: ShrinkModDependencyOrdering.After, versionRange: "[1.2,)");
|
||||||
|
bool matches = ShrinkModVersionRange.Parse("[1.0,2.0)").Contains("1.5.0");
|
||||||
|
```
|
||||||
|
|
||||||
|
区间支持开闭边界、无上/下界、精确值 `[1.2]` 和并集 `(,1.0],[1.2,)`;裸版本 `1.0`
|
||||||
|
表示 `>= 1.0`。数字版本的尾部零等价(`1.2 == 1.2.0`),带后缀版本沿用框架版本比较规则,
|
||||||
|
不承诺 Maven 的全部 qualifier 排序规则。无效区间、范围不满足、必选依赖缺失和排序环均明确报错。
|
||||||
|
|
||||||
|
`optional` 只决定目标能否缺席;目标存在时仍检查区间。`None` 不添加先后边,`Before` 让本模组
|
||||||
|
先于目标,`After` 让目标先于本模组。若只想排序且不要求安装目标,使用 `optional: true`。
|
||||||
|
原 `minimumVersion` 参数与三参数构造函数保留,未指定排序时仍为 `After`;`VersionRange` 优先于
|
||||||
|
`MinimumVersion`。旧 Loader 的增量路径无法把新模组插到已运行模组之前,会明确要求改用 ContextHost。
|
||||||
|
|
||||||
|
### 按清单约束程序集解析
|
||||||
|
|
||||||
|
在发现之前设置策略;宿主把程序集简单名称、授权绝对路径映射回自己的 packageId:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
ShrinkModLoader.AssemblyResolvePolicy = (requestingAssembly, requestedName, candidatePath) =>
|
||||||
|
{
|
||||||
|
if (requestingAssembly == null) return false;
|
||||||
|
if (!assemblyOwners.TryGetValue(requestingAssembly.GetName().Name, out var requesterId)) return false;
|
||||||
|
if (!pathOwners.TryGetValue(candidatePath, out var candidateId)) return false;
|
||||||
|
return requesterId == candidateId || declaredDependencies[requesterId].Contains(candidateId);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
`assemblyOwners`、`pathOwners` 和 `declaredDependencies` 由宿主清单建立。回调在返回缓存候选或加载
|
||||||
|
候选字节前执行,返回 false 拒绝本次解析;候选始终来自授权白名单,策略不能扩大白名单。
|
||||||
|
未设置策略时保持原行为。入口 DLL 文件名应与程序集简单名称一致。策略仅约束框架的
|
||||||
|
`AssemblyResolve` 回调,不能拦截 CLR 已解析的程序集引用,也不是不可信代码沙箱。
|
||||||
|
|
||||||
|
### 显式绑定生成订阅
|
||||||
|
|
||||||
|
宿主组合在 RegisterContent 后自动为公开实例调用以下入口,并将 Dispose 登记为可逆效应;
|
||||||
|
Initialize/Ready 失败、替换或卸载都会退订。自动路径不需要包装器再手动绑定同一个实例。
|
||||||
|
如果需要手动绑定其它订阅对象:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var binding = ShrinkModOptionalRuntimeIntegration.TryAttachEventBusInstance(
|
||||||
|
subscriber.GetType(), subscriber, context.ModInfo.ModId, verboseLogging: false);
|
||||||
|
if (binding != null) context.EffectInverse(binding.Dispose);
|
||||||
|
```
|
||||||
|
|
||||||
|
返回值为 `IDisposable`;没有生成合同或可选绑定失败时返回 null。它使用 `ShrinkBusKey.Mod(modId)`,
|
||||||
|
不会反射枚举订阅方法。手动调用方负责释放;ContextHost 自动路径还会在退役时移除对应 Mod Bus。
|
||||||
|
|
||||||
|
共享 NuGet `ShrinkSDK.ModFramework` 0.3.8 包含依赖元数据和范围解析;上述 Unity 发现/ContextHost API
|
||||||
|
属于 UPM Runtime。Godot 适配包独立版本为 0.1.7,本次仅更新它对共享包的发布引用。
|
||||||
|
|
||||||
## 配置文件
|
## 配置文件
|
||||||
|
|
||||||
创建 `ShrinkModFrameworkSettings` 资产后,框架会自动查找它。
|
菜单 `ShrinkSDK/模组/创建设置` 会在
|
||||||
|
`Assets/Resources/GameAssets/Runtime/Data/ShrinkSDK/ShrinkModFrameworkSettings.asset`
|
||||||
|
创建配置。运行时优先加载该路径,并保留旧根路径回退。
|
||||||
|
|
||||||
关键配置包括:
|
关键配置包括:
|
||||||
|
|
||||||
- `autoLoadOnStartup`
|
- `autoLoadOnStartup`
|
||||||
- 是否在启动时自动装载模组
|
- 是否在启动时自动装载工程内模组,默认关闭
|
||||||
- `useContextHost`
|
- `useContextHost`
|
||||||
- 默认开启:把模组四阶段放进 `ShrinkModContextHost`,替换失败恢复旧组件源;关闭后回退旧 Loader
|
- 默认开启:把模组四阶段放进 `ShrinkModContextHost`,替换失败恢复旧组件源;关闭后回退旧 Loader
|
||||||
- `verboseLogging`
|
- `verboseLogging`
|
||||||
@@ -65,11 +179,11 @@
|
|||||||
- `assemblyNamePrefixes`
|
- `assemblyNamePrefixes`
|
||||||
- 只扫描指定前缀的程序集
|
- 只扫描指定前缀的程序集
|
||||||
- `enableExternalDllMods`
|
- `enableExternalDllMods`
|
||||||
- 是否启用外部 DLL 模组
|
- 是否允许显式白名单中的外部 DLL 模组,默认关闭
|
||||||
- `externalModsFolderName`
|
- `externalModsFolderName`
|
||||||
- 外部模组目录名,默认 `Mods`
|
- 外部模组目录名,默认 `Mods`
|
||||||
- `watchExternalModsDirectory`
|
- `watchExternalModsDirectory`
|
||||||
- 是否自动监听目录变化并协调外部 DLL revision 变化
|
- 是否监听文件变化并重新提交既有白名单,默认关闭;监听不会扩大授权范围
|
||||||
- `externalModsReloadDelaySeconds`
|
- `externalModsReloadDelaySeconds`
|
||||||
- 文件变更后延迟多少秒再尝试热加载
|
- 文件变更后延迟多少秒再尝试热加载
|
||||||
- `externalAssemblyRevisionSoftLimit`
|
- `externalAssemblyRevisionSoftLimit`
|
||||||
@@ -182,13 +296,8 @@ public class DemoSafeMod : ShrinkModBase
|
|||||||
|
|
||||||
## 外部 DLL 模组热加载
|
## 外部 DLL 模组热加载
|
||||||
|
|
||||||
框架会扫描:
|
框架不会递归扫描模组目录。调用方必须把每个允许进入 AppDomain 的入口 DLL 绝对路径
|
||||||
|
作为白名单提交给 `LoadAuthorized`;目录中未列出的 DLL 不会被读取或加载。
|
||||||
`Application.persistentDataPath/<externalModsFolderName>`
|
|
||||||
|
|
||||||
默认就是:
|
|
||||||
|
|
||||||
`Application.persistentDataPath/Mods`
|
|
||||||
|
|
||||||
ContextLoader 装载规则:
|
ContextLoader 装载规则:
|
||||||
|
|
||||||
@@ -199,16 +308,19 @@ ContextLoader 装载规则:
|
|||||||
- 不支持 IL2CPP Player 动态程序集加载
|
- 不支持 IL2CPP Player 动态程序集加载
|
||||||
- 支持同目录依赖程序集解析
|
- 支持同目录依赖程序集解析
|
||||||
|
|
||||||
你可以在运行时调用:
|
首次安全加载:
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
ShrinkModLoader.LoadNewExternalMods();
|
ShrinkModRuntimeBootstrap.InitializeDriver(settings);
|
||||||
|
ShrinkModLoader.LoadAuthorized(settings, authorizedDllPaths);
|
||||||
```
|
```
|
||||||
|
|
||||||
默认会扫描当前 DLL revision,并把新增、替换、删除映射为一个完整期望组合;
|
后续可调用 `ShrinkModLoader.LoadNewExternalMods(settings)` 重新读取同一白名单的 revision,
|
||||||
变更事务失败时保留旧模组组合。设置 `useContextHost = false` 才回退为仅新增 DLL 的旧路径。
|
把新增、替换、删除映射为完整期望组合;变更事务失败时保留旧模组组合。设置
|
||||||
|
`useContextHost = false` 时,旧路径同样只读取显式白名单,但仍保持只增不减的兼容语义。
|
||||||
|
|
||||||
如果 `watchExternalModsDirectory = true`,框架还会监听新增、修改、删除、重命名事件,经过主线程 debouncer 后提交一次完整组合;同一 burst 内的中间坏文件不会覆盖当前有效 revision。
|
如果 `watchExternalModsDirectory = true`,框架会监听目录变化并在主线程 debouncer 后重新提交
|
||||||
|
既有白名单;未授权文件即使触发通知也不会被加载。同一 burst 内的中间坏文件不会覆盖当前有效 revision。
|
||||||
|
|
||||||
### 常驻 revision 诊断
|
### 常驻 revision 诊断
|
||||||
|
|
||||||
@@ -674,9 +786,9 @@ public sealed partial class DemoFullMod : ShrinkModBase
|
|||||||
|
|
||||||
## 设计约束
|
## 设计约束
|
||||||
|
|
||||||
- 一个模组类必须有 `[ShrinkMod]`
|
- 自动发现的模组类必须有 `[ShrinkMod]`;宿主组合使用显式元数据和工厂
|
||||||
- 一个模组类必须实现 `IShrinkMod`
|
- 一个模组类必须实现 `IShrinkMod`
|
||||||
- 一个模组类必须能被无参构造
|
- 自动发现的模组类必须能被无参构造;宿主工厂可自行构造包装器
|
||||||
- 模组 ID 必须全局唯一
|
- 模组 ID 必须全局唯一
|
||||||
- 必选依赖缺失或版本不满足时,装载直接失败
|
- 必选依赖缺失或版本不满足时,装载直接失败
|
||||||
- 检测到循环依赖时,装载直接失败
|
- 检测到循环依赖时,装载直接失败
|
||||||
@@ -697,8 +809,8 @@ public sealed partial class DemoFullMod : ShrinkModBase
|
|||||||
|
|
||||||
现在这套框架已经从“只能在工程内静态发现模组”的骨架,升级成了:
|
现在这套框架已经从“只能在工程内静态发现模组”的骨架,升级成了:
|
||||||
|
|
||||||
- 自动启动
|
- 可显式托管启动
|
||||||
- 可增量接入外部 DLL
|
- 可按精确白名单增量接入外部 DLL
|
||||||
- 可选 Harmony 补丁
|
- 可选 Harmony 补丁
|
||||||
- 可扩展的网络同步框架
|
- 可扩展的网络同步框架
|
||||||
|
|
||||||
@@ -708,3 +820,13 @@ public sealed partial class DemoFullMod : ShrinkModBase
|
|||||||
- 模组资源系统
|
- 模组资源系统
|
||||||
- 模组命令系统
|
- 模组命令系统
|
||||||
- 模组专属存档与同步策略
|
- 模组专属存档与同步策略
|
||||||
|
|
||||||
|
## 可复用能力
|
||||||
|
|
||||||
|
<!-- shrink:capabilities -->
|
||||||
|
Capability: 模组发现、依赖、阶段生命周期、内容注册和外部程序集加载
|
||||||
|
Aliases: mod 插件 模组 模组退役 热加载 内容注册
|
||||||
|
Limits: 动态程序集不能假定全部卸载;宿主加载上下文须单独验证;不默认 NativeAOT
|
||||||
|
Extension: 模组声明、阶段钩子与宿主加载接口
|
||||||
|
Evidence: [ShrinkModContextHost](Runtime/Context/ShrinkModContextHost.cs)
|
||||||
|
<!-- /shrink:capabilities -->
|
||||||
@@ -9,7 +9,7 @@ namespace ShrinkModFramework
|
|||||||
[SerializeField] private ShrinkModFrameworkSettings settingsOverride;
|
[SerializeField] private ShrinkModFrameworkSettings settingsOverride;
|
||||||
|
|
||||||
[Header("Bootstrap")]
|
[Header("Bootstrap")]
|
||||||
[SerializeField] private bool autoLoadOnAwake = true;
|
[SerializeField] private bool autoLoadOnAwake;
|
||||||
|
|
||||||
private static bool _bootstrapped;
|
private static bool _bootstrapped;
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ namespace ShrinkModFramework
|
|||||||
[CreateAssetMenu(fileName = "ShrinkModFrameworkSettings", menuName = "ShrinkSDK/模组/模组设置")]
|
[CreateAssetMenu(fileName = "ShrinkModFrameworkSettings", menuName = "ShrinkSDK/模组/模组设置")]
|
||||||
public class ShrinkModFrameworkSettings : ScriptableObject
|
public class ShrinkModFrameworkSettings : ScriptableObject
|
||||||
{
|
{
|
||||||
|
public const string PreferredResourcesPath =
|
||||||
|
"GameAssets/Runtime/Data/ShrinkSDK/ShrinkModFrameworkSettings";
|
||||||
|
public const string LegacyResourcesPath = "ShrinkModFrameworkSettings";
|
||||||
|
|
||||||
private static ShrinkModFrameworkSettings _instance;
|
private static ShrinkModFrameworkSettings _instance;
|
||||||
|
|
||||||
public static ShrinkModFrameworkSettings Instance
|
public static ShrinkModFrameworkSettings Instance
|
||||||
@@ -13,7 +17,9 @@ namespace ShrinkModFramework
|
|||||||
{
|
{
|
||||||
if (_instance) return _instance;
|
if (_instance) return _instance;
|
||||||
|
|
||||||
_instance = Resources.Load<ShrinkModFrameworkSettings>("ShrinkModFrameworkSettings");
|
_instance = Resources.Load<ShrinkModFrameworkSettings>(PreferredResourcesPath);
|
||||||
|
if (!_instance)
|
||||||
|
_instance = Resources.Load<ShrinkModFrameworkSettings>(LegacyResourcesPath);
|
||||||
|
|
||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
if (!_instance)
|
if (!_instance)
|
||||||
@@ -39,8 +45,13 @@ namespace ShrinkModFramework
|
|||||||
internal set => _instance = value;
|
internal set => _instance = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static void ResetCachedInstance()
|
||||||
|
{
|
||||||
|
_instance = null;
|
||||||
|
}
|
||||||
|
|
||||||
[Header("Bootstrap")]
|
[Header("Bootstrap")]
|
||||||
public bool autoLoadOnStartup = true;
|
public bool autoLoadOnStartup;
|
||||||
[Tooltip("使用 ShrinkContextHost 协调模组组件;关闭时回退到旧的只增不减 ShrinkModLoader。")]
|
[Tooltip("使用 ShrinkContextHost 协调模组组件;关闭时回退到旧的只增不减 ShrinkModLoader。")]
|
||||||
public bool useContextHost = true;
|
public bool useContextHost = true;
|
||||||
|
|
||||||
@@ -51,10 +62,10 @@ namespace ShrinkModFramework
|
|||||||
public string[] assemblyNamePrefixes = new string[0];
|
public string[] assemblyNamePrefixes = new string[0];
|
||||||
|
|
||||||
[Header("External Mods")]
|
[Header("External Mods")]
|
||||||
public bool enableExternalDllMods = true;
|
public bool enableExternalDllMods;
|
||||||
public bool autoCreateExternalModsDirectory = true;
|
public bool autoCreateExternalModsDirectory = true;
|
||||||
public string externalModsFolderName = "Mods";
|
public string externalModsFolderName = "Mods";
|
||||||
public bool watchExternalModsDirectory = true;
|
public bool watchExternalModsDirectory;
|
||||||
public float externalModsReloadDelaySeconds = 0.5f;
|
public float externalModsReloadDelaySeconds = 0.5f;
|
||||||
[Min(1)]
|
[Min(1)]
|
||||||
[Tooltip("Mono 下外部程序集 revision 会常驻;历史数量达到该软阈值后提示 Domain Reload/重启。")]
|
[Tooltip("Mono 下外部程序集 revision 会常驻;历史数量达到该软阈值后提示 Domain Reload/重启。")]
|
||||||
|
|||||||
@@ -4,6 +4,15 @@ namespace ShrinkModFramework
|
|||||||
{
|
{
|
||||||
public static class ShrinkModRuntimeBootstrap
|
public static class ShrinkModRuntimeBootstrap
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 显式创建或更新模组运行时驱动。安全启动链可先调用此入口,再调用
|
||||||
|
/// ShrinkModLoader.LoadAuthorized 提交已校验的 DLL 白名单。
|
||||||
|
/// </summary>
|
||||||
|
public static void InitializeDriver(ShrinkModFrameworkSettings settings = null)
|
||||||
|
{
|
||||||
|
ShrinkModRuntimeDriver.EnsureCreated(settings ?? ShrinkModFrameworkSettings.Instance);
|
||||||
|
}
|
||||||
|
|
||||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
||||||
private static void ResetStaticStateForPlayMode()
|
private static void ResetStaticStateForPlayMode()
|
||||||
{
|
{
|
||||||
@@ -15,11 +24,11 @@ namespace ShrinkModFramework
|
|||||||
private static void AutoLoad()
|
private static void AutoLoad()
|
||||||
{
|
{
|
||||||
var settings = ShrinkModFrameworkSettings.Instance;
|
var settings = ShrinkModFrameworkSettings.Instance;
|
||||||
ShrinkModRuntimeDriver.EnsureCreated(settings);
|
|
||||||
|
|
||||||
if (settings && !settings.autoLoadOnStartup)
|
if (settings && !settings.autoLoadOnStartup)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
InitializeDriver(settings);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
ShrinkModLoader.LoadAll(settings);
|
ShrinkModLoader.LoadAll(settings);
|
||||||
|
|||||||
@@ -19,9 +19,8 @@ namespace ShrinkModFramework
|
|||||||
{
|
{
|
||||||
_host = host ?? throw new ArgumentNullException(nameof(host));
|
_host = host ?? throw new ArgumentNullException(nameof(host));
|
||||||
_source = source ?? throw new ArgumentNullException(nameof(source));
|
_source = source ?? throw new ArgumentNullException(nameof(source));
|
||||||
_inject = source.Info.Dependencies
|
_inject = host.GetPredecessors(source.Info.ModId)
|
||||||
.Where(dependency => !dependency.Optional)
|
.Select(ShrinkModContextHost.GetModKey)
|
||||||
.Select(dependency => ShrinkModContextHost.GetModKey(dependency.ModId))
|
|
||||||
.Distinct(StringComparer.Ordinal)
|
.Distinct(StringComparer.Ordinal)
|
||||||
.ToArray();
|
.ToArray();
|
||||||
_provide = new[] { ShrinkModContextHost.GetModKey(source.Info.ModId) };
|
_provide = new[] { ShrinkModContextHost.GetModKey(source.Info.ModId) };
|
||||||
@@ -37,7 +36,8 @@ namespace ShrinkModFramework
|
|||||||
if (instance == null)
|
if (instance == null)
|
||||||
throw new InvalidOperationException($"Mod factory returned null: {_source.Info.ModId}");
|
throw new InvalidOperationException($"Mod factory returned null: {_source.Info.ModId}");
|
||||||
|
|
||||||
var handle = new ShrinkModHandle(_source.Info, instance)
|
var publicInstance = instance is IShrinkModWrapper wrapper ? wrapper.PublicInstance : instance;
|
||||||
|
var handle = new ShrinkModHandle(_source.Info, publicInstance)
|
||||||
{
|
{
|
||||||
Generation = _host.NextGeneration()
|
Generation = _host.NextGeneration()
|
||||||
};
|
};
|
||||||
@@ -70,7 +70,7 @@ namespace ShrinkModFramework
|
|||||||
IDisposable eventBinding = null;
|
IDisposable eventBinding = null;
|
||||||
ctx.Effect(
|
ctx.Effect(
|
||||||
() => eventBinding = ShrinkModOptionalRuntimeIntegration.TryAttachEventBusInstance(
|
() => eventBinding = ShrinkModOptionalRuntimeIntegration.TryAttachEventBusInstance(
|
||||||
instance.GetType(), instance, handle.Info.ModId, _host.VerboseLogging),
|
publicInstance?.GetType(), publicInstance, handle.Info.ModId, _host.VerboseLogging),
|
||||||
() =>
|
() =>
|
||||||
{
|
{
|
||||||
eventBinding?.Dispose();
|
eventBinding?.Dispose();
|
||||||
|
|||||||
@@ -10,12 +10,35 @@ namespace ShrinkModFramework
|
|||||||
/// 把工程内程序集和外部 DLL 的当前 revision 投影为延迟组件源。
|
/// 把工程内程序集和外部 DLL 的当前 revision 投影为延迟组件源。
|
||||||
/// 同一路径的旧外部程序集无法从 Mono AppDomain 卸载,但不会再进入候选集合。
|
/// 同一路径的旧外部程序集无法从 Mono AppDomain 卸载,但不会再进入候选集合。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal static class ShrinkModComponentDiscovery
|
public static class ShrinkModComponentDiscovery
|
||||||
{
|
{
|
||||||
public static IReadOnlyList<ShrinkModComponentSource> Discover(ShrinkModFrameworkSettings settings,
|
public static IReadOnlyList<ShrinkModComponentSource> Discover(
|
||||||
bool verboseLogging)
|
ShrinkModFrameworkSettings settings, IEnumerable<string> authorizedDllPaths) =>
|
||||||
|
Discover(settings, settings != null && settings.verboseLogging, authorizedDllPaths);
|
||||||
|
|
||||||
|
/// <summary>只发现,不构造实例或提交 current revision。WithMetadata 可保留发现快照。</summary>
|
||||||
|
public static IReadOnlyList<ShrinkModComponentSource> Discover(
|
||||||
|
ShrinkModFrameworkSettings settings, bool verboseLogging, IEnumerable<string> authorizedDllPaths)
|
||||||
{
|
{
|
||||||
ShrinkExternalModAssemblyLoader.ScanExternalAssemblyRevisions(settings, verboseLogging);
|
if (authorizedDllPaths == null) throw new ArgumentNullException(nameof(authorizedDllPaths));
|
||||||
|
var previous = ShrinkExternalModAssemblyLoader.CaptureState();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var sources = DiscoverCurrent(settings, verboseLogging, authorizedDllPaths);
|
||||||
|
var state = ShrinkExternalModAssemblyLoader.CaptureState();
|
||||||
|
foreach (var source in sources) source.DiscoveryState = state;
|
||||||
|
return sources;
|
||||||
|
}
|
||||||
|
finally { ShrinkExternalModAssemblyLoader.RestoreState(previous); }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static IReadOnlyList<ShrinkModComponentSource> DiscoverCurrent(
|
||||||
|
ShrinkModFrameworkSettings settings,
|
||||||
|
bool verboseLogging,
|
||||||
|
IEnumerable<string> authorizedDllPaths)
|
||||||
|
{
|
||||||
|
ShrinkExternalModAssemblyLoader.ScanExternalAssemblyRevisions(
|
||||||
|
settings, verboseLogging, authorizedDllPaths);
|
||||||
var results = new List<ShrinkModComponentSource>();
|
var results = new List<ShrinkModComponentSource>();
|
||||||
var prefixes = settings?.assemblyNamePrefixes;
|
var prefixes = settings?.assemblyNamePrefixes;
|
||||||
|
|
||||||
@@ -50,7 +73,7 @@ namespace ShrinkModFramework
|
|||||||
var dependencies = type
|
var dependencies = type
|
||||||
.GetCustomAttributes<ShrinkModDependencyAttribute>(false)
|
.GetCustomAttributes<ShrinkModDependencyAttribute>(false)
|
||||||
.Select(attribute => new ShrinkModDependency(
|
.Select(attribute => new ShrinkModDependency(
|
||||||
attribute.ModId, attribute.MinimumVersion, attribute.Optional))
|
attribute.ModId, attribute.MinimumVersion, attribute.Optional, attribute.Ordering, attribute.VersionRange))
|
||||||
.ToArray();
|
.ToArray();
|
||||||
var info = new ShrinkModInfo(
|
var info = new ShrinkModInfo(
|
||||||
modAttribute.ModId,
|
modAttribute.ModId,
|
||||||
|
|||||||
@@ -2,9 +2,15 @@ using System;
|
|||||||
|
|
||||||
namespace ShrinkModFramework
|
namespace ShrinkModFramework
|
||||||
{
|
{
|
||||||
|
/// <summary>宿主包装器执行生命周期;Handle 和自动订阅使用 PublicInstance。数据包可返回 null。</summary>
|
||||||
|
public interface IShrinkModWrapper : IShrinkMod
|
||||||
|
{
|
||||||
|
IShrinkMod PublicInstance { get; }
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 延迟模组组件源。Revision 是来源内容的稳定指纹(外部 DLL 可使用文件哈希);
|
/// 延迟模组组件源。Revision 是来源内容的稳定指纹(外部 DLL 可使用文件哈希);
|
||||||
/// 同一 ModId 的 revision/factory 变化由 ShrinkModContextHost 作为替换事务处理。
|
/// 同一 ModId 的 revision/metadata 变化由 ShrinkModContextHost 作为替换事务处理。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class ShrinkModComponentSource
|
public sealed class ShrinkModComponentSource
|
||||||
{
|
{
|
||||||
@@ -23,5 +29,27 @@ namespace ShrinkModFramework
|
|||||||
public ShrinkModInfo Info { get; }
|
public ShrinkModInfo Info { get; }
|
||||||
public string Revision { get; }
|
public string Revision { get; }
|
||||||
public Func<IShrinkMod> Factory { get; }
|
public Func<IShrinkMod> Factory { get; }
|
||||||
|
|
||||||
|
internal ShrinkExternalModAssemblyLoader.RevisionState DiscoveryState { get; set; }
|
||||||
|
|
||||||
|
/// <summary>替换清单元数据或生命周期工厂,同时保留授权发现的程序集 revision。</summary>
|
||||||
|
public ShrinkModComponentSource WithMetadata(ShrinkModInfo info, string revision,
|
||||||
|
Func<IShrinkMod> factory = null) =>
|
||||||
|
new ShrinkModComponentSource(info, revision, factory ?? Factory) { DiscoveryState = DiscoveryState };
|
||||||
|
|
||||||
|
/// <summary>创建无入口类型的数据包;可选生命周期工厂用于注册内容和可逆效应。</summary>
|
||||||
|
public static ShrinkModComponentSource CreateDataOnly(ShrinkModInfo info, string revision,
|
||||||
|
Func<IShrinkMod> factory = null)
|
||||||
|
{
|
||||||
|
if (info == null) throw new ArgumentNullException(nameof(info));
|
||||||
|
if (info.EntryType != null)
|
||||||
|
throw new ArgumentException("A data-only mod must have no entry type.", nameof(info));
|
||||||
|
return new ShrinkModComponentSource(info, revision, factory ?? (() => new EmptyDataMod()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class EmptyDataMod : ShrinkModBase, IShrinkModWrapper
|
||||||
|
{
|
||||||
|
public IShrinkMod PublicInstance => null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -33,6 +33,10 @@ namespace ShrinkModFramework
|
|||||||
private long _generation;
|
private long _generation;
|
||||||
private int _catalogGeneration;
|
private int _catalogGeneration;
|
||||||
private bool _applying;
|
private bool _applying;
|
||||||
|
private IReadOnlyList<ShrinkModComponentSource> _buildingSources = Array.Empty<ShrinkModComponentSource>();
|
||||||
|
|
||||||
|
internal IEnumerable<string> GetPredecessors(string modId) =>
|
||||||
|
ShrinkModDependencyGraph.Predecessors(modId, _buildingSources.Select(source => source.Info));
|
||||||
|
|
||||||
public ShrinkModContextHost(bool enableHarmonyPatching = true, bool verboseLogging = false)
|
public ShrinkModContextHost(bool enableHarmonyPatching = true, bool verboseLogging = false)
|
||||||
{
|
{
|
||||||
@@ -64,7 +68,9 @@ namespace ShrinkModFramework
|
|||||||
return "shrink.mod/" + modId.Trim();
|
return "shrink.mod/" + modId.Trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async UniTask ApplyAsync(IReadOnlyList<ShrinkModComponentSource> desiredSources)
|
public UniTask ApplyAsync(IReadOnlyList<ShrinkModComponentSource> desiredSources) => ApplyAsync(desiredSources, null);
|
||||||
|
|
||||||
|
internal async UniTask ApplyAsync(IReadOnlyList<ShrinkModComponentSource> desiredSources, Action beforeRestore)
|
||||||
{
|
{
|
||||||
if (desiredSources == null)
|
if (desiredSources == null)
|
||||||
throw new ArgumentNullException(nameof(desiredSources));
|
throw new ArgumentNullException(nameof(desiredSources));
|
||||||
@@ -95,8 +101,11 @@ namespace ShrinkModFramework
|
|||||||
catch (Exception applyError)
|
catch (Exception applyError)
|
||||||
{
|
{
|
||||||
Exception restoreError = null;
|
Exception restoreError = null;
|
||||||
|
_currentSources.Clear();
|
||||||
|
_currentSources.AddRange(previous);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
beforeRestore?.Invoke();
|
||||||
await Loader.ApplyAsync(BuildEntries(previous));
|
await Loader.ApplyAsync(BuildEntries(previous));
|
||||||
EnsureActive(previous);
|
EnsureActive(previous);
|
||||||
}
|
}
|
||||||
@@ -143,6 +152,7 @@ namespace ShrinkModFramework
|
|||||||
|
|
||||||
private IReadOnlyList<ShrinkLoaderEntry> BuildEntries(IEnumerable<ShrinkModComponentSource> sources)
|
private IReadOnlyList<ShrinkLoaderEntry> BuildEntries(IEnumerable<ShrinkModComponentSource> sources)
|
||||||
{
|
{
|
||||||
|
_buildingSources = sources.ToArray();
|
||||||
var entries = new List<ShrinkLoaderEntry>();
|
var entries = new List<ShrinkLoaderEntry>();
|
||||||
foreach (var source in sources)
|
foreach (var source in sources)
|
||||||
{
|
{
|
||||||
@@ -184,79 +194,34 @@ namespace ShrinkModFramework
|
|||||||
throw new InvalidOperationException($"Duplicate mod source id: {source.Info.ModId}");
|
throw new InvalidOperationException($"Duplicate mod source id: {source.Info.ModId}");
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var source in sources)
|
return ShrinkModDependencyGraph.Order(sources.Select(source => source.Info))
|
||||||
{
|
.Select(info => map[info.ModId]).ToList();
|
||||||
foreach (var dependency in source.Info.Dependencies)
|
|
||||||
{
|
|
||||||
if (!map.TryGetValue(dependency.ModId, out var target))
|
|
||||||
{
|
|
||||||
if (!dependency.Optional)
|
|
||||||
throw new InvalidOperationException(
|
|
||||||
$"Mod {source.Info.ModId} is missing required dependency {dependency.ModId}.");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!string.IsNullOrEmpty(dependency.MinimumVersion) &&
|
|
||||||
ShrinkVersionUtility.Compare(target.Info.Version, dependency.MinimumVersion) < 0)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException(
|
|
||||||
$"Mod {source.Info.ModId} requires {dependency.ModId} >= {dependency.MinimumVersion}, " +
|
|
||||||
$"but found {target.Info.Version}.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var result = new List<ShrinkModComponentSource>();
|
|
||||||
var visiting = new HashSet<string>(StringComparer.Ordinal);
|
|
||||||
var visited = new HashSet<string>(StringComparer.Ordinal);
|
|
||||||
foreach (var source in sources.OrderBy(item => item.Info.LoadOrder)
|
|
||||||
.ThenBy(item => item.Info.ModId, StringComparer.Ordinal))
|
|
||||||
{
|
|
||||||
Visit(source, map, visiting, visited, result);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<ShrinkModComponentSource> ReuseUnchangedSources(
|
private List<ShrinkModComponentSource> ReuseUnchangedSources(
|
||||||
IEnumerable<ShrinkModComponentSource> desired)
|
IEnumerable<ShrinkModComponentSource> desired)
|
||||||
{
|
{
|
||||||
|
var desiredArray = desired.ToArray();
|
||||||
var currentById = _currentSources.ToDictionary(source => source.Info.ModId, StringComparer.Ordinal);
|
var currentById = _currentSources.ToDictionary(source => source.Info.ModId, StringComparer.Ordinal);
|
||||||
var normalized = new List<ShrinkModComponentSource>();
|
var normalized = new List<ShrinkModComponentSource>();
|
||||||
foreach (var source in desired)
|
foreach (var source in desiredArray)
|
||||||
{
|
{
|
||||||
if (currentById.TryGetValue(source.Info.ModId, out var current) &&
|
if (currentById.TryGetValue(source.Info.ModId, out var current) &&
|
||||||
string.Equals(current.Revision, source.Revision, StringComparison.Ordinal))
|
string.Equals(current.Revision, source.Revision, StringComparison.Ordinal) &&
|
||||||
|
ShrinkModDependencyGraph.SameMetadata(current.Info, source.Info) &&
|
||||||
|
ShrinkModDependencyGraph.Predecessors(source.Info.ModId, _currentSources.Select(item => item.Info)).OrderBy(id => id)
|
||||||
|
.SequenceEqual(ShrinkModDependencyGraph.Predecessors(source.Info.ModId, desiredArray.Select(item => item.Info)).OrderBy(id => id)))
|
||||||
{
|
{
|
||||||
normalized.Add(current);
|
normalized.Add(current);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
normalized.Add(source);
|
normalized.Add(ReferenceEquals(source, current)
|
||||||
|
? source.WithMetadata(source.Info, source.Revision) : source);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return normalized;
|
return normalized;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void Visit(ShrinkModComponentSource source,
|
|
||||||
IReadOnlyDictionary<string, ShrinkModComponentSource> map,
|
|
||||||
ISet<string> visiting,
|
|
||||||
ISet<string> visited,
|
|
||||||
ICollection<ShrinkModComponentSource> result)
|
|
||||||
{
|
|
||||||
if (visited.Contains(source.Info.ModId))
|
|
||||||
return;
|
|
||||||
if (!visiting.Add(source.Info.ModId))
|
|
||||||
throw new InvalidOperationException($"Circular mod dependency includes {source.Info.ModId}.");
|
|
||||||
|
|
||||||
foreach (var dependency in source.Info.Dependencies.OrderBy(item => item.ModId, StringComparer.Ordinal))
|
|
||||||
{
|
|
||||||
if (map.TryGetValue(dependency.ModId, out var target))
|
|
||||||
Visit(target, map, visiting, visited, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
visiting.Remove(source.Info.ModId);
|
|
||||||
visited.Add(source.Info.ModId);
|
|
||||||
result.Add(source);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
using Cysharp.Threading.Tasks;
|
using Cysharp.Threading.Tasks;
|
||||||
|
|
||||||
namespace ShrinkModFramework
|
namespace ShrinkModFramework
|
||||||
@@ -19,7 +20,8 @@ namespace ShrinkModFramework
|
|||||||
new Dictionary<string, ShrinkModHandle>();
|
new Dictionary<string, ShrinkModHandle>();
|
||||||
|
|
||||||
public static async UniTask<IReadOnlyDictionary<string, ShrinkModHandle>> ApplyDiscoveredAsync(
|
public static async UniTask<IReadOnlyDictionary<string, ShrinkModHandle>> ApplyDiscoveredAsync(
|
||||||
ShrinkModFrameworkSettings settings = null)
|
ShrinkModFrameworkSettings settings = null,
|
||||||
|
IEnumerable<string> authorizedDllPaths = null)
|
||||||
{
|
{
|
||||||
settings ??= ShrinkModFrameworkSettings.Instance;
|
settings ??= ShrinkModFrameworkSettings.Instance;
|
||||||
var verboseLogging = settings == null || settings.verboseLogging;
|
var verboseLogging = settings == null || settings.verboseLogging;
|
||||||
@@ -34,8 +36,10 @@ namespace ShrinkModFramework
|
|||||||
ShrinkModNetworkManager.Configure(settings == null || settings.enableNetworkSync, verboseLogging);
|
ShrinkModNetworkManager.Configure(settings == null || settings.enableNetworkSync, verboseLogging);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var sources = ShrinkModComponentDiscovery.Discover(settings, verboseLogging);
|
var authorizedPaths = authorizedDllPaths?.ToArray() ?? Array.Empty<string>();
|
||||||
await _host.ApplyAsync(sources);
|
var sources = ShrinkModComponentDiscovery.DiscoverCurrent(
|
||||||
|
settings, verboseLogging, authorizedPaths);
|
||||||
|
await _host.ApplyAsync(sources, () => ShrinkExternalModAssemblyLoader.RestoreState(revisionState));
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
@@ -50,6 +54,42 @@ namespace ShrinkModFramework
|
|||||||
return _host.Mods;
|
return _host.Mods;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>提交宿主组合;生命周期或发现失败时恢复之前的程序集 revision 和组件。</summary>
|
||||||
|
public static async UniTask<IReadOnlyDictionary<string, ShrinkModHandle>> ApplyComposedAsync(
|
||||||
|
ShrinkModFrameworkSettings settings, IReadOnlyList<ShrinkModComponentSource> sources)
|
||||||
|
{
|
||||||
|
if (sources == null) throw new ArgumentNullException(nameof(sources));
|
||||||
|
settings ??= ShrinkModFrameworkSettings.Instance;
|
||||||
|
var verbose = settings != null && settings.verboseLogging;
|
||||||
|
if (_host == null) _host = new ShrinkModContextHost(settings == null || settings.enableHarmonyPatching, verbose);
|
||||||
|
var previous = ShrinkExternalModAssemblyLoader.CaptureState();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var states = sources.Where(source => source != null && source.DiscoveryState != null)
|
||||||
|
.Select(source => source.DiscoveryState).Distinct().ToArray();
|
||||||
|
var composedState = new ShrinkExternalModAssemblyLoader.RevisionState();
|
||||||
|
foreach (var state in states)
|
||||||
|
{
|
||||||
|
foreach (var pair in state.Current)
|
||||||
|
{
|
||||||
|
if (composedState.Current.TryGetValue(pair.Key, out var other) && other.Revision != pair.Value.Revision)
|
||||||
|
throw new InvalidOperationException($"Conflicting discovered revisions for {pair.Key}.");
|
||||||
|
composedState.Current[pair.Key] = pair.Value;
|
||||||
|
}
|
||||||
|
foreach (var pair in state.Known) composedState.Known[pair.Key] = pair.Value;
|
||||||
|
}
|
||||||
|
ShrinkExternalModAssemblyLoader.RestoreState(composedState);
|
||||||
|
ShrinkModNetworkManager.Configure(settings == null || settings.enableNetworkSync, verbose);
|
||||||
|
await _host.ApplyAsync(sources, () => ShrinkExternalModAssemblyLoader.RestoreState(previous));
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
ShrinkExternalModAssemblyLoader.RestoreState(previous);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
return _host.Mods;
|
||||||
|
}
|
||||||
|
|
||||||
public static IReadOnlyShrinkModRegistry<T> GetOrCreateRegistry<T>(string name) =>
|
public static IReadOnlyShrinkModRegistry<T> GetOrCreateRegistry<T>(string name) =>
|
||||||
Host.GetOrCreateRegistry<T>(name);
|
Host.GetOrCreateRegistry<T>(name);
|
||||||
|
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ using UnityEngine;
|
|||||||
|
|
||||||
namespace ShrinkModFramework
|
namespace ShrinkModFramework
|
||||||
{
|
{
|
||||||
internal static class ShrinkModOptionalRuntimeIntegration
|
public static class ShrinkModOptionalRuntimeIntegration
|
||||||
{
|
{
|
||||||
public static IDisposable RegisterModInstance(IShrinkMod modInstance, ShrinkModInfo modInfo,
|
internal static IDisposable RegisterModInstance(IShrinkMod modInstance, ShrinkModInfo modInfo,
|
||||||
bool verboseLogging)
|
bool verboseLogging)
|
||||||
{
|
{
|
||||||
if (modInstance == null || modInfo == null)
|
if (modInstance == null || modInfo == null)
|
||||||
@@ -21,11 +21,12 @@ namespace ShrinkModFramework
|
|||||||
return eventBinding;
|
return eventBinding;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void RefreshGlobalBindings(bool verboseLogging)
|
internal static void RefreshGlobalBindings(bool verboseLogging)
|
||||||
{
|
{
|
||||||
TryRefreshNetworkEventBusBridge(verboseLogging);
|
TryRefreshNetworkEventBusBridge(verboseLogging);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>绑定生成的实例订阅。调用方须 Dispose 返回值,或通过 context.EffectInverse 登记释放。</summary>
|
||||||
public static IDisposable TryAttachEventBusInstance(Type modType, object modInstance,
|
public static IDisposable TryAttachEventBusInstance(Type modType, object modInstance,
|
||||||
string modId, bool verboseLogging)
|
string modId, bool verboseLogging)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -34,17 +34,22 @@ namespace ShrinkModFramework
|
|||||||
private static bool _resolveRegistered;
|
private static bool _resolveRegistered;
|
||||||
private static int _lastWarnedResidentCount;
|
private static int _lastWarnedResidentCount;
|
||||||
|
|
||||||
public static IReadOnlyList<Assembly> LoadExternalAssemblies(ShrinkModFrameworkSettings settings, bool verboseLogging)
|
public static IReadOnlyList<Assembly> LoadExternalAssemblies(
|
||||||
|
ShrinkModFrameworkSettings settings,
|
||||||
|
bool verboseLogging,
|
||||||
|
IEnumerable<string> authorizedDllPaths = null)
|
||||||
{
|
{
|
||||||
return ScanExternalAssemblyRevisions(settings, verboseLogging)
|
return ScanExternalAssemblyRevisions(settings, verboseLogging, authorizedDllPaths)
|
||||||
.Select(revision => revision.Assembly)
|
.Select(revision => revision.Assembly)
|
||||||
.ToArray();
|
.ToArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static IReadOnlyList<ExternalAssemblyRevision> ScanExternalAssemblyRevisions(
|
internal static IReadOnlyList<ExternalAssemblyRevision> ScanExternalAssemblyRevisions(
|
||||||
ShrinkModFrameworkSettings settings, bool verboseLogging)
|
ShrinkModFrameworkSettings settings,
|
||||||
|
bool verboseLogging,
|
||||||
|
IEnumerable<string> authorizedDllPaths = null)
|
||||||
{
|
{
|
||||||
if (settings != null && !settings.enableExternalDllMods)
|
if (settings == null || !settings.enableExternalDllMods)
|
||||||
{
|
{
|
||||||
CurrentAssemblyRevisions.Clear();
|
CurrentAssemblyRevisions.Clear();
|
||||||
KnownAssemblyFiles.Clear();
|
KnownAssemblyFiles.Clear();
|
||||||
@@ -52,27 +57,23 @@ namespace ShrinkModFramework
|
|||||||
}
|
}
|
||||||
|
|
||||||
#if ENABLE_IL2CPP && !UNITY_EDITOR
|
#if ENABLE_IL2CPP && !UNITY_EDITOR
|
||||||
Debug.LogWarning("[ShrinkModFramework] IL2CPP 运行时不支持外部 DLL 热加载,已跳过外部模组扫描。");
|
Debug.LogWarning("[ShrinkModFramework] IL2CPP 运行时不支持外部 DLL 加载,已跳过授权模组。");
|
||||||
return Array.Empty<ExternalAssemblyRevision>();
|
return Array.Empty<ExternalAssemblyRevision>();
|
||||||
#else
|
#else
|
||||||
var modsDirectory = GetExternalModsDirectory(settings);
|
|
||||||
if (settings == null || settings.autoCreateExternalModsDirectory)
|
|
||||||
Directory.CreateDirectory(modsDirectory);
|
|
||||||
|
|
||||||
RegisterAssemblyResolve();
|
RegisterAssemblyResolve();
|
||||||
|
|
||||||
var dllPaths = Directory.GetFiles(modsDirectory, "*.dll", SearchOption.AllDirectories)
|
var dllPaths = NormalizeAuthorizedPaths(authorizedDllPaths);
|
||||||
.Select(Path.GetFullPath)
|
var presentPaths = new HashSet<string>(
|
||||||
.OrderBy(path => path, StringComparer.OrdinalIgnoreCase)
|
dllPaths.Where(File.Exists),
|
||||||
.ToArray();
|
StringComparer.OrdinalIgnoreCase);
|
||||||
var presentPaths = new HashSet<string>(dllPaths, StringComparer.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
foreach (var dllPath in dllPaths
|
KnownAssemblyFiles.Clear();
|
||||||
|
foreach (var dllPath in presentPaths)
|
||||||
|
KnownAssemblyFiles[Path.GetFileNameWithoutExtension(dllPath)] = dllPath;
|
||||||
|
|
||||||
|
foreach (var dllPath in presentPaths
|
||||||
.OrderBy(path => path, StringComparer.OrdinalIgnoreCase))
|
.OrderBy(path => path, StringComparer.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
var assemblyName = Path.GetFileNameWithoutExtension(dllPath);
|
|
||||||
KnownAssemblyFiles[assemblyName] = dllPath;
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var bytes = File.ReadAllBytes(dllPath);
|
var bytes = File.ReadAllBytes(dllPath);
|
||||||
@@ -131,6 +132,41 @@ namespace ShrinkModFramework
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string[] NormalizeAuthorizedPaths(IEnumerable<string> authorizedDllPaths)
|
||||||
|
{
|
||||||
|
if (authorizedDllPaths == null)
|
||||||
|
return Array.Empty<string>();
|
||||||
|
|
||||||
|
var normalized = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
foreach (var rawPath in authorizedDllPaths)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(rawPath))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
string fullPath;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
fullPath = Path.GetFullPath(rawPath.Trim());
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"授权 DLL 路径无效:{rawPath}",
|
||||||
|
nameof(authorizedDllPaths), exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.Equals(Path.GetExtension(fullPath), ".dll",
|
||||||
|
StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"授权路径不是 DLL:{fullPath}",
|
||||||
|
nameof(authorizedDllPaths));
|
||||||
|
}
|
||||||
|
|
||||||
|
normalized.Add(fullPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalized.OrderBy(path => path, StringComparer.OrdinalIgnoreCase).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
internal static bool IsExternalAssembly(Assembly assembly) =>
|
internal static bool IsExternalAssembly(Assembly assembly) =>
|
||||||
assembly != null && ExternalAssemblyHistory.ContainsKey(assembly);
|
assembly != null && ExternalAssemblyHistory.ContainsKey(assembly);
|
||||||
|
|
||||||
@@ -259,7 +295,7 @@ namespace ShrinkModFramework
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
|
internal static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
|
||||||
{
|
{
|
||||||
var requestedName = new AssemblyName(args.Name).Name;
|
var requestedName = new AssemblyName(args.Name).Name;
|
||||||
if (string.IsNullOrWhiteSpace(requestedName))
|
if (string.IsNullOrWhiteSpace(requestedName))
|
||||||
@@ -268,9 +304,37 @@ namespace ShrinkModFramework
|
|||||||
if (!KnownAssemblyFiles.TryGetValue(requestedName, out var path) || !File.Exists(path))
|
if (!KnownAssemblyFiles.TryGetValue(requestedName, out var path) || !File.Exists(path))
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
|
if (ShrinkModLoader.AssemblyResolvePolicy != null &&
|
||||||
|
!ShrinkModLoader.AssemblyResolvePolicy(args.RequestingAssembly, new AssemblyName(args.Name), path))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
lock (ResolveLock)
|
||||||
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return Assembly.Load(File.ReadAllBytes(path));
|
var bytes = File.ReadAllBytes(path);
|
||||||
|
var revision = ComputeSha256(bytes);
|
||||||
|
if (CurrentAssemblyRevisions.TryGetValue(path, out var current) &&
|
||||||
|
string.Equals(current.Revision, revision, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return current.Assembly;
|
||||||
|
}
|
||||||
|
|
||||||
|
var pdbPath = Path.ChangeExtension(path, ".pdb");
|
||||||
|
var pdbBytes = File.Exists(pdbPath) ? File.ReadAllBytes(pdbPath) : null;
|
||||||
|
var assembly = pdbBytes != null
|
||||||
|
? Assembly.Load(bytes, pdbBytes)
|
||||||
|
: Assembly.Load(bytes);
|
||||||
|
var loadedRevision = new ExternalAssemblyRevision
|
||||||
|
{
|
||||||
|
Path = path,
|
||||||
|
Revision = revision,
|
||||||
|
Assembly = assembly,
|
||||||
|
LoadedBytes = bytes.LongLength + (pdbBytes?.LongLength ?? 0L)
|
||||||
|
};
|
||||||
|
CurrentAssemblyRevisions[path] = loadedRevision;
|
||||||
|
ExternalAssemblyHistory[assembly] = loadedRevision;
|
||||||
|
return assembly;
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
@@ -278,4 +342,5 @@ namespace ShrinkModFramework
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -88,7 +88,7 @@ namespace ShrinkModFramework
|
|||||||
private static IDisposable ApplyPatchesCore(ShrinkModInfo modInfo, bool enableHarmonyPatching,
|
private static IDisposable ApplyPatchesCore(ShrinkModInfo modInfo, bool enableHarmonyPatching,
|
||||||
bool verboseLogging, bool reversible)
|
bool verboseLogging, bool reversible)
|
||||||
{
|
{
|
||||||
if (!enableHarmonyPatching || !modInfo.AutoApplyHarmonyPatches)
|
if (!enableHarmonyPatching || !modInfo.AutoApplyHarmonyPatches || modInfo.EntryType == null)
|
||||||
return EmptyLease.Instance;
|
return EmptyLease.Instance;
|
||||||
|
|
||||||
var harmonyType = Type.GetType("HarmonyLib.Harmony, 0Harmony");
|
var harmonyType = Type.GetType("HarmonyLib.Harmony, 0Harmony");
|
||||||
|
|||||||
@@ -18,6 +18,25 @@ namespace ShrinkModFramework
|
|||||||
private static readonly Dictionary<string, ShrinkModHandle> LoadedMods = new(StringComparer.Ordinal);
|
private static readonly Dictionary<string, ShrinkModHandle> LoadedMods = new(StringComparer.Ordinal);
|
||||||
private static readonly List<ShrinkModHandle> LoadSequence = new();
|
private static readonly List<ShrinkModHandle> LoadSequence = new();
|
||||||
private static readonly ShrinkModRegistryManager RegistryManager = new();
|
private static readonly ShrinkModRegistryManager RegistryManager = new();
|
||||||
|
private static string[] _authorizedDllPaths = Array.Empty<string>();
|
||||||
|
private static bool _hostComposed;
|
||||||
|
|
||||||
|
/// <summary>可选解析策略:请求方程序集(可能为 null)、请求名称、候选授权 DLL 的绝对路径。
|
||||||
|
/// 只约束本框架 AssemblyResolve 回调,不是 CLR 已加载程序集的访问沙箱。</summary>
|
||||||
|
public static Func<Assembly, AssemblyName, string, bool> AssemblyResolvePolicy { get; set; }
|
||||||
|
|
||||||
|
public static IReadOnlyDictionary<string, ShrinkModHandle> LoadComposed(
|
||||||
|
ShrinkModFrameworkSettings settings, IReadOnlyList<ShrinkModComponentSource> sources)
|
||||||
|
{
|
||||||
|
if (sources == null) throw new ArgumentNullException(nameof(sources));
|
||||||
|
if (LoadedMods.Count != 0) throw new InvalidOperationException("Cannot compose over legacy loaded mods.");
|
||||||
|
var previous = Mods.ToDictionary(pair => pair.Key, pair => pair.Value.Generation, StringComparer.Ordinal);
|
||||||
|
var result = ShrinkModCordisRuntime.ApplyComposedAsync(settings, sources).GetAwaiter().GetResult();
|
||||||
|
_hostComposed = true;
|
||||||
|
PublishReady(result, previous);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public static bool IsLoaded { get; private set; }
|
public static bool IsLoaded { get; private set; }
|
||||||
public static IReadOnlyDictionary<string, ShrinkModHandle> Mods =>
|
public static IReadOnlyDictionary<string, ShrinkModHandle> Mods =>
|
||||||
@@ -27,8 +46,36 @@ namespace ShrinkModFramework
|
|||||||
public static event Action<IReadOnlyDictionary<string, ShrinkModHandle>> OnAllModsReady;
|
public static event Action<IReadOnlyDictionary<string, ShrinkModHandle>> OnAllModsReady;
|
||||||
|
|
||||||
public static IReadOnlyDictionary<string, ShrinkModHandle> LoadAll(ShrinkModFrameworkSettings settings = null)
|
public static IReadOnlyDictionary<string, ShrinkModHandle> LoadAll(ShrinkModFrameworkSettings settings = null)
|
||||||
|
=> LoadInternal(settings, Array.Empty<string>());
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 加载工程内模组,并且只加载调用方显式授权的外部 DLL 路径。
|
||||||
|
/// 路径集合是完整白名单,不会递归扫描模组目录;后续 revision 刷新也只复用该白名单。
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyDictionary<string, ShrinkModHandle> LoadAuthorized(
|
||||||
|
ShrinkModFrameworkSettings settings,
|
||||||
|
IEnumerable<string> authorizedDllPaths)
|
||||||
{
|
{
|
||||||
|
if (authorizedDllPaths == null)
|
||||||
|
throw new ArgumentNullException(nameof(authorizedDllPaths));
|
||||||
|
|
||||||
|
return LoadInternal(settings, authorizedDllPaths);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyDictionary<string, ShrinkModHandle> LoadInternal(
|
||||||
|
ShrinkModFrameworkSettings settings,
|
||||||
|
IEnumerable<string> authorizedDllPaths)
|
||||||
|
{
|
||||||
|
if (_hostComposed) throw new InvalidOperationException("Use LoadComposed to update a host composition.");
|
||||||
settings ??= ShrinkModFrameworkSettings.Instance;
|
settings ??= ShrinkModFrameworkSettings.Instance;
|
||||||
|
_authorizedDllPaths = authorizedDllPaths
|
||||||
|
.Where(path => !string.IsNullOrWhiteSpace(path))
|
||||||
|
.Select(path => path.Trim())
|
||||||
|
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
if (settings == null || settings.useContextHost)
|
||||||
|
return ApplyContextComposition(settings, _authorizedDllPaths);
|
||||||
|
|
||||||
if (IsLoaded)
|
if (IsLoaded)
|
||||||
{
|
{
|
||||||
@@ -36,15 +83,13 @@ namespace ShrinkModFramework
|
|||||||
return Mods;
|
return Mods;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (settings == null || settings.useContextHost)
|
|
||||||
return ApplyContextComposition(settings);
|
|
||||||
|
|
||||||
var verboseLogging = settings == null || settings.verboseLogging;
|
var verboseLogging = settings == null || settings.verboseLogging;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
ShrinkModNetworkManager.Configure(settings == null || settings.enableNetworkSync, verboseLogging);
|
ShrinkModNetworkManager.Configure(settings == null || settings.enableNetworkSync, verboseLogging);
|
||||||
ShrinkExternalModAssemblyLoader.LoadExternalAssemblies(settings, verboseLogging);
|
ShrinkExternalModAssemblyLoader.LoadExternalAssemblies(
|
||||||
|
settings, verboseLogging, _authorizedDllPaths);
|
||||||
|
|
||||||
var discovered = DiscoverMods(settings);
|
var discovered = DiscoverMods(settings);
|
||||||
var ordered = ResolveLoadOrder(discovered, allowExistingLoadedDependencies: true);
|
var ordered = ResolveLoadOrder(discovered, allowExistingLoadedDependencies: true);
|
||||||
@@ -71,14 +116,16 @@ namespace ShrinkModFramework
|
|||||||
|
|
||||||
public static IReadOnlyDictionary<string, ShrinkModHandle> LoadNewExternalMods(ShrinkModFrameworkSettings settings = null)
|
public static IReadOnlyDictionary<string, ShrinkModHandle> LoadNewExternalMods(ShrinkModFrameworkSettings settings = null)
|
||||||
{
|
{
|
||||||
|
if (_hostComposed) return Mods; // A watcher cannot reconstruct host manifest metadata.
|
||||||
settings ??= ShrinkModFrameworkSettings.Instance;
|
settings ??= ShrinkModFrameworkSettings.Instance;
|
||||||
if (settings == null || settings.useContextHost)
|
if (settings == null || settings.useContextHost)
|
||||||
return ApplyContextComposition(settings);
|
return ApplyContextComposition(settings, _authorizedDllPaths);
|
||||||
if (!IsLoaded)
|
if (!IsLoaded)
|
||||||
return LoadAll(settings);
|
return LoadInternal(settings, _authorizedDllPaths);
|
||||||
|
|
||||||
var verboseLogging = settings == null || settings.verboseLogging;
|
var verboseLogging = settings == null || settings.verboseLogging;
|
||||||
ShrinkExternalModAssemblyLoader.LoadExternalAssemblies(settings, verboseLogging);
|
ShrinkExternalModAssemblyLoader.LoadExternalAssemblies(
|
||||||
|
settings, verboseLogging, _authorizedDllPaths);
|
||||||
|
|
||||||
var discovered = DiscoverMods(settings)
|
var discovered = DiscoverMods(settings)
|
||||||
.Where(mod => !LoadedMods.ContainsKey(mod.Info.ModId))
|
.Where(mod => !LoadedMods.ContainsKey(mod.Info.ModId))
|
||||||
@@ -145,6 +192,9 @@ namespace ShrinkModFramework
|
|||||||
ShrinkModNetworkManager.ResetForDomainReload();
|
ShrinkModNetworkManager.ResetForDomainReload();
|
||||||
ShrinkExternalModAssemblyLoader.ResetForTesting();
|
ShrinkExternalModAssemblyLoader.ResetForTesting();
|
||||||
ShrinkHarmonyPatchService.ResetForTesting();
|
ShrinkHarmonyPatchService.ResetForTesting();
|
||||||
|
_authorizedDllPaths = Array.Empty<string>();
|
||||||
|
_hostComposed = false;
|
||||||
|
AssemblyResolvePolicy = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static void ResetForDomainReload()
|
internal static void ResetForDomainReload()
|
||||||
@@ -160,17 +210,31 @@ namespace ShrinkModFramework
|
|||||||
ShrinkModNetworkManager.ResetForDomainReload();
|
ShrinkModNetworkManager.ResetForDomainReload();
|
||||||
ShrinkExternalModAssemblyLoader.ResetForDomainReload();
|
ShrinkExternalModAssemblyLoader.ResetForDomainReload();
|
||||||
ShrinkHarmonyPatchService.ResetForTesting();
|
ShrinkHarmonyPatchService.ResetForTesting();
|
||||||
|
_authorizedDllPaths = Array.Empty<string>();
|
||||||
|
_hostComposed = false;
|
||||||
|
AssemblyResolvePolicy = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static IReadOnlyDictionary<string, ShrinkModHandle> ApplyContextComposition(
|
private static IReadOnlyDictionary<string, ShrinkModHandle> ApplyContextComposition(
|
||||||
ShrinkModFrameworkSettings settings)
|
ShrinkModFrameworkSettings settings,
|
||||||
|
IEnumerable<string> authorizedDllPaths)
|
||||||
{
|
{
|
||||||
var previousGenerations = Mods.ToDictionary(
|
var previousGenerations = Mods.ToDictionary(
|
||||||
pair => pair.Key,
|
pair => pair.Key,
|
||||||
pair => pair.Value.Generation,
|
pair => pair.Value.Generation,
|
||||||
StringComparer.Ordinal);
|
StringComparer.Ordinal);
|
||||||
|
|
||||||
var result = ShrinkModCordisRuntime.ApplyDiscoveredAsync(settings).GetAwaiter().GetResult();
|
var result = ShrinkModCordisRuntime
|
||||||
|
.ApplyDiscoveredAsync(settings, authorizedDllPaths)
|
||||||
|
.GetAwaiter()
|
||||||
|
.GetResult();
|
||||||
|
PublishReady(result, previousGenerations);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void PublishReady(IReadOnlyDictionary<string, ShrinkModHandle> result,
|
||||||
|
IReadOnlyDictionary<string, long> previousGenerations)
|
||||||
|
{
|
||||||
IsLoaded = true;
|
IsLoaded = true;
|
||||||
foreach (var pair in result.OrderBy(pair => pair.Key, StringComparer.Ordinal))
|
foreach (var pair in result.OrderBy(pair => pair.Key, StringComparer.Ordinal))
|
||||||
{
|
{
|
||||||
@@ -181,7 +245,6 @@ namespace ShrinkModFramework
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
OnAllModsReady?.Invoke(result);
|
OnAllModsReady?.Invoke(result);
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ShrinkModHandle InstantiateAndTrack(DiscoveredMod discoveredMod,
|
private static ShrinkModHandle InstantiateAndTrack(DiscoveredMod discoveredMod,
|
||||||
@@ -206,6 +269,11 @@ namespace ShrinkModFramework
|
|||||||
|
|
||||||
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
|
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
|
||||||
{
|
{
|
||||||
|
if (ShrinkExternalModAssemblyLoader.IsExternalAssembly(assembly) &&
|
||||||
|
!ShrinkExternalModAssemblyLoader.TryGetCurrentRevision(assembly, out _))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (!ShouldScanAssembly(assembly, prefixes))
|
if (!ShouldScanAssembly(assembly, prefixes))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
@@ -229,7 +297,7 @@ namespace ShrinkModFramework
|
|||||||
|
|
||||||
var dependencies = type
|
var dependencies = type
|
||||||
.GetCustomAttributes<ShrinkModDependencyAttribute>(false)
|
.GetCustomAttributes<ShrinkModDependencyAttribute>(false)
|
||||||
.Select(attr => new ShrinkModDependency(attr.ModId, attr.MinimumVersion, attr.Optional))
|
.Select(attr => new ShrinkModDependency(attr.ModId, attr.MinimumVersion, attr.Optional, attr.Ordering, attr.VersionRange))
|
||||||
.ToArray();
|
.ToArray();
|
||||||
|
|
||||||
results.Add(new DiscoveredMod
|
results.Add(new DiscoveredMod
|
||||||
@@ -311,55 +379,20 @@ namespace ShrinkModFramework
|
|||||||
|
|
||||||
private static void ValidateDependencyVersion(ShrinkModInfo owner, ShrinkModDependency dependency, string actualVersion)
|
private static void ValidateDependencyVersion(ShrinkModInfo owner, ShrinkModDependency dependency, string actualVersion)
|
||||||
{
|
{
|
||||||
if (!string.IsNullOrEmpty(dependency.MinimumVersion) &&
|
ShrinkModDependencyGraph.ValidateVersion(owner, dependency, actualVersion);
|
||||||
ShrinkVersionUtility.Compare(actualVersion, dependency.MinimumVersion) < 0)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException(
|
|
||||||
$"模组 {owner.ModId} 依赖 {dependency.ModId} >= {dependency.MinimumVersion},但当前只有 {actualVersion}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<DiscoveredMod> ResolveLoadOrder(List<DiscoveredMod> discovered, bool allowExistingLoadedDependencies)
|
private static List<DiscoveredMod> ResolveLoadOrder(List<DiscoveredMod> discovered, bool allowExistingLoadedDependencies)
|
||||||
{
|
{
|
||||||
var map = discovered.ToDictionary(x => x.Info.ModId, x => x, StringComparer.Ordinal);
|
var map = discovered.ToDictionary(mod => mod.Info.ModId, StringComparer.Ordinal);
|
||||||
var result = new List<DiscoveredMod>();
|
var infos = discovered.Select(mod => mod.Info).ToList();
|
||||||
var visiting = new HashSet<string>(StringComparer.Ordinal);
|
if (allowExistingLoadedDependencies)
|
||||||
var visited = new HashSet<string>(StringComparer.Ordinal);
|
infos.AddRange(LoadedMods.Values.Where(handle => !map.ContainsKey(handle.Info.ModId)).Select(handle => handle.Info));
|
||||||
|
var ordered = ShrinkModDependencyGraph.Order(infos);
|
||||||
foreach (var mod in discovered.OrderBy(x => x.Info.LoadOrder).ThenBy(x => x.Info.ModId, StringComparer.Ordinal))
|
foreach (var loaded in LoadedMods.Keys)
|
||||||
Visit(mod, map, visiting, visited, result, allowExistingLoadedDependencies);
|
if (ShrinkModDependencyGraph.Predecessors(loaded, infos).Any(map.ContainsKey))
|
||||||
|
throw new InvalidOperationException($"Cannot load a new mod before already loaded mod {loaded}; use ContextHost.");
|
||||||
return result;
|
return ordered.Where(info => map.ContainsKey(info.ModId)).Select(info => map[info.ModId]).ToList();
|
||||||
}
|
|
||||||
|
|
||||||
private static void Visit(DiscoveredMod current, Dictionary<string, DiscoveredMod> map,
|
|
||||||
HashSet<string> visiting, HashSet<string> visited, List<DiscoveredMod> result,
|
|
||||||
bool allowExistingLoadedDependencies)
|
|
||||||
{
|
|
||||||
if (visited.Contains(current.Info.ModId))
|
|
||||||
return;
|
|
||||||
|
|
||||||
if (!visiting.Add(current.Info.ModId))
|
|
||||||
throw new InvalidOperationException($"检测到模组循环依赖,涉及 {current.Info.ModId}");
|
|
||||||
|
|
||||||
foreach (var dependency in current.Info.Dependencies.OrderBy(x => x.ModId, StringComparer.Ordinal))
|
|
||||||
{
|
|
||||||
if (map.TryGetValue(dependency.ModId, out var target))
|
|
||||||
{
|
|
||||||
Visit(target, map, visiting, visited, result, allowExistingLoadedDependencies);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allowExistingLoadedDependencies && LoadedMods.ContainsKey(dependency.ModId))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
if (!dependency.Optional)
|
|
||||||
throw new InvalidOperationException($"模组 {current.Info.ModId} 缺少必选依赖 {dependency.ModId}");
|
|
||||||
}
|
|
||||||
|
|
||||||
visiting.Remove(current.Info.ModId);
|
|
||||||
visited.Add(current.Info.ModId);
|
|
||||||
result.Add(current);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static IShrinkMod CreateInstance(DiscoveredMod discovered)
|
private static IShrinkMod CreateInstance(DiscoveredMod discovered)
|
||||||
|
|||||||
@@ -2,12 +2,16 @@ using System;
|
|||||||
|
|
||||||
namespace ShrinkModFramework
|
namespace ShrinkModFramework
|
||||||
{
|
{
|
||||||
|
public enum ShrinkModDependencyOrdering { None, Before, After }
|
||||||
|
|
||||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
|
||||||
public sealed class ShrinkModDependencyAttribute : Attribute
|
public sealed class ShrinkModDependencyAttribute : Attribute
|
||||||
{
|
{
|
||||||
public string ModId { get; }
|
public string ModId { get; }
|
||||||
public string MinimumVersion { get; }
|
public string MinimumVersion { get; }
|
||||||
public bool Optional { get; }
|
public bool Optional { get; }
|
||||||
|
public string VersionRange { get; set; }
|
||||||
|
public ShrinkModDependencyOrdering Ordering { get; set; } = ShrinkModDependencyOrdering.After;
|
||||||
|
|
||||||
public ShrinkModDependencyAttribute(string modId, string minimumVersion = null, bool optional = false)
|
public ShrinkModDependencyAttribute(string modId, string minimumVersion = null, bool optional = false)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace ShrinkModFramework
|
||||||
|
{
|
||||||
|
internal static class ShrinkModDependencyGraph
|
||||||
|
{
|
||||||
|
internal static void ValidateVersion(ShrinkModInfo owner, ShrinkModDependency dependency, string actual)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(dependency.VersionRange) && !ShrinkModVersionRange.Parse(dependency.VersionRange).Contains(actual))
|
||||||
|
throw new InvalidOperationException($"Mod {owner.ModId} requires {dependency.ModId} in range {dependency.VersionRange}, but found {actual}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static IEnumerable<string> Predecessors(string id, IEnumerable<ShrinkModInfo> infos)
|
||||||
|
{
|
||||||
|
var map = infos.ToDictionary(info => info.ModId, StringComparer.Ordinal);
|
||||||
|
foreach (var owner in map.Values)
|
||||||
|
foreach (var dependency in owner.Dependencies)
|
||||||
|
{
|
||||||
|
if (!map.ContainsKey(dependency.ModId)) continue;
|
||||||
|
if (owner.ModId == id && dependency.Ordering == ShrinkModDependencyOrdering.After)
|
||||||
|
yield return dependency.ModId;
|
||||||
|
if (dependency.ModId == id && dependency.Ordering == ShrinkModDependencyOrdering.Before)
|
||||||
|
yield return owner.ModId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static IReadOnlyList<ShrinkModInfo> Order(IEnumerable<ShrinkModInfo> infos)
|
||||||
|
{
|
||||||
|
var map = infos.ToDictionary(info => info.ModId, StringComparer.Ordinal);
|
||||||
|
foreach (var owner in map.Values)
|
||||||
|
foreach (var dependency in owner.Dependencies)
|
||||||
|
{
|
||||||
|
if (map.TryGetValue(dependency.ModId, out var target)) ValidateVersion(owner, dependency, target.Version);
|
||||||
|
else if (!dependency.Optional)
|
||||||
|
throw new InvalidOperationException($"Mod {owner.ModId} is missing required dependency {dependency.ModId}.");
|
||||||
|
}
|
||||||
|
var result = new List<ShrinkModInfo>();
|
||||||
|
var visiting = new HashSet<string>(StringComparer.Ordinal);
|
||||||
|
var visited = new HashSet<string>(StringComparer.Ordinal);
|
||||||
|
void Visit(string id)
|
||||||
|
{
|
||||||
|
if (visited.Contains(id)) return;
|
||||||
|
if (!visiting.Add(id)) throw new InvalidOperationException($"Circular mod dependency/Before/After ordering includes {id}.");
|
||||||
|
foreach (var predecessor in Predecessors(id, map.Values).OrderBy(value => value, StringComparer.Ordinal)) Visit(predecessor);
|
||||||
|
visiting.Remove(id); visited.Add(id); result.Add(map[id]);
|
||||||
|
}
|
||||||
|
foreach (var info in map.Values.OrderBy(info => info.LoadOrder).ThenBy(info => info.ModId, StringComparer.Ordinal)) Visit(info.ModId);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static bool SameMetadata(ShrinkModInfo a, ShrinkModInfo b) =>
|
||||||
|
a.ModId == b.ModId && a.DisplayName == b.DisplayName && a.Version == b.Version &&
|
||||||
|
a.LoadOrder == b.LoadOrder && a.EntryType == b.EntryType && a.AutoApplyHarmonyPatches == b.AutoApplyHarmonyPatches &&
|
||||||
|
a.Dependencies.Count == b.Dependencies.Count && a.Dependencies.Zip(b.Dependencies, (x, y) =>
|
||||||
|
x.ModId == y.ModId && x.VersionRange == y.VersionRange && x.Optional == y.Optional && x.Ordering == y.Ordering).All(equal => equal);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 343ada1a71214620a6c0ca56a56ff70d
|
||||||
@@ -23,7 +23,9 @@ namespace ShrinkModFramework
|
|||||||
LoadOrder = loadOrder;
|
LoadOrder = loadOrder;
|
||||||
EntryType = entryType;
|
EntryType = entryType;
|
||||||
AutoApplyHarmonyPatches = autoApplyHarmonyPatches;
|
AutoApplyHarmonyPatches = autoApplyHarmonyPatches;
|
||||||
Dependencies = dependencies;
|
Dependencies = dependencies == null
|
||||||
|
? Array.Empty<ShrinkModDependency>()
|
||||||
|
: new List<ShrinkModDependency>(dependencies).AsReadOnly();
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() => $"{DisplayName} ({ModId}@{Version})";
|
public override string ToString() => $"{DisplayName} ({ModId}@{Version})";
|
||||||
@@ -35,20 +37,27 @@ namespace ShrinkModFramework
|
|||||||
public string ModId { get; }
|
public string ModId { get; }
|
||||||
public string MinimumVersion { get; }
|
public string MinimumVersion { get; }
|
||||||
public bool Optional { get; }
|
public bool Optional { get; }
|
||||||
|
public string VersionRange { get; }
|
||||||
|
public ShrinkModDependencyOrdering Ordering { get; }
|
||||||
|
|
||||||
public ShrinkModDependency(string modId, string minimumVersion, bool optional)
|
public ShrinkModDependency(string modId, string minimumVersion, bool optional)
|
||||||
|
: this(modId, minimumVersion, optional, ShrinkModDependencyOrdering.After, null) { }
|
||||||
|
|
||||||
|
public ShrinkModDependency(string modId, string minimumVersion, bool optional,
|
||||||
|
ShrinkModDependencyOrdering ordering = ShrinkModDependencyOrdering.After, string versionRange = null)
|
||||||
{
|
{
|
||||||
ModId = modId;
|
if (string.IsNullOrWhiteSpace(modId)) throw new ArgumentException("ModId must not be empty.", nameof(modId));
|
||||||
|
if (!Enum.IsDefined(typeof(ShrinkModDependencyOrdering), ordering))
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(ordering));
|
||||||
|
ModId = modId.Trim();
|
||||||
MinimumVersion = minimumVersion;
|
MinimumVersion = minimumVersion;
|
||||||
Optional = optional;
|
Optional = optional;
|
||||||
|
VersionRange = versionRange ?? minimumVersion;
|
||||||
|
Ordering = ordering;
|
||||||
|
ShrinkModVersionRange.Parse(VersionRange);
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString()
|
public override string ToString() =>
|
||||||
{
|
$"{ModId} {VersionRange ?? "*"} ({Ordering}{(Optional ? ", optional" : "")})";
|
||||||
if (string.IsNullOrEmpty(MinimumVersion))
|
|
||||||
return Optional ? $"{ModId} (optional)" : ModId;
|
|
||||||
|
|
||||||
return Optional ? $"{ModId} >= {MinimumVersion} (optional)" : $"{ModId} >= {MinimumVersion}";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace ShrinkModFramework
|
||||||
|
{
|
||||||
|
/// <summary>Maven 风格区间/并集;裸版本表示最低版本。版本比较沿用框架规则,数字尾部零等价。</summary>
|
||||||
|
public sealed class ShrinkModVersionRange
|
||||||
|
{
|
||||||
|
private readonly List<Func<string, bool>> _ranges = new();
|
||||||
|
private ShrinkModVersionRange() { }
|
||||||
|
|
||||||
|
public static ShrinkModVersionRange Parse(string expression)
|
||||||
|
{
|
||||||
|
var result = new ShrinkModVersionRange();
|
||||||
|
if (string.IsNullOrWhiteSpace(expression)) return result;
|
||||||
|
var text = expression.Trim();
|
||||||
|
if (text[0] != '[' && text[0] != '(')
|
||||||
|
{
|
||||||
|
ValidateVersion(text);
|
||||||
|
result._ranges.Add(version => ShrinkVersionUtility.Compare(version, text) >= 0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
while (text.Length > 0)
|
||||||
|
{
|
||||||
|
var end = text.IndexOfAny(new[] { ']', ')' });
|
||||||
|
if (end < 0 || (text[0] != '[' && text[0] != '(')) throw Invalid(expression);
|
||||||
|
var lowerInclusive = text[0] == '[';
|
||||||
|
var upperInclusive = text[end] == ']';
|
||||||
|
var bounds = text.Substring(1, end - 1).Split(',');
|
||||||
|
string lower, upper;
|
||||||
|
if (bounds.Length == 1)
|
||||||
|
{
|
||||||
|
if (!lowerInclusive || !upperInclusive) throw Invalid(expression);
|
||||||
|
lower = upper = bounds[0].Trim();
|
||||||
|
ValidateVersion(lower);
|
||||||
|
}
|
||||||
|
else if (bounds.Length == 2)
|
||||||
|
{
|
||||||
|
lower = bounds[0].Trim(); upper = bounds[1].Trim();
|
||||||
|
if (lower.Length > 0) ValidateVersion(lower);
|
||||||
|
if (upper.Length > 0) ValidateVersion(upper);
|
||||||
|
if ((lower.Length == 0 && lowerInclusive) || (upper.Length == 0 && upperInclusive))
|
||||||
|
throw Invalid(expression);
|
||||||
|
if (lower.Length > 0 && upper.Length > 0)
|
||||||
|
{
|
||||||
|
var comparison = ShrinkVersionUtility.Compare(lower, upper);
|
||||||
|
if (comparison > 0 || (comparison == 0 && (!lowerInclusive || !upperInclusive))) throw Invalid(expression);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else throw Invalid(expression);
|
||||||
|
result._ranges.Add(version =>
|
||||||
|
(lower.Length == 0 || (lowerInclusive ? ShrinkVersionUtility.Compare(version, lower) >= 0 : ShrinkVersionUtility.Compare(version, lower) > 0)) &&
|
||||||
|
(upper.Length == 0 || (upperInclusive ? ShrinkVersionUtility.Compare(version, upper) <= 0 : ShrinkVersionUtility.Compare(version, upper) < 0)));
|
||||||
|
text = text.Substring(end + 1).Trim();
|
||||||
|
if (text.Length == 0) break;
|
||||||
|
if (text[0] != ',' || text.Length == 1) throw Invalid(expression);
|
||||||
|
text = text.Substring(1).Trim();
|
||||||
|
if (text.Length == 0) throw Invalid(expression);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Contains(string version)
|
||||||
|
{
|
||||||
|
ValidateVersion(version);
|
||||||
|
return _ranges.Count == 0 || _ranges.Any(range => range(version));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ValidateVersion(string version)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(version) || !Regex.IsMatch(version, @"^[0-9]+(?:[.][0-9]+)*(?:[-+][A-Za-z0-9.-]+)?$"))
|
||||||
|
throw Invalid(version);
|
||||||
|
}
|
||||||
|
private static FormatException Invalid(string value) => new FormatException($"Invalid mod version range: '{value}'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: c9d273c1b5d349a1822f3dfc3d8e6ff2
|
||||||
@@ -23,6 +23,8 @@ namespace ShrinkModFramework
|
|||||||
return leftValue.CompareTo(rightValue);
|
return leftValue.CompareTo(rightValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (System.Text.RegularExpressions.Regex.IsMatch(left, @"^[0-9]+(?:[.][0-9]+)*$") &&
|
||||||
|
System.Text.RegularExpressions.Regex.IsMatch(right, @"^[0-9]+(?:[.][0-9]+)*$")) return 0;
|
||||||
return string.CompareOrdinal(left, right);
|
return string.CompareOrdinal(left, right);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,312 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using NUnit.Framework;
|
||||||
|
using ShrinkEventBus;
|
||||||
|
using UnityEngine;
|
||||||
|
|
||||||
|
namespace ShrinkModFramework.Tests
|
||||||
|
{
|
||||||
|
public sealed class ShrinkModCompositionTests
|
||||||
|
{
|
||||||
|
private ShrinkModFrameworkSettings _settings;
|
||||||
|
[SetUp] public void SetUp()
|
||||||
|
{
|
||||||
|
ShrinkModLoader.ResetForTesting();
|
||||||
|
_settings = ScriptableObject.CreateInstance<ShrinkModFrameworkSettings>();
|
||||||
|
_settings.enableHarmonyPatching = false;
|
||||||
|
_settings.verboseLogging = false;
|
||||||
|
_settings.assemblyNamePrefixes = new[] { "ExternalFixture." };
|
||||||
|
}
|
||||||
|
[TearDown] public void TearDown()
|
||||||
|
{
|
||||||
|
ShrinkModLoader.ResetForTesting();
|
||||||
|
UnityEngine.Object.DestroyImmediate(_settings);
|
||||||
|
}
|
||||||
|
private static ShrinkModInfo Info(string id, params ShrinkModDependency[] dependencies) =>
|
||||||
|
new ShrinkModInfo(id, id, "1.2.0", 0, null, false, dependencies);
|
||||||
|
private static ShrinkModComponentSource Source(string id, Action<ShrinkModContext> construct = null,
|
||||||
|
params ShrinkModDependency[] dependencies) => new ShrinkModComponentSource(Info(id, dependencies), "r1",
|
||||||
|
() => new Mod { Construct = construct });
|
||||||
|
private static ShrinkModDependency Dep(string id, ShrinkModDependencyOrdering ordering, bool optional = true,
|
||||||
|
string range = null) => new ShrinkModDependency(id, null, optional, ordering, range);
|
||||||
|
|
||||||
|
[Test] public void ComposedLoad_UsesManifestOrderAndAllFourPhases_AndPublishesReadyOnce()
|
||||||
|
{
|
||||||
|
var phases = new List<string>(); var ready = new List<string>(); var all = 0;
|
||||||
|
ShrinkModLoader.OnModReady += handle => { Assert.IsTrue(ShrinkModLoader.IsLoaded); ready.Add(handle.Info.ModId); };
|
||||||
|
ShrinkModLoader.OnAllModsReady += mods => { Assert.AreEqual(2, mods.Count); all++; };
|
||||||
|
ShrinkModComponentSource Make(string id, params ShrinkModDependency[] dependencies) =>
|
||||||
|
new ShrinkModComponentSource(Info(id, dependencies), "r1", () => new Mod
|
||||||
|
{
|
||||||
|
Construct = _ => phases.Add(id + ":construct"), Register = _ => phases.Add(id + ":register"),
|
||||||
|
Initialize = _ => phases.Add(id + ":initialize"), Ready = _ => phases.Add(id + ":ready")
|
||||||
|
});
|
||||||
|
var sources = new[] { Make("a.addon", new ShrinkModDependency("z.core", "1.0", false)), Make("z.core") };
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, sources);
|
||||||
|
Assert.That(phases, Is.EqualTo(new[] { "z.core:construct", "z.core:register", "z.core:initialize", "z.core:ready",
|
||||||
|
"a.addon:construct", "a.addon:register", "a.addon:initialize", "a.addon:ready" }));
|
||||||
|
Assert.That(ready, Is.EquivalentTo(new[] { "z.core", "a.addon" }));
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, sources);
|
||||||
|
Assert.AreEqual(2, ready.Count); Assert.AreEqual(2, all); Assert.AreEqual(8, phases.Count);
|
||||||
|
Assert.AreEqual(2, ShrinkModLoader.LoadNewExternalMods(_settings).Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void DataOnly_AllowsNullEntryAndReversibleContent()
|
||||||
|
{
|
||||||
|
var source = ShrinkModComponentSource.CreateDataOnly(Info("data"), "r1",
|
||||||
|
() => new Mod { Register = ctx => ctx.RegisterContent("items", "one", "value") });
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { source, ShrinkModComponentSource.CreateDataOnly(Info("empty"), "r1") });
|
||||||
|
Assert.IsNull(ShrinkModLoader.Mods["empty"].Instance);
|
||||||
|
Assert.IsNull(ShrinkModLoader.Mods["data"].Info.EntryType);
|
||||||
|
var registry = ShrinkModLoader.GetOrCreateRegistry<string>("items");
|
||||||
|
Assert.IsTrue(registry.Contains("data:one"));
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, Array.Empty<ShrinkModComponentSource>());
|
||||||
|
Assert.IsFalse(registry.Contains("data:one")); Assert.IsEmpty(ShrinkModLoader.Mods);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void Wrapper_ExposesRealInstance_AndAutomaticallyAttachesAndDetachesGeneratedSubscribers()
|
||||||
|
{
|
||||||
|
var real = new Subscriber();
|
||||||
|
var busKey = ShrinkBusKey.Mod("wrapped");
|
||||||
|
var bus = EventBus.GetOrCreateBus(busKey, ShrinkBusOptions.Inline());
|
||||||
|
var wrapperCalls = 0;
|
||||||
|
var source = new ShrinkModComponentSource(Info("wrapped"), "r1", () => new Wrapper(real, ctx =>
|
||||||
|
{
|
||||||
|
wrapperCalls++; Assert.IsTrue(ctx.TryGetLoadedMod("wrapped", out var handle)); Assert.AreSame(real, handle.Instance);
|
||||||
|
}));
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { source });
|
||||||
|
Assert.AreSame(real, ShrinkModLoader.Mods["wrapped"].Instance);
|
||||||
|
bus.Post(new Ping()); Assert.AreEqual(1, real.Events); Assert.AreEqual(1, wrapperCalls);
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, Array.Empty<ShrinkModComponentSource>());
|
||||||
|
Assert.AreEqual(1, real.Detaches);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void PublicEventAttachment_CanBeDisposedExplicitly()
|
||||||
|
{
|
||||||
|
var real = new Subscriber(); var key = ShrinkBusKey.Mod("manual");
|
||||||
|
var bus = EventBus.GetOrCreateBus(key, ShrinkBusOptions.Inline());
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var binding = ShrinkModOptionalRuntimeIntegration.TryAttachEventBusInstance(real.GetType(), real, "manual", false);
|
||||||
|
Assert.IsNotNull(binding); bus.Post(new Ping()); Assert.AreEqual(1, real.Events);
|
||||||
|
binding.Dispose(); bus.Post(new Ping()); Assert.AreEqual(1, real.Events);
|
||||||
|
}
|
||||||
|
finally { EventBus.RemoveBus(key); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestCase("[1.0,2.0)", "1.0.0", true)]
|
||||||
|
[TestCase("[1.0,2.0)", "2.0", false)]
|
||||||
|
[TestCase("[1.2,)", "7.0", true)]
|
||||||
|
[TestCase("1.0", "0.9", false)]
|
||||||
|
[TestCase("1.0", "1.0.0", true)]
|
||||||
|
[TestCase("[1.2]", "1.2.0", true)]
|
||||||
|
[TestCase("(,1.0],[1.2,)", "1.1", false)]
|
||||||
|
public void Ranges_ParseAndCheckBounds(string range, string version, bool expected) =>
|
||||||
|
Assert.AreEqual(expected, ShrinkModVersionRange.Parse(range).Contains(version));
|
||||||
|
[TestCase("[2,1]")] [TestCase("[1,2")] [TestCase("[1,)", false)]
|
||||||
|
public void Ranges_RejectInvalidSyntax(string range, bool invalid = true)
|
||||||
|
{
|
||||||
|
if (invalid) Assert.Throws<FormatException>(() => ShrinkModVersionRange.Parse(range));
|
||||||
|
else Assert.DoesNotThrow(() => ShrinkModVersionRange.Parse(range));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void RangeAndMissingMandatoryErrors_PreserveCurrentComposition()
|
||||||
|
{
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { Source("core") });
|
||||||
|
var generation = ShrinkModLoader.Mods["core"].Generation;
|
||||||
|
var violation = Source("addon", null, Dep("core", ShrinkModDependencyOrdering.After, false, "[2,3)"));
|
||||||
|
var error = Assert.Throws<InvalidOperationException>(() => ShrinkModLoader.LoadComposed(_settings, new[] { Source("core"), violation }));
|
||||||
|
Assert.That(error.Message, Does.Contain("[2,3)"));
|
||||||
|
Assert.Throws<InvalidOperationException>(() => ShrinkModLoader.LoadComposed(_settings, new[] { violation }));
|
||||||
|
Assert.AreEqual(generation, ShrinkModLoader.Mods["core"].Generation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestCase(ShrinkModDependencyOrdering.Before, "a", "z")]
|
||||||
|
[TestCase(ShrinkModDependencyOrdering.After, "z", "a")]
|
||||||
|
[TestCase(ShrinkModDependencyOrdering.None, "a", "z")]
|
||||||
|
public void OptionalOrdering_OrdersPresentTargets_AndAllowsAbsentTargets(ShrinkModDependencyOrdering order, string first, string second)
|
||||||
|
{
|
||||||
|
var calls = new List<string>();
|
||||||
|
var a = Source("a", _ => calls.Add("a"), Dep("z", order));
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { a, Source("z", _ => calls.Add("z")) });
|
||||||
|
Assert.That(calls, Is.EqualTo(new[] { first, second }));
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { a });
|
||||||
|
Assert.That(ShrinkModLoader.Mods.Keys, Is.EquivalentTo(new[] { "a" }));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void BeforeCycles_AreRejectedBeforeLifecycle()
|
||||||
|
{
|
||||||
|
var a = Source("a", _ => Assert.Fail("No lifecycle before validation"), Dep("b", ShrinkModDependencyOrdering.Before));
|
||||||
|
var b = Source("b", null, Dep("a", ShrinkModDependencyOrdering.Before));
|
||||||
|
var error = Assert.Throws<InvalidOperationException>(() => ShrinkModLoader.LoadComposed(_settings, new[] { a, b }));
|
||||||
|
Assert.That(error.Message, Does.Contain("Circular")); Assert.IsFalse(ShrinkModLoader.IsLoaded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void ChangedIncomingOrdering_RebuildsExistingTarget()
|
||||||
|
{
|
||||||
|
var calls = new List<string>(); var z = Source("z", _ => calls.Add("z"));
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { z }); calls.Clear();
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { z, Source("a", _ => calls.Add("a"), Dep("z", ShrinkModDependencyOrdering.Before)) });
|
||||||
|
Assert.That(calls, Is.EqualTo(new[] { "a", "z" }));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void FailedReplacement_RestoresPublicInstanceAndEventBinding()
|
||||||
|
{
|
||||||
|
var instances = new List<Subscriber>();
|
||||||
|
var source = new ShrinkModComponentSource(Info("wrapped"), "r1", () =>
|
||||||
|
{ var real = new Subscriber(); instances.Add(real); return new Wrapper(real, null); });
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { source });
|
||||||
|
var broken = source.WithMetadata(source.Info, "r2", () => new Mod { Initialize = _ => throw new InvalidOperationException("broken") });
|
||||||
|
Assert.Throws<ShrinkModTransactionException>(() => ShrinkModLoader.LoadComposed(_settings, new[] { broken }));
|
||||||
|
Assert.IsTrue(ShrinkModLoader.IsLoaded); Assert.AreEqual(2, instances.Count);
|
||||||
|
Assert.AreEqual(1, instances[0].Detaches); Assert.AreSame(instances[1], ShrinkModLoader.Mods["wrapped"].Instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void Discovery_IsPublicAuthorizedAndDeferred_WithShaRevisionAndRollback()
|
||||||
|
{
|
||||||
|
_settings.enableExternalDllMods = true;
|
||||||
|
var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".dll");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Copy(Fixture("ExternalFixture.Mod.V1.dll.bytes"), path);
|
||||||
|
Assert.IsEmpty(ShrinkModComponentDiscovery.Discover(_settings, Array.Empty<string>()));
|
||||||
|
var source = ShrinkModComponentDiscovery.Discover(_settings, new[] { path }).Single();
|
||||||
|
Assert.IsFalse(ShrinkModLoader.IsLoaded); Assert.IsEmpty(ShrinkModLoader.Mods);
|
||||||
|
Assert.AreEqual(0, ShrinkModDiagnostics.CaptureExternalAssemblies(_settings).CurrentRevisionCount);
|
||||||
|
using (var sha = System.Security.Cryptography.SHA256.Create())
|
||||||
|
Assert.That(source.Revision, Does.StartWith(BitConverter.ToString(sha.ComputeHash(File.ReadAllBytes(path))).Replace("-", "") + ":"));
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { source.WithMetadata(source.Info, source.Revision) });
|
||||||
|
Assert.AreEqual(1, ShrinkModDiagnostics.CaptureExternalAssemblies(_settings).CurrentRevisionCount);
|
||||||
|
var oldRevision = source.Revision;
|
||||||
|
File.Copy(Fixture("ExternalFixture.Mod.V2.Failing.dll.bytes"), path, true);
|
||||||
|
var broken = ShrinkModComponentDiscovery.Discover(_settings, new[] { path }).Single();
|
||||||
|
Assert.Throws<ShrinkModTransactionException>(() => ShrinkModLoader.LoadComposed(_settings, new[] { broken }));
|
||||||
|
Assert.AreEqual(oldRevision, ShrinkModCordisRuntime.Host.CurrentSources.Single().Revision);
|
||||||
|
Assert.AreEqual("1.0.0", ShrinkModLoader.Mods["external.fixture"].Info.Version);
|
||||||
|
}
|
||||||
|
finally { File.Delete(path); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void ResolvePolicy_ReceivesRequesterNameAndAuthorizedPath_AndCanDenyCachedCandidate()
|
||||||
|
{
|
||||||
|
_settings.enableExternalDllMods = true;
|
||||||
|
var path = Path.Combine(Path.GetTempPath(), "ExternalFixture.Mod." + Guid.NewGuid() + ".dll");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Copy(Fixture("ExternalFixture.Mod.V1.dll.bytes"), path);
|
||||||
|
ShrinkModLoader.LoadAuthorized(_settings, new[] { path });
|
||||||
|
var name = Path.GetFileNameWithoutExtension(path);
|
||||||
|
var args = new ResolveEventArgs(name, typeof(ShrinkModCompositionTests).Assembly);
|
||||||
|
Assert.IsNotNull(ShrinkExternalModAssemblyLoader.OnAssemblyResolve(null, args));
|
||||||
|
var calls = 0;
|
||||||
|
ShrinkModLoader.AssemblyResolvePolicy = (requester, requested, candidate) =>
|
||||||
|
{ calls++; Assert.AreSame(args.RequestingAssembly, requester); Assert.AreEqual(name, requested.Name); Assert.AreEqual(path, candidate); return false; };
|
||||||
|
Assert.IsNull(ShrinkExternalModAssemblyLoader.OnAssemblyResolve(null, args)); Assert.AreEqual(1, calls);
|
||||||
|
Assert.IsNull(ShrinkExternalModAssemblyLoader.OnAssemblyResolve(null, new ResolveEventArgs("not.authorized")));
|
||||||
|
Assert.AreEqual(1, calls);
|
||||||
|
ShrinkModLoader.AssemblyResolvePolicy = (_, __, ___) => true;
|
||||||
|
Assert.IsNotNull(ShrinkExternalModAssemblyLoader.OnAssemblyResolve(null, args));
|
||||||
|
var state = ShrinkExternalModAssemblyLoader.CaptureState();
|
||||||
|
state.Current.Clear();
|
||||||
|
ShrinkExternalModAssemblyLoader.RestoreState(state);
|
||||||
|
ShrinkModLoader.AssemblyResolvePolicy = (_, __, ___) => false;
|
||||||
|
Assert.IsNull(ShrinkExternalModAssemblyLoader.OnAssemblyResolve(null, args));
|
||||||
|
Assert.AreEqual(0, ShrinkModDiagnostics.CaptureExternalAssemblies(_settings).CurrentRevisionCount);
|
||||||
|
ShrinkModLoader.AssemblyResolvePolicy = (_, __, ___) => true;
|
||||||
|
Assert.IsNotNull(ShrinkExternalModAssemblyLoader.OnAssemblyResolve(null, args));
|
||||||
|
}
|
||||||
|
finally { File.Delete(path); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void ManifestMetadataChange_WithSameRevision_RevalidatesAndRebuilds()
|
||||||
|
{
|
||||||
|
var first = Source("mod");
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { first });
|
||||||
|
var generation = ShrinkModLoader.Mods["mod"].Generation;
|
||||||
|
var info = new ShrinkModInfo("mod", "new manifest name", "1.3", 0, null, false,
|
||||||
|
new[] { Dep("missing.optional", ShrinkModDependencyOrdering.None) });
|
||||||
|
ShrinkModLoader.LoadComposed(_settings, new[] { first.WithMetadata(info, first.Revision) });
|
||||||
|
Assert.Greater(ShrinkModLoader.Mods["mod"].Generation, generation);
|
||||||
|
Assert.AreEqual("1.3", ShrinkModLoader.Mods["mod"].Info.Version);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void MixedBeforeAfterCycle_AndOptionalRangeViolation_AreRejected()
|
||||||
|
{
|
||||||
|
var a = Source("a", null, Dep("b", ShrinkModDependencyOrdering.Before));
|
||||||
|
var b = Source("b", null, Dep("c", ShrinkModDependencyOrdering.Before));
|
||||||
|
var c = Source("c", null, Dep("a", ShrinkModDependencyOrdering.Before));
|
||||||
|
Assert.Throws<InvalidOperationException>(() => ShrinkModLoader.LoadComposed(_settings, new[] { a, b, c }));
|
||||||
|
c = Source("c", null, Dep("b", ShrinkModDependencyOrdering.After), Dep("a", ShrinkModDependencyOrdering.Before));
|
||||||
|
Assert.Throws<InvalidOperationException>(() => ShrinkModLoader.LoadComposed(_settings, new[] { a, b, c }));
|
||||||
|
Assert.Throws<InvalidOperationException>(() => ShrinkModLoader.LoadComposed(_settings, new[]
|
||||||
|
{ Source("a", null, Dep("b", ShrinkModDependencyOrdering.None, true, "[2,3)")), Source("b") }));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void InitialLifecycleFailure_KeepsLoaderUnloadedAndSuppressesReadyEvents()
|
||||||
|
{
|
||||||
|
var notifications = 0;
|
||||||
|
ShrinkModLoader.OnModReady += _ => notifications++;
|
||||||
|
ShrinkModLoader.OnAllModsReady += _ => notifications++;
|
||||||
|
var source = new ShrinkModComponentSource(Info("broken"), "r1", () => new Mod
|
||||||
|
{ Ready = _ => throw new InvalidOperationException("failure") });
|
||||||
|
Assert.Throws<ShrinkModTransactionException>(() => ShrinkModLoader.LoadComposed(_settings, new[] { source }));
|
||||||
|
Assert.IsFalse(ShrinkModLoader.IsLoaded); Assert.IsEmpty(ShrinkModLoader.Mods); Assert.AreEqual(0, notifications);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test] public void AttributeRangeAndOrdering_ArePreservedByDiscovery()
|
||||||
|
{
|
||||||
|
_settings.assemblyNamePrefixes = new[] { typeof(AttributeMod).Assembly.GetName().Name };
|
||||||
|
var source = ShrinkModComponentDiscovery.Discover(_settings, Array.Empty<string>())
|
||||||
|
.Single(item => item.Info.ModId == "composition.attribute");
|
||||||
|
var dependency = source.Info.Dependencies.Single();
|
||||||
|
Assert.AreEqual("[1,2)", dependency.VersionRange);
|
||||||
|
Assert.AreEqual(ShrinkModDependencyOrdering.Before, dependency.Ordering); Assert.IsTrue(dependency.Optional);
|
||||||
|
Assert.IsFalse(ShrinkModLoader.IsLoaded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[ShrinkMod("composition.attribute", "Attribute fixture", "1.0")]
|
||||||
|
[ShrinkModDependency("composition.target", optional: true, VersionRange = "[1,2)", Ordering = ShrinkModDependencyOrdering.Before)]
|
||||||
|
public sealed class AttributeMod : ShrinkModBase { }
|
||||||
|
|
||||||
|
private static string Fixture(string name)
|
||||||
|
{
|
||||||
|
var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(ShrinkModCompositionTests).Assembly);
|
||||||
|
var root = package != null ? package.resolvedPath : UnityEditor.AssetDatabase.FindAssets("ShrinkModFramework.Tests t:asmdef")
|
||||||
|
.Select(UnityEditor.AssetDatabase.GUIDToAssetPath).Select(Path.GetDirectoryName).Select(Path.GetDirectoryName).First();
|
||||||
|
return Path.Combine(root, "Tests", "Fixtures", name);
|
||||||
|
}
|
||||||
|
private class Mod : ShrinkModBase
|
||||||
|
{
|
||||||
|
public Action<ShrinkModContext> Construct, Register, Initialize, Ready;
|
||||||
|
public override void OnConstruct(ShrinkModContext context) => Construct?.Invoke(context);
|
||||||
|
public override void OnRegisterContent(ShrinkModContext context) => Register?.Invoke(context);
|
||||||
|
public override void OnInitialize(ShrinkModContext context) => Initialize?.Invoke(context);
|
||||||
|
public override void OnReady(ShrinkModContext context) => Ready?.Invoke(context);
|
||||||
|
}
|
||||||
|
private sealed class Wrapper : Mod, IShrinkModWrapper
|
||||||
|
{
|
||||||
|
public Wrapper(IShrinkMod real, Action<ShrinkModContext> construct) { PublicInstance = real; Construct = construct; }
|
||||||
|
public IShrinkMod PublicInstance { get; }
|
||||||
|
}
|
||||||
|
private readonly struct Ping : IShrinkEvent { }
|
||||||
|
private sealed class Subscriber : ShrinkModBase, IShrinkGeneratedSubscriber
|
||||||
|
{
|
||||||
|
public int Events, Detaches;
|
||||||
|
public IDisposable AttachGenerated(IShrinkBusResolver resolver, ShrinkBusKey? defaultBus = null)
|
||||||
|
{
|
||||||
|
var subscription = ShrinkGeneratedBinding.Subscribe<Ping>(resolver, defaultBus, null, this,
|
||||||
|
_ => Events++, ShrinkEventPriority.Normal, 0, false);
|
||||||
|
return new Lease(() => { subscription.Dispose(); Detaches++; });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private sealed class Lease : IDisposable
|
||||||
|
{
|
||||||
|
private Action _dispose;
|
||||||
|
public Lease(Action dispose) { _dispose = dispose; }
|
||||||
|
public void Dispose() { var dispose = _dispose; _dispose = null; dispose?.Invoke(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 44e4b1f576a745fe9c36b173015b98a3
|
||||||
@@ -286,7 +286,23 @@ namespace ShrinkModFramework.Tests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public void ExternalDllRevision_FailedReplacementRestoresPreviousAndBrokenBytesDoNotReplaceIt()
|
public void Settings_Defaults_DoNotAutoLoadOrWatchExternalDlls()
|
||||||
|
{
|
||||||
|
var settings = ScriptableObject.CreateInstance<ShrinkModFrameworkSettings>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Assert.IsFalse(settings.autoLoadOnStartup);
|
||||||
|
Assert.IsFalse(settings.enableExternalDllMods);
|
||||||
|
Assert.IsFalse(settings.watchExternalModsDirectory);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Object.DestroyImmediate(settings);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public void ExternalDll_IsIgnoredUntilItsExactPathIsAuthorized()
|
||||||
{
|
{
|
||||||
ResetExternalRuntime();
|
ResetExternalRuntime();
|
||||||
var settings = CreateExternalSettings();
|
var settings = CreateExternalSettings();
|
||||||
@@ -299,6 +315,62 @@ namespace ShrinkModFramework.Tests
|
|||||||
CopyFixture("ExternalFixture.Mod.V1.dll.bytes", target);
|
CopyFixture("ExternalFixture.Mod.V1.dll.bytes", target);
|
||||||
|
|
||||||
ShrinkModLoader.LoadAll(settings);
|
ShrinkModLoader.LoadAll(settings);
|
||||||
|
|
||||||
|
Assert.IsEmpty(ShrinkModLoader.Mods);
|
||||||
|
Assert.AreEqual(0,
|
||||||
|
ShrinkModDiagnostics.CaptureExternalAssemblies(settings).CurrentRevisionCount);
|
||||||
|
|
||||||
|
ShrinkModLoader.LoadAuthorized(settings, new[] { target });
|
||||||
|
AssertExternalFixture("1.0.0", "v1");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
CleanupExternalRuntime(settings, directory);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public void LegacyLoader_OnlyLoadsExplicitlyAuthorizedDllPaths()
|
||||||
|
{
|
||||||
|
ResetExternalRuntime();
|
||||||
|
var settings = CreateExternalSettings();
|
||||||
|
settings.useContextHost = false;
|
||||||
|
var directory = ShrinkExternalModAssemblyLoader.GetExternalModsDirectory(settings);
|
||||||
|
var authorized = Path.Combine(directory, "Authorized.Mod.dll");
|
||||||
|
var unauthorized = Path.Combine(directory, "Unauthorized.Mod.dll");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
CopyFixture("ExternalFixture.Mod.V1.dll.bytes", authorized);
|
||||||
|
CopyFixture("ExternalFixture.Mod.V3.dll.bytes", unauthorized);
|
||||||
|
|
||||||
|
ShrinkModLoader.LoadAuthorized(settings, new[] { authorized });
|
||||||
|
|
||||||
|
AssertExternalFixture("1.0.0", "v1");
|
||||||
|
Assert.AreEqual(1,
|
||||||
|
ShrinkModDiagnostics.CaptureExternalAssemblies(settings).CurrentRevisionCount);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
CleanupExternalRuntime(settings, directory);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public void ExternalDllRevision_FailedReplacementRestoresPreviousAndBrokenBytesDoNotReplaceIt()
|
||||||
|
{
|
||||||
|
ResetExternalRuntime();
|
||||||
|
var settings = CreateExternalSettings();
|
||||||
|
var directory = ShrinkExternalModAssemblyLoader.GetExternalModsDirectory(settings);
|
||||||
|
var target = Path.Combine(directory, "ExternalFixture.Mod.dll");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
CopyFixture("ExternalFixture.Mod.V1.dll.bytes", target);
|
||||||
|
|
||||||
|
ShrinkModLoader.LoadAuthorized(settings, new[] { target });
|
||||||
AssertExternalFixture("1.0.0", "v1");
|
AssertExternalFixture("1.0.0", "v1");
|
||||||
var restoredGeneration = ShrinkModLoader.Mods["external.fixture"].Generation;
|
var restoredGeneration = ShrinkModLoader.Mods["external.fixture"].Generation;
|
||||||
|
|
||||||
@@ -358,7 +430,7 @@ namespace ShrinkModFramework.Tests
|
|||||||
Assert.IsTrue(ShrinkModRuntimeDriver.InstanceForTesting!.HasWatcherForTesting);
|
Assert.IsTrue(ShrinkModRuntimeDriver.InstanceForTesting!.HasWatcherForTesting);
|
||||||
|
|
||||||
CopyFixture("ExternalFixture.Mod.V1.dll.bytes", target);
|
CopyFixture("ExternalFixture.Mod.V1.dll.bytes", target);
|
||||||
ShrinkModLoader.LoadAll(settings);
|
ShrinkModLoader.LoadAuthorized(settings, new[] { target });
|
||||||
AssertExternalFixture("1.0.0", "v1");
|
AssertExternalFixture("1.0.0", "v1");
|
||||||
|
|
||||||
// Two writes arrive as one debounce window; only the final valid revision should commit.
|
// Two writes arrive as one debounce window; only the final valid revision should commit.
|
||||||
@@ -395,7 +467,7 @@ namespace ShrinkModFramework.Tests
|
|||||||
CopyFixture("ExternalFixture.Provider.dll.bytes", providerPath);
|
CopyFixture("ExternalFixture.Provider.dll.bytes", providerPath);
|
||||||
CopyFixture("ExternalFixture.Consumer.dll.bytes", consumerPath);
|
CopyFixture("ExternalFixture.Consumer.dll.bytes", consumerPath);
|
||||||
|
|
||||||
ShrinkModLoader.LoadAll(settings);
|
ShrinkModLoader.LoadAuthorized(settings, new[] { providerPath, consumerPath });
|
||||||
Assert.AreEqual(2, ShrinkModLoader.Mods.Count);
|
Assert.AreEqual(2, ShrinkModLoader.Mods.Count);
|
||||||
Assert.AreEqual(ShrinkModState.Ready, ShrinkModLoader.Mods["external.provider"].State);
|
Assert.AreEqual(ShrinkModState.Ready, ShrinkModLoader.Mods["external.provider"].State);
|
||||||
Assert.AreEqual(ShrinkModState.Ready, ShrinkModLoader.Mods["external.consumer"].State);
|
Assert.AreEqual(ShrinkModState.Ready, ShrinkModLoader.Mods["external.consumer"].State);
|
||||||
@@ -475,6 +547,7 @@ namespace ShrinkModFramework.Tests
|
|||||||
settings.useContextHost = true;
|
settings.useContextHost = true;
|
||||||
settings.enableExternalDllMods = true;
|
settings.enableExternalDllMods = true;
|
||||||
settings.autoCreateExternalModsDirectory = false;
|
settings.autoCreateExternalModsDirectory = false;
|
||||||
|
settings.watchExternalModsDirectory = true;
|
||||||
settings.externalModsFolderName = "ShrinkModFrameworkTests_" + Guid.NewGuid().ToString("N");
|
settings.externalModsFolderName = "ShrinkModFrameworkTests_" + Guid.NewGuid().ToString("N");
|
||||||
settings.assemblyNamePrefixes = new[] { "ExternalFixture." };
|
settings.assemblyNamePrefixes = new[] { "ExternalFixture." };
|
||||||
settings.enableHarmonyPatching = false;
|
settings.enableHarmonyPatching = false;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
"rootNamespace": "ShrinkModFramework.Tests",
|
"rootNamespace": "ShrinkModFramework.Tests",
|
||||||
"references": [
|
"references": [
|
||||||
"ShrinkModFramework.Runtime",
|
"ShrinkModFramework.Runtime",
|
||||||
|
"ShrinkEventBus.Runtime",
|
||||||
"ShrinkContext.Core.Runtime",
|
"ShrinkContext.Core.Runtime",
|
||||||
"UniTask",
|
"UniTask",
|
||||||
"UnityEngine.TestRunner",
|
"UnityEngine.TestRunner",
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# 独立生命周期回归
|
||||||
|
|
||||||
|
从包根运行:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
dotnet test Tools~/HostTests/Tests/Tests.csproj --configuration Release
|
||||||
|
```
|
||||||
|
|
||||||
|
此 harness 编译包内真实 Unity Loader、ContextHost、Registry 和测试源码,使用已发布的 Context.Core 0.3.1、EventBus 2.3.1 与 UniTask。测试替身只覆盖 Unity 对象创建、日志、时钟和编辑器包路径查询;不模拟 Unity PlayerLoop、程序集导入或 IL 编织。生成订阅测试直接实现生成合同。原生 Unity EditMode 测试仍使用 `Tests` asmdef。
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework><AssemblyName>ShrinkModFramework.Runtime</AssemblyName>
|
||||||
|
<Nullable>disable</Nullable><ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="../../../Runtime/**/*.cs" />
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
<PackageReference Include="ShrinkSDK.Context.Core" Version="0.3.1" />
|
||||||
|
<PackageReference Include="ShrinkSDK.EventBus" Version="2.3.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
// Minimal engine boundary for .NET lifecycle tests; not a Unity runtime replacement.
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace UnityEngine
|
||||||
|
{
|
||||||
|
public class Object
|
||||||
|
{
|
||||||
|
public static implicit operator bool(Object value) => value != null;
|
||||||
|
public static void DestroyImmediate(Object value)
|
||||||
|
{
|
||||||
|
if (value is GameObject go) foreach (var component in go.Components)
|
||||||
|
component.GetType().GetMethod("OnDestroy", BindingFlags.NonPublic | BindingFlags.Instance)?.Invoke(component, null);
|
||||||
|
}
|
||||||
|
public static void Destroy(Object value) => DestroyImmediate(value);
|
||||||
|
public static void DontDestroyOnLoad(Object value) { }
|
||||||
|
}
|
||||||
|
public class ScriptableObject : Object { public static T CreateInstance<T>() where T : ScriptableObject, new() => new T(); }
|
||||||
|
public class MonoBehaviour : Object { public GameObject gameObject; }
|
||||||
|
public class GameObject : Object
|
||||||
|
{
|
||||||
|
internal readonly List<MonoBehaviour> Components = new();
|
||||||
|
public GameObject(string name) { }
|
||||||
|
public T AddComponent<T>() where T : MonoBehaviour, new() { var c = new T { gameObject = this }; Components.Add(c); return c; }
|
||||||
|
}
|
||||||
|
public static class Resources { public static T Load<T>(string path) where T : Object => null; }
|
||||||
|
public static class Application { public static string persistentDataPath => System.IO.Path.GetTempPath(); public static bool isPlaying => false; }
|
||||||
|
public static class Time { private static readonly Stopwatch Clock = Stopwatch.StartNew(); public static float realtimeSinceStartup => (float)Clock.Elapsed.TotalSeconds; }
|
||||||
|
public static class Mathf { public static float Max(float a, float b) => Math.Max(a, b); }
|
||||||
|
public enum LogType { Error, Assert, Warning, Log, Exception }
|
||||||
|
public static class Debug
|
||||||
|
{
|
||||||
|
public static event Action<LogType, string> Logged;
|
||||||
|
public static void Log(object value) => Logged?.Invoke(LogType.Log, value?.ToString());
|
||||||
|
public static void LogWarning(object value) => Logged?.Invoke(LogType.Warning, value?.ToString());
|
||||||
|
public static void LogError(object value) => Logged?.Invoke(LogType.Error, value?.ToString());
|
||||||
|
public static void LogException(Exception value) => Logged?.Invoke(LogType.Exception, value.ToString());
|
||||||
|
}
|
||||||
|
public class CreateAssetMenuAttribute : Attribute { public string fileName, menuName; }
|
||||||
|
public class HeaderAttribute : Attribute { public HeaderAttribute(string text) { } }
|
||||||
|
public class TooltipAttribute : Attribute { public TooltipAttribute(string text) { } }
|
||||||
|
public class MinAttribute : Attribute { public MinAttribute(float value) { } }
|
||||||
|
public class SerializeField : Attribute { }
|
||||||
|
public class DefaultExecutionOrder : Attribute { public DefaultExecutionOrder(int value) { } }
|
||||||
|
public enum RuntimeInitializeLoadType { SubsystemRegistration, AfterAssembliesLoaded }
|
||||||
|
public class RuntimeInitializeOnLoadMethodAttribute : Attribute { public RuntimeInitializeOnLoadMethodAttribute(RuntimeInitializeLoadType type) { } }
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using NUnit.Framework;
|
||||||
|
using UnityEngine;
|
||||||
|
|
||||||
|
namespace UnityEditor.PackageManager
|
||||||
|
{
|
||||||
|
public class PackageInfo
|
||||||
|
{
|
||||||
|
public string resolvedPath;
|
||||||
|
public static PackageInfo FindForAssembly(System.Reflection.Assembly assembly)
|
||||||
|
{
|
||||||
|
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||||
|
while (directory != null && !File.Exists(Path.Combine(directory.FullName, "package.json"))) directory = directory.Parent;
|
||||||
|
return new PackageInfo { resolvedPath = directory?.FullName ?? throw new DirectoryNotFoundException("Package root") };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
namespace UnityEditor
|
||||||
|
{
|
||||||
|
public static class AssetDatabase
|
||||||
|
{
|
||||||
|
public static string[] FindAssets(string query) => Array.Empty<string>();
|
||||||
|
public static string GUIDToAssetPath(string guid) => guid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
namespace UnityEngine.TestTools
|
||||||
|
{
|
||||||
|
public static class LogAssert
|
||||||
|
{
|
||||||
|
internal static readonly Queue<(LogType type, Regex text)> Expected = new();
|
||||||
|
public static void Expect(LogType type, Regex text) => Expected.Enqueue((type, text));
|
||||||
|
public static void Expect(LogType type, string text) => Expect(type, new Regex(Regex.Escape(text)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[SetUpFixture]
|
||||||
|
public class LogVerification
|
||||||
|
{
|
||||||
|
private readonly List<string> _unexpected = new();
|
||||||
|
[OneTimeSetUp] public void Start() => Debug.Logged += Observe;
|
||||||
|
private void Observe(LogType type, string text)
|
||||||
|
{
|
||||||
|
var expected = UnityEngine.TestTools.LogAssert.Expected;
|
||||||
|
if (expected.Count > 0 && expected.Peek().type == type && expected.Peek().text.IsMatch(text)) expected.Dequeue();
|
||||||
|
else if (type == LogType.Error || type == LogType.Exception) _unexpected.Add(text);
|
||||||
|
}
|
||||||
|
[OneTimeTearDown] public void Finish()
|
||||||
|
{
|
||||||
|
Debug.Logged -= Observe;
|
||||||
|
Assert.IsEmpty(_unexpected, "Unexpected Unity-style errors");
|
||||||
|
Assert.IsEmpty(UnityEngine.TestTools.LogAssert.Expected, "Expected log was not emitted");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework><AssemblyName>ShrinkModFramework.Tests</AssemblyName>
|
||||||
|
<Nullable>disable</Nullable><IsPackable>false</IsPackable><ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="../Runtime/Runtime.csproj" />
|
||||||
|
<Compile Include="../../../Tests/*.cs" />
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||||
|
<PackageReference Include="NUnit" Version="3.14.0" />
|
||||||
|
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
+3
-3
@@ -1,13 +1,13 @@
|
|||||||
{
|
{
|
||||||
"name": "com.cneicy.shrink-mod-framework",
|
"name": "com.cneicy.shrink-mod-framework",
|
||||||
"version": "0.2.2",
|
"version": "0.3.8",
|
||||||
"displayName": "ShrinkModFramework",
|
"displayName": "ShrinkModFramework",
|
||||||
"description": "Unity 模组框架,提供发现、依赖、可逆生命周期、命名空间内容注册与优先级覆盖。",
|
"description": "Unity 模组框架,提供发现、依赖、可逆生命周期、命名空间内容注册与优先级覆盖。",
|
||||||
"unity": "2022.3",
|
"unity": "2022.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"com.unity.nuget.newtonsoft-json": "3.2.2",
|
"com.unity.nuget.newtonsoft-json": "3.2.2",
|
||||||
"com.cneicy.shrink-context-core": "0.1.0",
|
"com.cneicy.shrink-context-core": "0.3.1",
|
||||||
"com.cneicy.shrink-eventbus": "2.0.0",
|
"com.cneicy.shrink-eventbus": "2.3.1",
|
||||||
"com.cysharp.unitask": "2.5.10"
|
"com.cysharp.unitask": "2.5.10"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
|
|||||||
Reference in new issue
Block a user