Compare commits
3
Commits
91f0141b86
..
v0.3.8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d15bf00512 | ||
|
|
5398036d3b
|
||
|
|
2ab8482359
|
No files matched your search
@@ -63,7 +63,8 @@ jobs:
|
||||
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 archiveResponse = await fetch(file.url);
|
||||
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()));
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<AssemblyName>ShrinkModFramework.Runtime</AssemblyName>
|
||||
<RootNamespace>ShrinkModFramework</RootNamespace>
|
||||
<PackageId>ShrinkSDK.ModFramework</PackageId>
|
||||
<Version>0.3.6</Version>
|
||||
<Version>0.3.8</Version>
|
||||
<Description>Engine-neutral ShrinkSDK mod contracts and lifecycle.</Description>
|
||||
<Nullable>disable</Nullable>
|
||||
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
|
||||
@@ -16,6 +16,6 @@
|
||||
<Compile Include="..\Runtime\Core\ShrinkModBase.cs" />
|
||||
<Compile Include="..\Runtime\Core\ShrinkModHandle.cs" />
|
||||
<Compile Include="..\Runtime\Metadata\*.cs" />
|
||||
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.1.0" />
|
||||
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.2.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -4,12 +4,12 @@
|
||||
<AssemblyName>ShrinkModFramework.Godot</AssemblyName>
|
||||
<RootNamespace>ShrinkModFramework.Godot</RootNamespace>
|
||||
<PackageId>ShrinkSDK.ModFramework.Godot</PackageId>
|
||||
<Version>0.1.5</Version>
|
||||
<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.1.5" />
|
||||
<PackageReference Include="ShrinkSDK.Godot" Version="0.2.1" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -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<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,本次仅更新它对共享包的发布引用。
|
||||
|
||||
## 配置文件
|
||||
|
||||
菜单 `ShrinkSDK/模组/创建设置` 会在
|
||||
@@ -678,9 +786,9 @@ public sealed partial class DemoFullMod : ShrinkModBase
|
||||
|
||||
## 设计约束
|
||||
|
||||
- 一个模组类必须有 `[ShrinkMod]`
|
||||
- 自动发现的模组类必须有 `[ShrinkMod]`;宿主组合使用显式元数据和工厂
|
||||
- 一个模组类必须实现 `IShrinkMod`
|
||||
- 一个模组类必须能被无参构造
|
||||
- 自动发现的模组类必须能被无参构造;宿主工厂可自行构造包装器
|
||||
- 模组 ID 必须全局唯一
|
||||
- 必选依赖缺失或版本不满足时,装载直接失败
|
||||
- 检测到循环依赖时,装载直接失败
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -10,9 +10,29 @@ namespace ShrinkModFramework
|
||||
/// 把工程内程序集和外部 DLL 的当前 revision 投影为延迟组件源。
|
||||
/// 同一路径的旧外部程序集无法从 Mono AppDomain 卸载,但不会再进入候选集合。
|
||||
/// </summary>
|
||||
internal static class ShrinkModComponentDiscovery
|
||||
public static class ShrinkModComponentDiscovery
|
||||
{
|
||||
public static IReadOnlyList<ShrinkModComponentSource> Discover(
|
||||
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)
|
||||
{
|
||||
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)
|
||||
@@ -53,7 +73,7 @@ namespace ShrinkModFramework
|
||||
var dependencies = type
|
||||
.GetCustomAttributes<ShrinkModDependencyAttribute>(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,
|
||||
|
||||
@@ -2,9 +2,15 @@ using System;
|
||||
|
||||
namespace ShrinkModFramework
|
||||
{
|
||||
/// <summary>宿主包装器执行生命周期;Handle 和自动订阅使用 PublicInstance。数据包可返回 null。</summary>
|
||||
public interface IShrinkModWrapper : IShrinkMod
|
||||
{
|
||||
IShrinkMod PublicInstance { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 延迟模组组件源。Revision 是来源内容的稳定指纹(外部 DLL 可使用文件哈希);
|
||||
/// 同一 ModId 的 revision/factory 变化由 ShrinkModContextHost 作为替换事务处理。
|
||||
/// 同一 ModId 的 revision/metadata 变化由 ShrinkModContextHost 作为替换事务处理。
|
||||
/// </summary>
|
||||
public sealed class ShrinkModComponentSource
|
||||
{
|
||||
@@ -23,5 +29,27 @@ namespace ShrinkModFramework
|
||||
public ShrinkModInfo Info { get; }
|
||||
public string Revision { 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 int _catalogGeneration;
|
||||
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)
|
||||
{
|
||||
@@ -64,7 +68,9 @@ namespace ShrinkModFramework
|
||||
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)
|
||||
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<ShrinkLoaderEntry> BuildEntries(IEnumerable<ShrinkModComponentSource> sources)
|
||||
{
|
||||
_buildingSources = sources.ToArray();
|
||||
var entries = new List<ShrinkLoaderEntry>();
|
||||
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<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;
|
||||
return ShrinkModDependencyGraph.Order(sources.Select(source => source.Info))
|
||||
.Select(info => map[info.ModId]).ToList();
|
||||
}
|
||||
|
||||
private List<ShrinkModComponentSource> ReuseUnchangedSources(
|
||||
IEnumerable<ShrinkModComponentSource> desired)
|
||||
{
|
||||
var desiredArray = desired.ToArray();
|
||||
var currentById = _currentSources.ToDictionary(source => source.Info.ModId, StringComparer.Ordinal);
|
||||
var normalized = new List<ShrinkModComponentSource>();
|
||||
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<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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,9 +37,9 @@ namespace ShrinkModFramework
|
||||
try
|
||||
{
|
||||
var authorizedPaths = authorizedDllPaths?.ToArray() ?? Array.Empty<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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) =>
|
||||
Host.GetOrCreateRegistry<T>(name);
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>绑定生成的实例订阅。调用方须 Dispose 返回值,或通过 context.EffectInverse 登记释放。</summary>
|
||||
public static IDisposable TryAttachEventBusInstance(Type modType, object modInstance,
|
||||
string modId, bool verboseLogging)
|
||||
{
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -19,6 +19,24 @@ namespace ShrinkModFramework
|
||||
private static readonly List<ShrinkModHandle> LoadSequence = 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 IReadOnlyDictionary<string, ShrinkModHandle> Mods =>
|
||||
@@ -48,6 +66,7 @@ namespace ShrinkModFramework
|
||||
ShrinkModFrameworkSettings settings,
|
||||
IEnumerable<string> 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<string, ShrinkModHandle> 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<string>();
|
||||
_hostComposed = false;
|
||||
AssemblyResolvePolicy = null;
|
||||
}
|
||||
|
||||
internal static void ResetForDomainReload()
|
||||
@@ -189,6 +211,8 @@ namespace ShrinkModFramework
|
||||
ShrinkExternalModAssemblyLoader.ResetForDomainReload();
|
||||
ShrinkHarmonyPatchService.ResetForTesting();
|
||||
_authorizedDllPaths = Array.Empty<string>();
|
||||
_hostComposed = false;
|
||||
AssemblyResolvePolicy = null;
|
||||
}
|
||||
|
||||
private static IReadOnlyDictionary<string, ShrinkModHandle> ApplyContextComposition(
|
||||
@@ -204,6 +228,13 @@ namespace ShrinkModFramework
|
||||
.ApplyDiscoveredAsync(settings, authorizedDllPaths)
|
||||
.GetAwaiter()
|
||||
.GetResult();
|
||||
PublishReady(result, previousGenerations);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void PublishReady(IReadOnlyDictionary<string, ShrinkModHandle> result,
|
||||
IReadOnlyDictionary<string, long> 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<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();
|
||||
|
||||
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<DiscoveredMod> ResolveLoadOrder(List<DiscoveredMod> discovered, bool allowExistingLoadedDependencies)
|
||||
{
|
||||
var map = discovered.ToDictionary(x => x.Info.ModId, x => x, StringComparer.Ordinal);
|
||||
var result = new List<DiscoveredMod>();
|
||||
var visiting = new HashSet<string>(StringComparer.Ordinal);
|
||||
var visited = new HashSet<string>(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<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);
|
||||
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)
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
EntryType = entryType;
|
||||
AutoApplyHarmonyPatches = autoApplyHarmonyPatches;
|
||||
Dependencies = dependencies;
|
||||
Dependencies = dependencies == null
|
||||
? Array.Empty<ShrinkModDependency>()
|
||||
: new List<ShrinkModDependency>(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" : "")})";
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -3,6 +3,7 @@
|
||||
"rootNamespace": "ShrinkModFramework.Tests",
|
||||
"references": [
|
||||
"ShrinkModFramework.Runtime",
|
||||
"ShrinkEventBus.Runtime",
|
||||
"ShrinkContext.Core.Runtime",
|
||||
"UniTask",
|
||||
"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",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.8",
|
||||
"displayName": "ShrinkModFramework",
|
||||
"description": "Unity 模组框架,提供发现、依赖、可逆生命周期、命名空间内容注册与优先级覆盖。",
|
||||
"unity": "2022.3",
|
||||
"dependencies": {
|
||||
"com.unity.nuget.newtonsoft-json": "3.2.2",
|
||||
"com.cneicy.shrink-context-core": "0.3.0",
|
||||
"com.cneicy.shrink-eventbus": "2.2.2",
|
||||
"com.cneicy.shrink-context-core": "0.3.1",
|
||||
"com.cneicy.shrink-eventbus": "2.3.1",
|
||||
"com.cysharp.unitask": "2.5.10"
|
||||
},
|
||||
"keywords": [
|
||||
|
||||
Reference in new issue
Block a user