diff --git a/CHANGELOG.md b/CHANGELOG.md
index 55d14ff..175c177 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,24 @@
本文件记录 `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
diff --git a/DotNet~/ShrinkSDK.ModFramework.csproj b/DotNet~/ShrinkSDK.ModFramework.csproj
index 9d98a23..e52d9e6 100644
--- a/DotNet~/ShrinkSDK.ModFramework.csproj
+++ b/DotNet~/ShrinkSDK.ModFramework.csproj
@@ -5,7 +5,7 @@
ShrinkModFramework.Runtime
ShrinkModFramework
ShrinkSDK.ModFramework
- 0.3.7
+ 0.3.8
Engine-neutral ShrinkSDK mod contracts and lifecycle.
disable
false
diff --git a/Godot~/ShrinkSDK.ModFramework.Godot.csproj b/Godot~/ShrinkSDK.ModFramework.Godot.csproj
index b1a58cc..81d8a05 100644
--- a/Godot~/ShrinkSDK.ModFramework.Godot.csproj
+++ b/Godot~/ShrinkSDK.ModFramework.Godot.csproj
@@ -4,7 +4,7 @@
ShrinkModFramework.Godot
ShrinkModFramework.Godot
ShrinkSDK.ModFramework.Godot
- 0.1.6
+ 0.1.7
Collectible AssemblyLoadContext host for ShrinkSDK mods in Godot.
false
diff --git a/README.md b/README.md
index fddb798..a5463a5 100644
--- a/README.md
+++ b/README.md
@@ -54,6 +54,114 @@ ShrinkModLoader.LoadAuthorized(settings, authorizedDllPaths);
`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());
+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` 可处理数据注册。
+数据包的 `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,本次仅更新它对共享包的发布引用。
+
## 配置文件
菜单 `ShrinkSDK/模组/创建设置` 会在
@@ -678,9 +786,9 @@ public sealed partial class DemoFullMod : ShrinkModBase
## 设计约束
-- 一个模组类必须有 `[ShrinkMod]`
+- 自动发现的模组类必须有 `[ShrinkMod]`;宿主组合使用显式元数据和工厂
- 一个模组类必须实现 `IShrinkMod`
-- 一个模组类必须能被无参构造
+- 自动发现的模组类必须能被无参构造;宿主工厂可自行构造包装器
- 模组 ID 必须全局唯一
- 必选依赖缺失或版本不满足时,装载直接失败
- 检测到循环依赖时,装载直接失败
diff --git a/Runtime/Context/ShrinkModComponent.cs b/Runtime/Context/ShrinkModComponent.cs
index 8284900..4c0a5d4 100644
--- a/Runtime/Context/ShrinkModComponent.cs
+++ b/Runtime/Context/ShrinkModComponent.cs
@@ -19,9 +19,8 @@ namespace ShrinkModFramework
{
_host = host ?? throw new ArgumentNullException(nameof(host));
_source = source ?? throw new ArgumentNullException(nameof(source));
- _inject = source.Info.Dependencies
- .Where(dependency => !dependency.Optional)
- .Select(dependency => ShrinkModContextHost.GetModKey(dependency.ModId))
+ _inject = host.GetPredecessors(source.Info.ModId)
+ .Select(ShrinkModContextHost.GetModKey)
.Distinct(StringComparer.Ordinal)
.ToArray();
_provide = new[] { ShrinkModContextHost.GetModKey(source.Info.ModId) };
@@ -37,7 +36,8 @@ namespace ShrinkModFramework
if (instance == null)
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()
};
@@ -70,7 +70,7 @@ namespace ShrinkModFramework
IDisposable eventBinding = null;
ctx.Effect(
() => eventBinding = ShrinkModOptionalRuntimeIntegration.TryAttachEventBusInstance(
- instance.GetType(), instance, handle.Info.ModId, _host.VerboseLogging),
+ publicInstance?.GetType(), publicInstance, handle.Info.ModId, _host.VerboseLogging),
() =>
{
eventBinding?.Dispose();
diff --git a/Runtime/Context/ShrinkModComponentDiscovery.cs b/Runtime/Context/ShrinkModComponentDiscovery.cs
index 5edc0e2..251f9bd 100644
--- a/Runtime/Context/ShrinkModComponentDiscovery.cs
+++ b/Runtime/Context/ShrinkModComponentDiscovery.cs
@@ -10,9 +10,29 @@ namespace ShrinkModFramework
/// 把工程内程序集和外部 DLL 的当前 revision 投影为延迟组件源。
/// 同一路径的旧外部程序集无法从 Mono AppDomain 卸载,但不会再进入候选集合。
///
- internal static class ShrinkModComponentDiscovery
+ public static class ShrinkModComponentDiscovery
{
public static IReadOnlyList Discover(
+ ShrinkModFrameworkSettings settings, IEnumerable authorizedDllPaths) =>
+ Discover(settings, settings != null && settings.verboseLogging, authorizedDllPaths);
+
+ /// 只发现,不构造实例或提交 current revision。WithMetadata 可保留发现快照。
+ public static IReadOnlyList Discover(
+ ShrinkModFrameworkSettings settings, bool verboseLogging, IEnumerable authorizedDllPaths)
+ {
+ 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 DiscoverCurrent(
ShrinkModFrameworkSettings settings,
bool verboseLogging,
IEnumerable authorizedDllPaths)
@@ -53,7 +73,7 @@ namespace ShrinkModFramework
var dependencies = type
.GetCustomAttributes(false)
.Select(attribute => new ShrinkModDependency(
- attribute.ModId, attribute.MinimumVersion, attribute.Optional))
+ attribute.ModId, attribute.MinimumVersion, attribute.Optional, attribute.Ordering, attribute.VersionRange))
.ToArray();
var info = new ShrinkModInfo(
modAttribute.ModId,
diff --git a/Runtime/Context/ShrinkModComponentSource.cs b/Runtime/Context/ShrinkModComponentSource.cs
index 351b8c0..71b3c06 100644
--- a/Runtime/Context/ShrinkModComponentSource.cs
+++ b/Runtime/Context/ShrinkModComponentSource.cs
@@ -2,9 +2,15 @@ using System;
namespace ShrinkModFramework
{
+ /// 宿主包装器执行生命周期;Handle 和自动订阅使用 PublicInstance。数据包可返回 null。
+ public interface IShrinkModWrapper : IShrinkMod
+ {
+ IShrinkMod PublicInstance { get; }
+ }
+
///
/// 延迟模组组件源。Revision 是来源内容的稳定指纹(外部 DLL 可使用文件哈希);
- /// 同一 ModId 的 revision/factory 变化由 ShrinkModContextHost 作为替换事务处理。
+ /// 同一 ModId 的 revision/metadata 变化由 ShrinkModContextHost 作为替换事务处理。
///
public sealed class ShrinkModComponentSource
{
@@ -23,5 +29,27 @@ namespace ShrinkModFramework
public ShrinkModInfo Info { get; }
public string Revision { get; }
public Func Factory { get; }
+
+ internal ShrinkExternalModAssemblyLoader.RevisionState DiscoveryState { get; set; }
+
+ /// 替换清单元数据或生命周期工厂,同时保留授权发现的程序集 revision。
+ public ShrinkModComponentSource WithMetadata(ShrinkModInfo info, string revision,
+ Func factory = null) =>
+ new ShrinkModComponentSource(info, revision, factory ?? Factory) { DiscoveryState = DiscoveryState };
+
+ /// 创建无入口类型的数据包;可选生命周期工厂用于注册内容和可逆效应。
+ public static ShrinkModComponentSource CreateDataOnly(ShrinkModInfo info, string revision,
+ Func 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;
+ }
}
}
diff --git a/Runtime/Context/ShrinkModContextHost.cs b/Runtime/Context/ShrinkModContextHost.cs
index 64a002d..bd8c1cd 100644
--- a/Runtime/Context/ShrinkModContextHost.cs
+++ b/Runtime/Context/ShrinkModContextHost.cs
@@ -33,6 +33,10 @@ namespace ShrinkModFramework
private long _generation;
private int _catalogGeneration;
private bool _applying;
+ private IReadOnlyList _buildingSources = Array.Empty();
+
+ internal IEnumerable GetPredecessors(string modId) =>
+ ShrinkModDependencyGraph.Predecessors(modId, _buildingSources.Select(source => source.Info));
public ShrinkModContextHost(bool enableHarmonyPatching = true, bool verboseLogging = false)
{
@@ -64,7 +68,9 @@ namespace ShrinkModFramework
return "shrink.mod/" + modId.Trim();
}
- public async UniTask ApplyAsync(IReadOnlyList desiredSources)
+ public UniTask ApplyAsync(IReadOnlyList desiredSources) => ApplyAsync(desiredSources, null);
+
+ internal async UniTask ApplyAsync(IReadOnlyList desiredSources, Action beforeRestore)
{
if (desiredSources == null)
throw new ArgumentNullException(nameof(desiredSources));
@@ -95,8 +101,11 @@ namespace ShrinkModFramework
catch (Exception applyError)
{
Exception restoreError = null;
+ _currentSources.Clear();
+ _currentSources.AddRange(previous);
try
{
+ beforeRestore?.Invoke();
await Loader.ApplyAsync(BuildEntries(previous));
EnsureActive(previous);
}
@@ -143,6 +152,7 @@ namespace ShrinkModFramework
private IReadOnlyList BuildEntries(IEnumerable sources)
{
+ _buildingSources = sources.ToArray();
var entries = new List();
foreach (var source in sources)
{
@@ -184,79 +194,34 @@ namespace ShrinkModFramework
throw new InvalidOperationException($"Duplicate mod source id: {source.Info.ModId}");
}
- foreach (var source in sources)
- {
- 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();
- var visiting = new HashSet(StringComparer.Ordinal);
- var visited = new HashSet(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;
+ return ShrinkModDependencyGraph.Order(sources.Select(source => source.Info))
+ .Select(info => map[info.ModId]).ToList();
}
private List ReuseUnchangedSources(
IEnumerable desired)
{
+ var desiredArray = desired.ToArray();
var currentById = _currentSources.ToDictionary(source => source.Info.ModId, StringComparer.Ordinal);
var normalized = new List();
- foreach (var source in desired)
+ foreach (var source in desiredArray)
{
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);
}
else
{
- normalized.Add(source);
+ normalized.Add(ReferenceEquals(source, current)
+ ? source.WithMetadata(source.Info, source.Revision) : source);
}
}
return normalized;
}
- private static void Visit(ShrinkModComponentSource source,
- IReadOnlyDictionary map,
- ISet visiting,
- ISet visited,
- ICollection 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);
- }
}
}
diff --git a/Runtime/Context/ShrinkModCordisRuntime.cs b/Runtime/Context/ShrinkModCordisRuntime.cs
index 0b218f5..a55cdb6 100644
--- a/Runtime/Context/ShrinkModCordisRuntime.cs
+++ b/Runtime/Context/ShrinkModCordisRuntime.cs
@@ -37,9 +37,9 @@ namespace ShrinkModFramework
try
{
var authorizedPaths = authorizedDllPaths?.ToArray() ?? Array.Empty();
- var sources = ShrinkModComponentDiscovery.Discover(
+ var sources = ShrinkModComponentDiscovery.DiscoverCurrent(
settings, verboseLogging, authorizedPaths);
- await _host.ApplyAsync(sources);
+ await _host.ApplyAsync(sources, () => ShrinkExternalModAssemblyLoader.RestoreState(revisionState));
}
catch
{
@@ -54,6 +54,42 @@ namespace ShrinkModFramework
return _host.Mods;
}
+ /// 提交宿主组合;生命周期或发现失败时恢复之前的程序集 revision 和组件。
+ public static async UniTask> ApplyComposedAsync(
+ ShrinkModFrameworkSettings settings, IReadOnlyList 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 GetOrCreateRegistry(string name) =>
Host.GetOrCreateRegistry(name);
diff --git a/Runtime/Integration/ShrinkModOptionalRuntimeIntegration.cs b/Runtime/Integration/ShrinkModOptionalRuntimeIntegration.cs
index a91d217..73399c7 100644
--- a/Runtime/Integration/ShrinkModOptionalRuntimeIntegration.cs
+++ b/Runtime/Integration/ShrinkModOptionalRuntimeIntegration.cs
@@ -6,9 +6,9 @@ using UnityEngine;
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)
{
if (modInstance == null || modInfo == null)
@@ -21,11 +21,12 @@ namespace ShrinkModFramework
return eventBinding;
}
- public static void RefreshGlobalBindings(bool verboseLogging)
+ internal static void RefreshGlobalBindings(bool verboseLogging)
{
TryRefreshNetworkEventBusBridge(verboseLogging);
}
+ /// 绑定生成的实例订阅。调用方须 Dispose 返回值,或通过 context.EffectInverse 登记释放。
public static IDisposable TryAttachEventBusInstance(Type modType, object modInstance,
string modId, bool verboseLogging)
{
diff --git a/Runtime/Loading/ShrinkExternalModAssemblyLoader.cs b/Runtime/Loading/ShrinkExternalModAssemblyLoader.cs
index 4f9aab7..e2fe65a 100644
--- a/Runtime/Loading/ShrinkExternalModAssemblyLoader.cs
+++ b/Runtime/Loading/ShrinkExternalModAssemblyLoader.cs
@@ -295,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;
if (string.IsNullOrWhiteSpace(requestedName))
@@ -304,6 +304,10 @@ namespace ShrinkModFramework
if (!KnownAssemblyFiles.TryGetValue(requestedName, out var path) || !File.Exists(path))
return null;
+ if (ShrinkModLoader.AssemblyResolvePolicy != null &&
+ !ShrinkModLoader.AssemblyResolvePolicy(args.RequestingAssembly, new AssemblyName(args.Name), path))
+ return null;
+
lock (ResolveLock)
{
try
diff --git a/Runtime/Loading/ShrinkHarmonyPatchService.cs b/Runtime/Loading/ShrinkHarmonyPatchService.cs
index bf44f5f..258fc66 100644
--- a/Runtime/Loading/ShrinkHarmonyPatchService.cs
+++ b/Runtime/Loading/ShrinkHarmonyPatchService.cs
@@ -88,7 +88,7 @@ namespace ShrinkModFramework
private static IDisposable ApplyPatchesCore(ShrinkModInfo modInfo, bool enableHarmonyPatching,
bool verboseLogging, bool reversible)
{
- if (!enableHarmonyPatching || !modInfo.AutoApplyHarmonyPatches)
+ if (!enableHarmonyPatching || !modInfo.AutoApplyHarmonyPatches || modInfo.EntryType == null)
return EmptyLease.Instance;
var harmonyType = Type.GetType("HarmonyLib.Harmony, 0Harmony");
diff --git a/Runtime/Loading/ShrinkModLoader.cs b/Runtime/Loading/ShrinkModLoader.cs
index fddbe8d..1640658 100644
--- a/Runtime/Loading/ShrinkModLoader.cs
+++ b/Runtime/Loading/ShrinkModLoader.cs
@@ -19,6 +19,24 @@ namespace ShrinkModFramework
private static readonly List LoadSequence = new();
private static readonly ShrinkModRegistryManager RegistryManager = new();
private static string[] _authorizedDllPaths = Array.Empty();
+ private static bool _hostComposed;
+
+ /// 可选解析策略:请求方程序集(可能为 null)、请求名称、候选授权 DLL 的绝对路径。
+ /// 只约束本框架 AssemblyResolve 回调,不是 CLR 已加载程序集的访问沙箱。
+ public static Func AssemblyResolvePolicy { get; set; }
+
+ public static IReadOnlyDictionary LoadComposed(
+ ShrinkModFrameworkSettings settings, IReadOnlyList 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 IReadOnlyDictionary Mods =>
@@ -48,6 +66,7 @@ namespace ShrinkModFramework
ShrinkModFrameworkSettings settings,
IEnumerable authorizedDllPaths)
{
+ if (_hostComposed) throw new InvalidOperationException("Use LoadComposed to update a host composition.");
settings ??= ShrinkModFrameworkSettings.Instance;
_authorizedDllPaths = authorizedDllPaths
.Where(path => !string.IsNullOrWhiteSpace(path))
@@ -97,6 +116,7 @@ namespace ShrinkModFramework
public static IReadOnlyDictionary LoadNewExternalMods(ShrinkModFrameworkSettings settings = null)
{
+ if (_hostComposed) return Mods; // A watcher cannot reconstruct host manifest metadata.
settings ??= ShrinkModFrameworkSettings.Instance;
if (settings == null || settings.useContextHost)
return ApplyContextComposition(settings, _authorizedDllPaths);
@@ -173,6 +193,8 @@ namespace ShrinkModFramework
ShrinkExternalModAssemblyLoader.ResetForTesting();
ShrinkHarmonyPatchService.ResetForTesting();
_authorizedDllPaths = Array.Empty();
+ _hostComposed = false;
+ AssemblyResolvePolicy = null;
}
internal static void ResetForDomainReload()
@@ -189,6 +211,8 @@ namespace ShrinkModFramework
ShrinkExternalModAssemblyLoader.ResetForDomainReload();
ShrinkHarmonyPatchService.ResetForTesting();
_authorizedDllPaths = Array.Empty();
+ _hostComposed = false;
+ AssemblyResolvePolicy = null;
}
private static IReadOnlyDictionary ApplyContextComposition(
@@ -204,6 +228,13 @@ namespace ShrinkModFramework
.ApplyDiscoveredAsync(settings, authorizedDllPaths)
.GetAwaiter()
.GetResult();
+ PublishReady(result, previousGenerations);
+ return result;
+ }
+
+ private static void PublishReady(IReadOnlyDictionary result,
+ IReadOnlyDictionary previousGenerations)
+ {
IsLoaded = true;
foreach (var pair in result.OrderBy(pair => pair.Key, StringComparer.Ordinal))
{
@@ -214,7 +245,6 @@ namespace ShrinkModFramework
}
}
OnAllModsReady?.Invoke(result);
- return result;
}
private static ShrinkModHandle InstantiateAndTrack(DiscoveredMod discoveredMod,
@@ -267,7 +297,7 @@ namespace ShrinkModFramework
var dependencies = type
.GetCustomAttributes(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();
results.Add(new DiscoveredMod
@@ -349,55 +379,20 @@ namespace ShrinkModFramework
private static void ValidateDependencyVersion(ShrinkModInfo owner, ShrinkModDependency dependency, string actualVersion)
{
- if (!string.IsNullOrEmpty(dependency.MinimumVersion) &&
- ShrinkVersionUtility.Compare(actualVersion, dependency.MinimumVersion) < 0)
- {
- throw new InvalidOperationException(
- $"模组 {owner.ModId} 依赖 {dependency.ModId} >= {dependency.MinimumVersion},但当前只有 {actualVersion}");
- }
+ ShrinkModDependencyGraph.ValidateVersion(owner, dependency, actualVersion);
}
private static List ResolveLoadOrder(List discovered, bool allowExistingLoadedDependencies)
{
- var map = discovered.ToDictionary(x => x.Info.ModId, x => x, StringComparer.Ordinal);
- var result = new List();
- var visiting = new HashSet(StringComparer.Ordinal);
- var visited = new HashSet(StringComparer.Ordinal);
-
- foreach (var mod in discovered.OrderBy(x => x.Info.LoadOrder).ThenBy(x => x.Info.ModId, StringComparer.Ordinal))
- Visit(mod, map, visiting, visited, result, allowExistingLoadedDependencies);
-
- return result;
- }
-
- private static void Visit(DiscoveredMod current, Dictionary map,
- HashSet visiting, HashSet visited, List 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);
+ var map = discovered.ToDictionary(mod => mod.Info.ModId, StringComparer.Ordinal);
+ var infos = discovered.Select(mod => mod.Info).ToList();
+ if (allowExistingLoadedDependencies)
+ infos.AddRange(LoadedMods.Values.Where(handle => !map.ContainsKey(handle.Info.ModId)).Select(handle => handle.Info));
+ var ordered = ShrinkModDependencyGraph.Order(infos);
+ foreach (var loaded in LoadedMods.Keys)
+ if (ShrinkModDependencyGraph.Predecessors(loaded, infos).Any(map.ContainsKey))
+ throw new InvalidOperationException($"Cannot load a new mod before already loaded mod {loaded}; use ContextHost.");
+ return ordered.Where(info => map.ContainsKey(info.ModId)).Select(info => map[info.ModId]).ToList();
}
private static IShrinkMod CreateInstance(DiscoveredMod discovered)
diff --git a/Runtime/Metadata/ShrinkModDependencyAttribute.cs b/Runtime/Metadata/ShrinkModDependencyAttribute.cs
index a3768f0..280f08b 100644
--- a/Runtime/Metadata/ShrinkModDependencyAttribute.cs
+++ b/Runtime/Metadata/ShrinkModDependencyAttribute.cs
@@ -2,12 +2,16 @@ using System;
namespace ShrinkModFramework
{
+ public enum ShrinkModDependencyOrdering { None, Before, After }
+
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public sealed class ShrinkModDependencyAttribute : Attribute
{
public string ModId { get; }
public string MinimumVersion { 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)
{
diff --git a/Runtime/Metadata/ShrinkModDependencyGraph.cs b/Runtime/Metadata/ShrinkModDependencyGraph.cs
new file mode 100644
index 0000000..d08f066
--- /dev/null
+++ b/Runtime/Metadata/ShrinkModDependencyGraph.cs
@@ -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 Predecessors(string id, IEnumerable 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 Order(IEnumerable 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();
+ var visiting = new HashSet(StringComparer.Ordinal);
+ var visited = new HashSet(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);
+ }
+}
diff --git a/Runtime/Metadata/ShrinkModDependencyGraph.cs.meta b/Runtime/Metadata/ShrinkModDependencyGraph.cs.meta
new file mode 100644
index 0000000..97fe855
--- /dev/null
+++ b/Runtime/Metadata/ShrinkModDependencyGraph.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 343ada1a71214620a6c0ca56a56ff70d
diff --git a/Runtime/Metadata/ShrinkModInfo.cs b/Runtime/Metadata/ShrinkModInfo.cs
index c105adc..d27147c 100644
--- a/Runtime/Metadata/ShrinkModInfo.cs
+++ b/Runtime/Metadata/ShrinkModInfo.cs
@@ -23,7 +23,9 @@ namespace ShrinkModFramework
LoadOrder = loadOrder;
EntryType = entryType;
AutoApplyHarmonyPatches = autoApplyHarmonyPatches;
- Dependencies = dependencies;
+ Dependencies = dependencies == null
+ ? Array.Empty()
+ : new List(dependencies).AsReadOnly();
}
public override string ToString() => $"{DisplayName} ({ModId}@{Version})";
@@ -35,20 +37,27 @@ namespace ShrinkModFramework
public string ModId { get; }
public string MinimumVersion { get; }
public bool Optional { get; }
+ public string VersionRange { get; }
+ public ShrinkModDependencyOrdering Ordering { get; }
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;
Optional = optional;
+ VersionRange = versionRange ?? minimumVersion;
+ Ordering = ordering;
+ ShrinkModVersionRange.Parse(VersionRange);
}
- public override string ToString()
- {
- if (string.IsNullOrEmpty(MinimumVersion))
- return Optional ? $"{ModId} (optional)" : ModId;
-
- return Optional ? $"{ModId} >= {MinimumVersion} (optional)" : $"{ModId} >= {MinimumVersion}";
- }
+ public override string ToString() =>
+ $"{ModId} {VersionRange ?? "*"} ({Ordering}{(Optional ? ", optional" : "")})";
}
}
diff --git a/Runtime/Metadata/ShrinkModVersionRange.cs b/Runtime/Metadata/ShrinkModVersionRange.cs
new file mode 100644
index 0000000..14595fa
--- /dev/null
+++ b/Runtime/Metadata/ShrinkModVersionRange.cs
@@ -0,0 +1,78 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+
+namespace ShrinkModFramework
+{
+ /// Maven 风格区间/并集;裸版本表示最低版本。版本比较沿用框架规则,数字尾部零等价。
+ public sealed class ShrinkModVersionRange
+ {
+ private readonly List> _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}'.");
+ }
+}
diff --git a/Runtime/Metadata/ShrinkModVersionRange.cs.meta b/Runtime/Metadata/ShrinkModVersionRange.cs.meta
new file mode 100644
index 0000000..fc043fc
--- /dev/null
+++ b/Runtime/Metadata/ShrinkModVersionRange.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: c9d273c1b5d349a1822f3dfc3d8e6ff2
diff --git a/Runtime/Metadata/ShrinkVersionUtility.cs b/Runtime/Metadata/ShrinkVersionUtility.cs
index f753f51..ad0dbcd 100644
--- a/Runtime/Metadata/ShrinkVersionUtility.cs
+++ b/Runtime/Metadata/ShrinkVersionUtility.cs
@@ -23,6 +23,8 @@ namespace ShrinkModFramework
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);
}
diff --git a/Tests/ShrinkModCompositionTests.cs b/Tests/ShrinkModCompositionTests.cs
new file mode 100644
index 0000000..1546ef0
--- /dev/null
+++ b/Tests/ShrinkModCompositionTests.cs
@@ -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();
+ _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 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(); var ready = new List(); 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("items");
+ Assert.IsTrue(registry.Contains("data:one"));
+ ShrinkModLoader.LoadComposed(_settings, Array.Empty());
+ 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());
+ 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(() => 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(() => ShrinkModLoader.LoadComposed(_settings, new[] { Source("core"), violation }));
+ Assert.That(error.Message, Does.Contain("[2,3)"));
+ Assert.Throws(() => 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();
+ 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(() => 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(); 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();
+ 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(() => 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()));
+ 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(() => 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(() => ShrinkModLoader.LoadComposed(_settings, new[] { a, b, c }));
+ c = Source("c", null, Dep("b", ShrinkModDependencyOrdering.After), Dep("a", ShrinkModDependencyOrdering.Before));
+ Assert.Throws(() => ShrinkModLoader.LoadComposed(_settings, new[] { a, b, c }));
+ Assert.Throws(() => 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(() => 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())
+ .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 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 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(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(); }
+ }
+ }
+}
diff --git a/Tests/ShrinkModCompositionTests.cs.meta b/Tests/ShrinkModCompositionTests.cs.meta
new file mode 100644
index 0000000..c175ae5
--- /dev/null
+++ b/Tests/ShrinkModCompositionTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 44e4b1f576a745fe9c36b173015b98a3
diff --git a/Tests/ShrinkModFramework.Tests.asmdef b/Tests/ShrinkModFramework.Tests.asmdef
index 6f94f0c..7011f62 100644
--- a/Tests/ShrinkModFramework.Tests.asmdef
+++ b/Tests/ShrinkModFramework.Tests.asmdef
@@ -3,6 +3,7 @@
"rootNamespace": "ShrinkModFramework.Tests",
"references": [
"ShrinkModFramework.Runtime",
+ "ShrinkEventBus.Runtime",
"ShrinkContext.Core.Runtime",
"UniTask",
"UnityEngine.TestRunner",
diff --git a/Tools~/HostTests/README.md b/Tools~/HostTests/README.md
new file mode 100644
index 0000000..d87fbfa
--- /dev/null
+++ b/Tools~/HostTests/README.md
@@ -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。
diff --git a/Tools~/HostTests/Runtime/Runtime.csproj b/Tools~/HostTests/Runtime/Runtime.csproj
new file mode 100644
index 0000000..5931c22
--- /dev/null
+++ b/Tools~/HostTests/Runtime/Runtime.csproj
@@ -0,0 +1,13 @@
+
+
+ net8.0ShrinkModFramework.Runtime
+ disablefalse
+
+
+
+
+
+
+
+
+
diff --git a/Tools~/HostTests/Runtime/UnityTestShim.cs b/Tools~/HostTests/Runtime/UnityTestShim.cs
new file mode 100644
index 0000000..1fe089f
--- /dev/null
+++ b/Tools~/HostTests/Runtime/UnityTestShim.cs
@@ -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() where T : ScriptableObject, new() => new T(); }
+ public class MonoBehaviour : Object { public GameObject gameObject; }
+ public class GameObject : Object
+ {
+ internal readonly List Components = new();
+ public GameObject(string name) { }
+ public T AddComponent() where T : MonoBehaviour, new() { var c = new T { gameObject = this }; Components.Add(c); return c; }
+ }
+ public static class Resources { public static T Load(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 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) { } }
+}
diff --git a/Tools~/HostTests/Tests/EditorTestShim.cs b/Tools~/HostTests/Tests/EditorTestShim.cs
new file mode 100644
index 0000000..eb2665e
--- /dev/null
+++ b/Tools~/HostTests/Tests/EditorTestShim.cs
@@ -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();
+ 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 _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");
+ }
+}
diff --git a/Tools~/HostTests/Tests/Tests.csproj b/Tools~/HostTests/Tests/Tests.csproj
new file mode 100644
index 0000000..b331ad7
--- /dev/null
+++ b/Tools~/HostTests/Tests/Tests.csproj
@@ -0,0 +1,13 @@
+
+
+ net8.0ShrinkModFramework.Tests
+ disablefalsefalse
+
+
+
+
+
+
+
+
+
diff --git a/package.json b/package.json
index c6eda84..29e41f5 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "com.cneicy.shrink-mod-framework",
- "version": "0.3.7",
+ "version": "0.3.8",
"displayName": "ShrinkModFramework",
"description": "Unity 模组框架,提供发现、依赖、可逆生命周期、命名空间内容注册与优先级覆盖。",
"unity": "2022.3",