21 Commits
Author SHA1 Message Date
cneicy d15bf00512 feat: 公开宿主组合加载 API、Forge 风格依赖版本区间与加载顺序、程序集解析策略
Publish UPM package / publish (push) Successful in 3s
Publish NuGet packages / publish (push) Successful in 2m18s
- ShrinkModComponentDiscovery.Discover 公开:只发现、不执行生命周期
- ShrinkModLoader.LoadComposed / ShrinkModCordisRuntime.ApplyComposedAsync:宿主提供元数据组合加载,支持纯数据包与 IShrinkModWrapper 公开真实实例
- 公开 TryAttachEventBusInstance,随生命周期逆操作释放
- 依赖新增 VersionRange(Maven/Forge 区间语法)与 Ordering(Before/After)
- AssemblyResolvePolicy 可限制跨模组程序集解析
2026-11-10 07:39:22 +08:00
cneicy 5398036d3b fix: download release SDK directly from Microsoft Blob
Publish NuGet packages / publish (push) Canceled after 1s
Publish UPM package / publish (push) Successful in 2s
2026-11-06 19:26:45 +08:00
cneicy 2ab8482359 feat: update Godot integration and coordinated package dependencies 2026-11-06 19:13:20 +08:00
cneicy 91f0141b86 chore: align SDK dependencies and document reusable capabilities
Publish UPM package / publish (push) Successful in 2s
Publish NuGet packages / publish (push) Successful in 3m38s
2026-09-29 10:14:46 +08:00
cneicy af76458da0 chore: exclude .NET metadata from UPM packages
Publish UPM package / publish (push) Successful in 2s
Publish NuGet packages / publish (push) Successful in 37s
2026-09-05 04:07:23 +08:00
cneicy 81f57566a7 ci: trust bundled CAs during NuGet publish 2026-09-05 04:05:03 +08:00
cneicy adffc1efeb ci: provide OpenSSL for .NET packaging 2026-09-05 04:01:36 +08:00
cneicy 4c7adcb58a ci: run .NET packaging in invariant mode 2026-09-05 03:57:16 +08:00
cneicy 1fec94cda8 ci: bootstrap .NET SDK without system packages 2026-09-05 03:54:54 +08:00
cneicy c3a42b935e ci: publish NuGet without external actions 2026-09-05 03:49:55 +08:00
cneicy 3f7604d4c8 ci: install .NET prerequisites for package publishing 2026-09-05 03:45:30 +08:00
cneicy 2c48d247b8 feat: add NuGet and Godot distribution 2026-09-05 03:41:41 +08:00
cneicy fea6ec56fc feat: add cross-engine runtime support 2026-09-05 02:34:01 +08:00
cneicy 9755e18087 chore: release 0.2.4
Publish UPM package / publish (push) Successful in 3s
2026-08-28 04:31:04 +08:00
cneicy f6688ce573 feat(security): 仅加载显式授权的外部 DLL
Publish UPM package / publish (push) Successful in 2s
2026-08-28 03:44:10 +08:00
cneicy 39f6f97707 chore(editor): localize mod framework menus
Publish UPM package / publish (push) Successful in 2s
2026-08-26 12:48:32 +08:00
cneicy 95446018c3 test(host): allow Unity test runner completion 2026-08-26 08:23:06 +08:00
cneicy e91db64d76 ci: mirror Git package dependencies 2026-08-26 07:07:04 +08:00
cneicy a5a7f3329f test: enable standalone host discovery 2026-08-26 06:56:06 +08:00
cneicy e793a0a742 ci: stabilize standalone Unity host 2026-08-26 06:36:36 +08:00
ShrinkSDK Automation 5e9f501c26 ci: fetch immutable release archive 2026-08-26 04:29:39 +08:00
50 changed files with 1659 additions and 236 deletions

No files matched your search

+124
View File
@@ -0,0 +1,124 @@
name: Publish NuGet packages
on:
push:
tags:
- 'v*'
workflow_dispatch:
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
env:
NUGET_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: '1'
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
LD_LIBRARY_PATH: /opt/dotnet-libs/usr/lib/x86_64-linux-gnu
SSL_CERT_FILE: /opt/ca-certificates.crt
steps:
- name: Fetch exact tagged source
env:
GITEA_REF: ${{ gitea.ref }}
GITEA_REPOSITORY: ${{ gitea.repository }}
shell: bash
run: |
set -euo pipefail
tag="${GITEA_REF#refs/tags/}"
case "$tag" in
v[0-9]*) ;;
*) echo "Expected a version tag ref, got: $GITEA_REF" >&2; exit 1 ;;
esac
export SHRINKSDK_ARCHIVE_URL="https://git.crash.work/${GITEA_REPOSITORY}/archive/${tag}.tar.gz"
node --input-type=module <<'NODE'
import { writeFile } from 'node:fs/promises';
const response = await fetch(process.env.SHRINKSDK_ARCHIVE_URL);
if (!response.ok) {
throw new Error(`Release archive download failed: ${response.status} ${response.statusText}`);
}
await writeFile('release.tar.gz', new Uint8Array(await response.arrayBuffer()));
NODE
mkdir release
tar -xzf release.tar.gz --strip-components=1 -C release
rm -f release.tar.gz
printf '%s' "$tag" > release/.shrink-sdk-release-tag
- name: Install .NET 8 SDK
shell: bash
run: |
set -euo pipefail
node --input-type=module <<'NODE'
import { writeFile } from 'node:fs/promises';
import { rootCertificates } from 'node:tls';
await writeFile('/opt/ca-certificates.crt', rootCertificates.join('\n'));
const metadataResponse = await fetch('https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/8.0/releases.json');
if (!metadataResponse.ok) throw new Error(`Release metadata download failed: ${metadataResponse.status}`);
const metadata = await metadataResponse.json();
const sdkVersion = metadata['latest-sdk'];
const release = metadata.releases.find(item => item.sdk?.version === sdkVersion);
const file = release?.sdk?.files?.find(item => item.rid === 'linux-x64' && item.name.endsWith('.tar.gz'));
if (!file) throw new Error(`Linux x64 SDK archive not found for ${sdkVersion}`);
const archiveUrl = `https://dotnetcli.blob.core.windows.net/dotnet/Sdk/${sdkVersion}/dotnet-sdk-${sdkVersion}-linux-x64.tar.gz`;
const archiveResponse = await fetch(archiveUrl);
if (!archiveResponse.ok) throw new Error(`SDK download failed: ${archiveResponse.status}`);
await writeFile('/tmp/dotnet-sdk.tar.gz', new Uint8Array(await archiveResponse.arrayBuffer()));
const poolUrl = 'https://deb.debian.org/debian-security/pool/updates/main/o/openssl/';
const poolResponse = await fetch(poolUrl);
if (!poolResponse.ok) throw new Error(`OpenSSL package index download failed: ${poolResponse.status}`);
const poolIndex = await poolResponse.text();
const packages = [...poolIndex.matchAll(/href="(libssl3_[^"]+_amd64\.deb)"/g)].map(match => match[1]).sort();
const packageName = packages.at(-1);
if (!packageName) throw new Error('Debian libssl3 package was not found');
const packageResponse = await fetch(poolUrl + packageName);
if (!packageResponse.ok) throw new Error(`OpenSSL package download failed: ${packageResponse.status}`);
await writeFile('/tmp/libssl3.deb', new Uint8Array(await packageResponse.arrayBuffer()));
NODE
mkdir -p /opt/dotnet
tar -xzf /tmp/dotnet-sdk.tar.gz -C /opt/dotnet
mkdir -p /opt/dotnet-libs
dpkg-deb -x /tmp/libssl3.deb /opt/dotnet-libs
rm -f /tmp/dotnet-sdk.tar.gz
rm -f /tmp/libssl3.deb
/opt/dotnet/dotnet --info
- name: Validate, pack and publish
shell: bash
run: |
set -euo pipefail
: "${NUGET_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
export PATH="/opt/dotnet:$PATH"
cd release
tag="$(cat .shrink-sdk-release-tag)"
projects=()
if [[ -d DotNet~ ]]; then
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find DotNet~ -type f -name '*.csproj' -print0)
fi
if [[ -d Godot~ ]]; then
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find Godot~ -type f -name '*.csproj' -print0)
fi
if [[ "${#projects[@]}" -eq 0 ]]; then
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find . -maxdepth 1 -type f -name '*.csproj' -print0)
fi
test "${#projects[@]}" -gt 0
if [[ -f package.json ]]; then
version="$(node -p "require('./package.json').version")"
else
version="$(dotnet msbuild "${projects[0]}" -getProperty:Version -nologo)"
fi
test "$tag" = "v$version"
mkdir -p packages
for project in "${projects[@]}"; do
dotnet restore "$project" --configfile NuGet.Config
dotnet pack "$project" --configuration Release --no-restore --output "$PWD/packages" --include-symbols --include-source
done
find packages -maxdepth 1 -name '*.nupkg' -type f | grep -q .
dotnet nuget push 'packages/*.nupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
if compgen -G 'packages/*.snupkg' > /dev/null; then
dotnet nuget push 'packages/*.snupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
fi
+25 -17
View File
@@ -15,32 +15,39 @@ jobs:
env:
NODE_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
steps:
- name: Install Git
- name: Fetch exact tagged release archive
env:
GITEA_REF: ${{ gitea.ref }}
shell: bash
run: |
set -eu
if ! command -v git >/dev/null 2>&1; then
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends git ca-certificates
rm -rf /var/lib/apt/lists/*
fi
tag="${GITEA_REF#refs/tags/}"
case "$tag" in
v[0-9]*) ;;
*) echo "Expected a version tag ref, got: $GITEA_REF" >&2; exit 1 ;;
esac
export SHRINKSDK_ARCHIVE_URL="https://git.crash.work/ShrinkSDK/ShrinkModFramework/archive/${tag}.tar.gz"
node --input-type=module <<'NODE'
import { writeFile } from 'node:fs/promises';
- name: Fetch tagged revision
shell: bash
run: |
set -eu
ref="${{ gitea.sha }}"
test -n "$ref"
git init .
git remote add origin "https://git.crash.work/ShrinkSDK/ShrinkModFramework.git"
git fetch --depth=1 --tags origin "$ref"
git checkout --detach FETCH_HEAD
const response = await fetch(process.env.SHRINKSDK_ARCHIVE_URL);
if (!response.ok) {
throw new Error(`Release archive download failed: ${response.status} ${response.statusText}`);
}
await writeFile('release.tar.gz', new Uint8Array(await response.arrayBuffer()));
NODE
mkdir release
tar -xzf release.tar.gz --strip-components=1 -C release
rm -f release.tar.gz
printf '%s' "$tag" > release/.shrink-sdk-release-tag
- name: Validate immutable release version
shell: bash
run: |
set -eu
tag="$(git describe --exact-match --tags HEAD)"
cd release
tag="$(cat .shrink-sdk-release-tag)"
version="$(node -p "require('./package.json').version")"
test "$tag" = "v$version"
npm pack --dry-run
@@ -50,6 +57,7 @@ jobs:
run: |
set -eu
: "${NODE_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
cd release
npmrc="$HOME/.npmrc"
cleanup() { rm -f "$npmrc"; }
trap cleanup EXIT
+6 -1
View File
@@ -26,12 +26,17 @@ jobs:
shell: bash
run: |
set -eu
machine_id_file="/root/.local/share/unity3d/Unity/.machine-id"
if test -s "$machine_id_file"; then
cat "$machine_id_file" > /etc/machine-id
echo "Unity machine identity restored"
fi
git config --global url."https://ghfast.top/https://github.com/".insteadOf "https://github.com/"
unity_bin="$(command -v unity-editor || command -v unity || command -v Unity || true)"
test -n "$unity_bin"
"$unity_bin" \
-batchmode \
-nographics \
-quit \
-projectPath "$PWD/Development~/UnityProject" \
-runTests \
-testPlatform EditMode \
+8
View File
@@ -8,3 +8,11 @@
/Tools~/**/[Oo]bj/
*.user
*.DotSettings.user
/DotNet~/**/[Bb]in/
/DotNet~/**/[Oo]bj/
/Godot~/**/[Bb]in/
/Godot~/**/[Oo]bj/
/artifacts/
/packages/
!DotNet~/**/*.csproj
!Godot~/**/*.csproj
+6
View File
@@ -6,3 +6,9 @@ Tools~/
*.sln
*.user
*.DotSettings.user
DotNet~/
Godot~/
NuGet.Config
Directory.Build.props
NuGet.Config.meta
Directory.Build.props.meta
+41
View File
@@ -2,6 +2,47 @@
本文件记录 `ShrinkModFramework` 在当前工作区中的包内变更。
## [0.3.8] - 2026-11-10
### Added
- 公开 `ShrinkModComponentDiscovery.Discover`,从显式授权 DLL 列表生成延迟组件源,保留 SHA-256 revision;发现不运行生命周期或提交当前 revision。
- 新增 `ShrinkModLoader.LoadComposed` 与 `ShrinkModCordisRuntime.ApplyComposedAsync`,复用 ContextHost 可逆生命周期、依赖排序、热替换和失败恢复。
- 新增源的 `WithMetadata` / `CreateDataOnly` 和 `IShrinkModWrapper.PublicInstance`,支持清单依赖、无入口数据包及真实实例句柄。
- 公开 `TryAttachEventBusInstance`;组合加载自动绑定公开实例,失败、替换及卸载时释放。
- 依赖支持 Maven 风格版本区间、并集及 None/Before/After 排序;保留 minimumVersion 和原三参数构造函数。
- 新增 `AssemblyResolvePolicy`,按请求程序集、请求名称和授权候选路径限制解析。
- 新增宿主组合回归测试与 `Tools~/HostTests` 独立 .NET harness。
### Changed
- 清单元数据或排序前驱变化会重新协调对应组件;宿主组合由宿主重新提交,内置 watcher 不覆盖清单。
- 恢复旧组件前先恢复程序集解析 revision,保证回滚实例使用旧解析集合。
- UPM 与共享 NuGet 升级至 0.3.8;Godot 适配 NuGet 升至 0.1.7,以发布新的共享依赖引用。
## [0.2.4] - 2026-08-28
### Changed
- 精确依赖 `ShrinkEventBus 2.0.1`。
## [0.2.3] - 2026-08-28
### Added
- 新增 `ShrinkModLoader.LoadAuthorized(settings, authorizedDllPaths)`,只从调用方提交的精确 DLL 白名单加载外部模组。
- 恢复公共入口 `ShrinkModRuntimeBootstrap.InitializeDriver(...)`,供安全启动链显式初始化运行时驱动。
### Changed
- ContextHost 与旧加载路径不再递归扫描外部模组目录;revision 刷新只复用已授权路径。
- `autoLoadOnStartup`、`enableExternalDllMods`、`watchExternalModsDirectory` 默认关闭。
- `ShrinkModFrameworkSettings` 优先从标准 ShrinkSDK 资源目录加载,创建菜单同步写入该目录。
### Fixed
- 授权 DLL 替换失败时继续恢复此前已提交的 SHA-256 revision 与模组组合。
## [0.2.1] - 2026-08-26
- 将 EventBus 生成器源码和 fixture builder 收敛到各自 UPM 包的 `Tools~`,并为独立包导出提供随包分析器回退。
@@ -10,6 +10,10 @@
],
"dependencies": {
"com.unity.test-framework": "1.1.33",
"com.cneicy.shrink-mod-framework": "file:../../.."
}
"com.cneicy.shrink-mod-framework": "file:../../..",
"com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#7c0f199fe0d3fc528024488ccd671e6c7b27745b"
},
"testables": [
"com.cneicy.shrink-mod-framework"
]
}
+13
View File
@@ -0,0 +1,13 @@
<Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<Deterministic>true</Deterministic>
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
<Authors>ShrinkSDK</Authors>
<Company>ShrinkSDK</Company>
<RepositoryUrl>https://git.crash.work/ShrinkSDK</RepositoryUrl>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
</Project>
+7
View File
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5d818c0b172f0114a85be0e1886f5b04
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+25
View File
@@ -0,0 +1,25 @@
#nullable enable
using System;
using System.Collections.Generic;
namespace ShrinkModFramework;
public sealed class ShrinkModContext
{
private readonly Dictionary<Type, object> _services = new();
public ShrinkModContext(string modDirectory) => ModDirectory = modDirectory ?? throw new ArgumentNullException(nameof(modDirectory));
public string ModDirectory { get; }
public void RegisterService<T>(T service) where T : class => _services[typeof(T)] = service ?? throw new ArgumentNullException(nameof(service));
public bool TryGetService<T>(out T? service) where T : class
{
service = _services.TryGetValue(typeof(T), out var value) ? value as T : null;
return service != null;
}
public T GetRequiredService<T>() where T : class => TryGetService<T>(out var value) ? value! : throw new InvalidOperationException($"Service is not registered: {typeof(T).FullName}");
}
public interface IShrinkModUnload
{
void OnUnload(ShrinkModContext context);
}
+21
View File
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<AssemblyName>ShrinkModFramework.Runtime</AssemblyName>
<RootNamespace>ShrinkModFramework</RootNamespace>
<PackageId>ShrinkSDK.ModFramework</PackageId>
<Version>0.3.8</Version>
<Description>Engine-neutral ShrinkSDK mod contracts and lifecycle.</Description>
<Nullable>disable</Nullable>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<Compile Include="Runtime\ShrinkModContext.cs" />
<Compile Include="..\Runtime\Core\IShrinkMod.cs" />
<Compile Include="..\Runtime\Core\ShrinkModBase.cs" />
<Compile Include="..\Runtime\Core\ShrinkModHandle.cs" />
<Compile Include="..\Runtime\Metadata\*.cs" />
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.2.0" />
</ItemGroup>
</Project>
@@ -11,7 +11,7 @@ using UnityEngine;
public static class ShrinkExternalModTemplateGenerator
{
private const string GenerateMenuPath = "ShrinkSDK/Mod/生成外部模组模板";
private const string GenerateMenuPath = "ShrinkSDK/模组/生成外部模板";
private const string TemplateRelativePath = "Assets/Modules/ShrinkModFramework/Editor/Scaffolding/ExternalModProjectTemplate";
private const string DefaultGeneratedModsRelativePath = "GeneratedMods";
private const string TemplateStampFileName = ".shrink-mod-template.json";
@@ -10,7 +10,7 @@ using UnityEngine;
public static class ShrinkInRepoModTemplateGenerator
{
private const string GenerateMenuPath = "ShrinkSDK/Mod/生成仓库内模组模板(推荐)";
private const string GenerateMenuPath = "ShrinkSDK/模组/生成仓库内模板(推荐)";
private const string TemplateRelativePath = "Assets/Modules/ShrinkModFramework/Editor/Scaffolding/InRepoModTemplate";
private const string DefaultOutputRootRelativePath = "Assets/GeneratedMods";
private const string TemplateStampFileName = ".shrink-inrepo-mod-template.json";
+1 -1
View File
@@ -11,7 +11,7 @@ using UnityEngine;
public static class ShrinkModSdkExporter
{
private const string ExportMenuPath = "ShrinkSDK/Mod/导出 Mod SDK 开发包";
private const string ExportMenuPath = "ShrinkSDK/模组/导出开发包";
private const string DefaultOutputRootRelativePath = "GeneratedModSdk";
private const string StampFileName = ".shrink-mod-sdk.json";
private const string TemplateProjectName = "SampleShrinkMod";
+49
View File
@@ -0,0 +1,49 @@
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
namespace ShrinkModFramework.Editor
{
public static class ShrinkModFrameworkSettingsMenu
{
private const string SettingsDirectory =
"Assets/Resources/GameAssets/Runtime/Data/ShrinkSDK";
private const string SettingsAssetPath =
SettingsDirectory + "/ShrinkModFrameworkSettings.asset";
[MenuItem("ShrinkSDK/模组/创建设置")]
public static void CreateSettingsAsset()
{
EnsureFolder(SettingsDirectory);
var existing = AssetDatabase.LoadAssetAtPath<ShrinkModFrameworkSettings>(SettingsAssetPath);
if (existing != null)
{
Selection.activeObject = existing;
EditorGUIUtility.PingObject(existing);
return;
}
var asset = ScriptableObject.CreateInstance<ShrinkModFrameworkSettings>();
AssetDatabase.CreateAsset(asset, SettingsAssetPath);
AssetDatabase.SaveAssets();
Selection.activeObject = asset;
EditorGUIUtility.PingObject(asset);
Debug.Log("[ShrinkModFramework] 已创建 ShrinkModFrameworkSettings.asset");
}
private static void EnsureFolder(string path)
{
var segments = path.Split('/');
var current = segments[0];
for (var i = 1; i < segments.Length; i++)
{
var next = current + "/" + segments[i];
if (!AssetDatabase.IsValidFolder(next))
AssetDatabase.CreateFolder(current, segments[i]);
current = next;
}
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 400ef5e3613144f9b9f248d259b84a22
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+66
View File
@@ -0,0 +1,66 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
namespace ShrinkModFramework.Godot;
public sealed class ShrinkGodotModLoader : IDisposable
{
private sealed record LoadedMod(AssemblyLoadContext LoadContext, WeakReference UnloadReference,
ShrinkModContext Context, IReadOnlyList<IShrinkMod> Instances);
private readonly Dictionary<string, LoadedMod> _loaded = new(StringComparer.OrdinalIgnoreCase);
public IReadOnlyCollection<string> LoadedAssemblyPaths => _loaded.Keys;
public IReadOnlyList<IShrinkMod> Load(string assemblyPath)
{
assemblyPath = Path.GetFullPath(assemblyPath);
if (_loaded.ContainsKey(assemblyPath)) throw new InvalidOperationException($"Mod assembly is already loaded: {assemblyPath}");
var loadContext = new AssemblyLoadContext($"ShrinkMod:{Path.GetFileNameWithoutExtension(assemblyPath)}", true);
loadContext.Resolving += (_, name) => ResolveDependency(loadContext, Path.GetDirectoryName(assemblyPath)!, name);
try
{
var assembly = loadContext.LoadFromAssemblyPath(assemblyPath);
var entries = assembly.GetTypes().Where(type => !type.IsAbstract && typeof(IShrinkMod).IsAssignableFrom(type) &&
type.GetCustomAttribute<ShrinkModAttribute>() != null).OrderBy(type => type.GetCustomAttribute<ShrinkModAttribute>()!.LoadOrder).ToArray();
var context = new ShrinkModContext(Path.GetDirectoryName(assemblyPath)!);
var instances = entries.Select(type => (IShrinkMod)(Activator.CreateInstance(type) ??
throw new InvalidOperationException($"Failed to create mod entry: {type.FullName}"))).ToArray();
foreach (var mod in instances) mod.OnConstruct(context);
foreach (var mod in instances) mod.OnRegisterContent(context);
foreach (var mod in instances) mod.OnInitialize(context);
foreach (var mod in instances) mod.OnReady(context);
_loaded[assemblyPath] = new LoadedMod(loadContext, new WeakReference(loadContext), context, instances);
return instances;
}
catch { loadContext.Unload(); throw; }
}
public bool Unload(string assemblyPath)
{
assemblyPath = Path.GetFullPath(assemblyPath);
if (!_loaded.Remove(assemblyPath, out var loaded)) return false;
for (var index = loaded.Instances.Count - 1; index >= 0; index--)
if (loaded.Instances[index] is IShrinkModUnload unload) unload.OnUnload(loaded.Context);
loaded.LoadContext.Unload();
return true;
}
public void Dispose()
{
foreach (var path in _loaded.Keys.ToArray()) Unload(path);
}
private static Assembly? ResolveDependency(AssemblyLoadContext context, string directory, AssemblyName name)
{
var shared = AssemblyLoadContext.Default.Assemblies.FirstOrDefault(assembly => assembly.GetName().Name == name.Name);
if (shared != null) return shared;
var path = Path.Combine(directory, name.Name + ".dll");
return File.Exists(path) ? context.LoadFromAssemblyPath(path) : null;
}
}
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AssemblyName>ShrinkModFramework.Godot</AssemblyName>
<RootNamespace>ShrinkModFramework.Godot</RootNamespace>
<PackageId>ShrinkSDK.ModFramework.Godot</PackageId>
<Version>0.1.7</Version>
<Description>Collectible AssemblyLoadContext host for ShrinkSDK mods in Godot.</Description>
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DotNet~\ShrinkSDK.ModFramework.csproj" />
<PackageReference Include="ShrinkSDK.Godot" Version="0.2.1" />
</ItemGroup>
</Project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="ShrinkSDK" value="https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json" />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
</packageSources>
</configuration>
+32
View File
@@ -0,0 +1,32 @@
fileFormatVersion: 2
guid: d2250189e7eded943a13c62da92db2d3
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
- first:
Windows Store Apps: WindowsStoreApps
second:
enabled: 1
settings: {}
userData:
assetBundleName:
assetBundleVariant:
+157 -35
View File
@@ -1,13 +1,15 @@
# ShrinkModFramework
一个面向 Unity 的轻量模组框架,目标是给 `Shrink` 系列提供接近 Forge 的核心能力:
一个面向 Unity 与 Godot C# 的轻量模组框架,目标是给 `Shrink` 系列提供接近 Forge 的核心能力:
共享模组合同和加载规则位于 `DotNet~`,Godot `AssemblyLoadContext` 适配与打包工程位于 `Godot~`。Godot 项目安装 `ShrinkSDK.ModFramework.Godot`,会同时取得共享核心包。
- 模组声明
- 模组发现
- 依赖解析
- 生命周期阶段
- 内容注册表
- 自动启动
- 可选显式启动
- 外部 DLL 模组热加载
- Harmony 热补丁接入
- 网络同步通道
@@ -31,17 +33,19 @@
- 内置的资源包系统、命令系统、配方编辑器
- 内置的具体联网实现
## 自动启动
## 启动
现在默认**不需要**把 `ShrinkModBootstrap` 挂到场景里。
框架会通过:
安全默认值不会自动启动或扫描外部 DLL。需要装载工程内模组时,可以显式调用
`ShrinkModLoader.LoadAll(settings)`;需要外部代码模组时,调用方必须先完成自己的清单、
启用状态和哈希校验,再提交精确白名单:
```csharp
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
ShrinkModRuntimeBootstrap.InitializeDriver(settings);
ShrinkModLoader.LoadAuthorized(settings, authorizedDllPaths);
```
自动读取 `ShrinkModFrameworkSettings` 并调用装载流程。
只有显式打开 `autoLoadOnStartup` 时,`AfterAssembliesLoaded` 入口才会装载工程内模组;
该自动入口仍不加载任何未授权外部 DLL。
相关入口:
@@ -50,14 +54,124 @@
`ShrinkModBootstrap` 仍然保留,作为手动覆盖或调试入口,但不是必需品。
## 宿主清单组合(0.3.8)
Unity 宿主可以先发现授权 DLL,再用清单替换元数据和生命周期工厂,最后提交完整组合。
`Discover` 不构造模组、不运行生命周期、不改变已提交的 current revision;DLL 会进入 AppDomain,
外部源的 `Revision` 仍为 `SHA-256:入口类型全名`。工程内源仍按 `assemblyNamePrefixes` 筛选。
```csharp
var discovered = ShrinkModComponentDiscovery.Discover(settings, authorizedDllPaths);
var original = discovered.Single(source => source.Info.ModId == "demo.code");
var info = new ShrinkModInfo("demo.code", "代码包", "1.2.0", 0,
original.Info.EntryType, original.Info.AutoApplyHarmonyPatches,
new[] { new ShrinkModDependency("demo.data", "1.0", optional: false) });
var code = original.WithMetadata(info, original.Revision,
() => new PackageWrapper(original.Factory()));
var dataInfo = new ShrinkModInfo("demo.data", "数据包", "1.0", 0,
entryType: null, autoApplyHarmonyPatches: false,
dependencies: Array.Empty<ShrinkModDependency>());
var data = ShrinkModComponentSource.CreateDataOnly(dataInfo, "manifest-sha256");
ShrinkModLoader.LoadComposed(settings, new[] { code, data });
sealed class PackageWrapper : ShrinkModBase, IShrinkModWrapper
{
public PackageWrapper(IShrinkMod instance) => PublicInstance = instance;
public IShrinkMod PublicInstance { get; }
public override void OnConstruct(ShrinkModContext ctx) => PublicInstance.OnConstruct(ctx);
public override void OnRegisterContent(ShrinkModContext ctx) => PublicInstance.OnRegisterContent(ctx);
public override void OnInitialize(ShrinkModContext ctx) => PublicInstance.OnInitialize(ctx);
public override void OnReady(ShrinkModContext ctx) => PublicInstance.OnReady(ctx);
}
```
包装器可以在各阶段加入宿主作用域、数据注册和 `EffectInverse`。`Handle.Instance` 保持原有
`IShrinkMod` 类型,返回 `IShrinkModWrapper.PublicInstance`,自动 EventBus 绑定也使用这个真实实例。
`CreateDataOnly` 的默认工厂不执行业务,公开实例为 null;传入自定义 `Func<IShrinkMod>` 可处理数据注册。
数据包的 `EntryType` 必须为 null,框架不会尝试为它应用 Harmony 补丁。
`LoadComposed` 始终使用可逆 ContextHost,与 `useContextHost` 的旧 Loader 开关无关。每个模组按
依赖/排序关系执行 Construct → RegisterContent → Initialize → Ready;成功后设置 `IsLoaded`,
对新建或重建的 handle 发送 `OnModReady`,再发送 `OnAllModsReady`。失败恢复旧组合及 DLL revision。
相同 revision、元数据和排序前驱保持幂等;工厂行为或清单数据改变时,宿主应更新 revision。
`WithMetadata` 保留发现快照,修改外部源时应使用它。不要把不同扫描中同一路径的不同 revision 混进一次提交。
热更新时重新发现、重新按清单组合,再调用 `LoadComposed`;删除源即卸载,空列表卸载全部实例。
宿主组合模式下 `LoadNewExternalMods` 保留当前组合,内置 watcher 不会丢弃清单元数据;宿主负责触发重组。
已有 `LoadAuthorized`、普通 ContextHost 和旧 Loader 的入口保持可用,不混用旧 Loader 实例与宿主组合。
高级异步宿主可调用 `ShrinkModCordisRuntime.ApplyComposedAsync(settings, sources)`,它与既有
`ApplyDiscoveredAsync` 一样仅负责根事务;需要 Loader 状态与静态通知时使用 `LoadComposed`。
### 依赖区间和排序
```csharp
[ShrinkModDependency("demo.core", optional: false,
VersionRange = "[1.0,2.0)", Ordering = ShrinkModDependencyOrdering.After)]
[ShrinkModDependency("demo.ui", optional: true,
Ordering = ShrinkModDependencyOrdering.Before)]
public sealed class MyMod : ShrinkModBase { }
var dependency = new ShrinkModDependency("demo.core", minimumVersion: null,
optional: true, ordering: ShrinkModDependencyOrdering.After, versionRange: "[1.2,)");
bool matches = ShrinkModVersionRange.Parse("[1.0,2.0)").Contains("1.5.0");
```
区间支持开闭边界、无上/下界、精确值 `[1.2]` 和并集 `(,1.0],[1.2,)`;裸版本 `1.0`
表示 `>= 1.0`。数字版本的尾部零等价(`1.2 == 1.2.0`),带后缀版本沿用框架版本比较规则,
不承诺 Maven 的全部 qualifier 排序规则。无效区间、范围不满足、必选依赖缺失和排序环均明确报错。
`optional` 只决定目标能否缺席;目标存在时仍检查区间。`None` 不添加先后边,`Before` 让本模组
先于目标,`After` 让目标先于本模组。若只想排序且不要求安装目标,使用 `optional: true`。
原 `minimumVersion` 参数与三参数构造函数保留,未指定排序时仍为 `After`;`VersionRange` 优先于
`MinimumVersion`。旧 Loader 的增量路径无法把新模组插到已运行模组之前,会明确要求改用 ContextHost。
### 按清单约束程序集解析
在发现之前设置策略;宿主把程序集简单名称、授权绝对路径映射回自己的 packageId:
```csharp
ShrinkModLoader.AssemblyResolvePolicy = (requestingAssembly, requestedName, candidatePath) =>
{
if (requestingAssembly == null) return false;
if (!assemblyOwners.TryGetValue(requestingAssembly.GetName().Name, out var requesterId)) return false;
if (!pathOwners.TryGetValue(candidatePath, out var candidateId)) return false;
return requesterId == candidateId || declaredDependencies[requesterId].Contains(candidateId);
};
```
`assemblyOwners`、`pathOwners` 和 `declaredDependencies` 由宿主清单建立。回调在返回缓存候选或加载
候选字节前执行,返回 false 拒绝本次解析;候选始终来自授权白名单,策略不能扩大白名单。
未设置策略时保持原行为。入口 DLL 文件名应与程序集简单名称一致。策略仅约束框架的
`AssemblyResolve` 回调,不能拦截 CLR 已解析的程序集引用,也不是不可信代码沙箱。
### 显式绑定生成订阅
宿主组合在 RegisterContent 后自动为公开实例调用以下入口,并将 Dispose 登记为可逆效应;
Initialize/Ready 失败、替换或卸载都会退订。自动路径不需要包装器再手动绑定同一个实例。
如果需要手动绑定其它订阅对象:
```csharp
var binding = ShrinkModOptionalRuntimeIntegration.TryAttachEventBusInstance(
subscriber.GetType(), subscriber, context.ModInfo.ModId, verboseLogging: false);
if (binding != null) context.EffectInverse(binding.Dispose);
```
返回值为 `IDisposable`;没有生成合同或可选绑定失败时返回 null。它使用 `ShrinkBusKey.Mod(modId)`,
不会反射枚举订阅方法。手动调用方负责释放;ContextHost 自动路径还会在退役时移除对应 Mod Bus。
共享 NuGet `ShrinkSDK.ModFramework` 0.3.8 包含依赖元数据和范围解析;上述 Unity 发现/ContextHost API
属于 UPM Runtime。Godot 适配包独立版本为 0.1.7,本次仅更新它对共享包的发布引用。
## 配置文件
创建 `ShrinkModFrameworkSettings` 资产后,框架会自动查找它。
菜单 `ShrinkSDK/模组/创建设置` 会在
`Assets/Resources/GameAssets/Runtime/Data/ShrinkSDK/ShrinkModFrameworkSettings.asset`
创建配置。运行时优先加载该路径,并保留旧根路径回退。
关键配置包括:
- `autoLoadOnStartup`
- 是否在启动时自动装载模组
- 是否在启动时自动装载工程内模组,默认关闭
- `useContextHost`
- 默认开启:把模组四阶段放进 `ShrinkModContextHost`,替换失败恢复旧组件源;关闭后回退旧 Loader
- `verboseLogging`
@@ -65,11 +179,11 @@
- `assemblyNamePrefixes`
- 只扫描指定前缀的程序集
- `enableExternalDllMods`
- 是否启用外部 DLL 模组
- 是否允许显式白名单中的外部 DLL 模组,默认关闭
- `externalModsFolderName`
- 外部模组目录名,默认 `Mods`
- `watchExternalModsDirectory`
- 是否自动监听目录变化并协调外部 DLL revision 变化
- 是否监听文件变化并重新提交既有白名单,默认关闭;监听不会扩大授权范围
- `externalModsReloadDelaySeconds`
- 文件变更后延迟多少秒再尝试热加载
- `externalAssemblyRevisionSoftLimit`
@@ -182,13 +296,8 @@ public class DemoSafeMod : ShrinkModBase
## 外部 DLL 模组热加载
框架会扫描:
`Application.persistentDataPath/<externalModsFolderName>`
默认就是:
`Application.persistentDataPath/Mods`
框架不会递归扫描模组目录。调用方必须把每个允许进入 AppDomain 的入口 DLL 绝对路径
作为白名单提交给 `LoadAuthorized`;目录中未列出的 DLL 不会被读取或加载。
ContextLoader 装载规则:
@@ -199,16 +308,19 @@ ContextLoader 装载规则:
- 不支持 IL2CPP Player 动态程序集加载
- 支持同目录依赖程序集解析
你可以在运行时调用:
首次安全加载:
```csharp
ShrinkModLoader.LoadNewExternalMods();
ShrinkModRuntimeBootstrap.InitializeDriver(settings);
ShrinkModLoader.LoadAuthorized(settings, authorizedDllPaths);
```
默认会扫描当前 DLL revision,并把新增、替换、删除映射为一个完整期望组合;
变更事务失败时保留旧模组组合。设置 `useContextHost = false` 才回退为仅新增 DLL 的旧路径。
后续可调用 `ShrinkModLoader.LoadNewExternalMods(settings)` 重新读取同一白名单的 revision,
把新增、替换、删除映射为完整期望组合;变更事务失败时保留旧模组组合。设置
`useContextHost = false` 时,旧路径同样只读取显式白名单,但仍保持只增不减的兼容语义。
如果 `watchExternalModsDirectory = true`,框架还会监听新增、修改、删除、重命名事件,经过主线程 debouncer 后提交一次完整组合;同一 burst 内的中间坏文件不会覆盖当前有效 revision。
如果 `watchExternalModsDirectory = true`,框架会监听目录变化并在主线程 debouncer 后重新提交
既有白名单;未授权文件即使触发通知也不会被加载。同一 burst 内的中间坏文件不会覆盖当前有效 revision。
### 常驻 revision 诊断
@@ -220,7 +332,7 @@ var snapshot = ShrinkModDiagnostics.CaptureExternalAssemblies(settings);
快照包含当前与历史 revision、来源路径、程序集名、SHA-256 revision、载入字节数、常驻数量和软阈值状态。失败 revision 可以成为已载入的历史程序集,但不会成为 current;达到软阈值只告警,不伪造卸载行为。
导入 `ShrinkContext.AppAdapter` 的 Editor 工具后,也可以从 `ShrinkSDK/Cordis/诊断与组合` 查看同一份常驻快照;该窗口通过可选反射读取,不会让 AppAdapter 对 ModFramework 建立硬依赖。
导入 `ShrinkContext.AppAdapter` 的 Editor 工具后,也可以从 `ShrinkSDK/上下文/诊断与组合` 查看同一份常驻快照;该窗口通过可选反射读取,不会让 AppAdapter 对 ModFramework 建立硬依赖。
## Harmony 热补丁
@@ -574,9 +686,9 @@ public sealed partial class DemoFullMod : ShrinkModBase
现在已经提供和 `ShrinkNetwork` 独立服务器生成器同风格的模组开发入口:
- 菜单:`ShrinkSDK/Mod/导出 Mod SDK 开发包`
- 菜单:`ShrinkSDK/Mod/生成仓库内模组模板(推荐)`
- 菜单:`ShrinkSDK/Mod/生成外部模组模板`
- 菜单:`ShrinkSDK/模组/导出开发包`
- 菜单:`ShrinkSDK/模组/生成仓库内模板(推荐)`
- 菜单:`ShrinkSDK/模组/生成外部模板`
更推荐优先用“仓库内模组模板”:
@@ -599,7 +711,7 @@ public sealed partial class DemoFullMod : ShrinkModBase
如果目标是给**外部模组开发者**发 SDK,当前更推荐直接用:
- `ShrinkSDK/Mod/导出 Mod SDK 开发包`
- `ShrinkSDK/模组/导出开发包`
它会导出:
@@ -661,10 +773,10 @@ public sealed partial class DemoFullMod : ShrinkModBase
建议流程:
1. 你自己在当前仓库开发时,优先用 `ShrinkSDK/Mod/生成仓库内模组模板(推荐)`
1. 你自己在当前仓库开发时,优先用 `ShrinkSDK/模组/生成仓库内模板(推荐)`
2. 先改 `modId`、命名空间、命令路径、`opcode`
3. 在当前 Unity/IDE 里直接开发和编译
4. 如果要发给外部模组开发者,改用 `ShrinkSDK/Mod/导出 Mod SDK 开发包`
4. 如果要发给外部模组开发者,改用 `ShrinkSDK/模组/导出开发包`
如果你已经知道目标 `Mods` 目录,也可以直接跑模板里的:
@@ -674,9 +786,9 @@ public sealed partial class DemoFullMod : ShrinkModBase
## 设计约束
- 一个模组类必须有 `[ShrinkMod]`
- 自动发现的模组类必须有 `[ShrinkMod]`;宿主组合使用显式元数据和工厂
- 一个模组类必须实现 `IShrinkMod`
- 一个模组类必须能被无参构造
- 自动发现的模组类必须能被无参构造;宿主工厂可自行构造包装器
- 模组 ID 必须全局唯一
- 必选依赖缺失或版本不满足时,装载直接失败
- 检测到循环依赖时,装载直接失败
@@ -697,8 +809,8 @@ public sealed partial class DemoFullMod : ShrinkModBase
现在这套框架已经从“只能在工程内静态发现模组”的骨架,升级成了:
- 自动启动
- 可增量接入外部 DLL
- 可显式托管启动
- 可按精确白名单增量接入外部 DLL
- 可选 Harmony 补丁
- 可扩展的网络同步框架
@@ -708,3 +820,13 @@ public sealed partial class DemoFullMod : ShrinkModBase
- 模组资源系统
- 模组命令系统
- 模组专属存档与同步策略
## 可复用能力
<!-- shrink:capabilities -->
Capability: 模组发现、依赖、阶段生命周期、内容注册和外部程序集加载
Aliases: mod 插件 模组 模组退役 热加载 内容注册
Limits: 动态程序集不能假定全部卸载;宿主加载上下文须单独验证;不默认 NativeAOT
Extension: 模组声明、阶段钩子与宿主加载接口
Evidence: [ShrinkModContextHost](Runtime/Context/ShrinkModContextHost.cs)
<!-- /shrink:capabilities -->
+1 -1
View File
@@ -9,7 +9,7 @@ namespace ShrinkModFramework
[SerializeField] private ShrinkModFrameworkSettings settingsOverride;
[Header("Bootstrap")]
[SerializeField] private bool autoLoadOnAwake = true;
[SerializeField] private bool autoLoadOnAwake;
private static bool _bootstrapped;
@@ -2,9 +2,13 @@ using UnityEngine;
namespace ShrinkModFramework
{
[CreateAssetMenu(fileName = "ShrinkModFrameworkSettings", menuName = "ShrinkModFramework/Settings")]
[CreateAssetMenu(fileName = "ShrinkModFrameworkSettings", menuName = "ShrinkSDK/模组/模组设置")]
public class ShrinkModFrameworkSettings : ScriptableObject
{
public const string PreferredResourcesPath =
"GameAssets/Runtime/Data/ShrinkSDK/ShrinkModFrameworkSettings";
public const string LegacyResourcesPath = "ShrinkModFrameworkSettings";
private static ShrinkModFrameworkSettings _instance;
public static ShrinkModFrameworkSettings Instance
@@ -13,7 +17,9 @@ namespace ShrinkModFramework
{
if (_instance) return _instance;
_instance = Resources.Load<ShrinkModFrameworkSettings>("ShrinkModFrameworkSettings");
_instance = Resources.Load<ShrinkModFrameworkSettings>(PreferredResourcesPath);
if (!_instance)
_instance = Resources.Load<ShrinkModFrameworkSettings>(LegacyResourcesPath);
#if UNITY_EDITOR
if (!_instance)
@@ -39,8 +45,13 @@ namespace ShrinkModFramework
internal set => _instance = value;
}
internal static void ResetCachedInstance()
{
_instance = null;
}
[Header("Bootstrap")]
public bool autoLoadOnStartup = true;
public bool autoLoadOnStartup;
[Tooltip("使用 ShrinkContextHost 协调模组组件;关闭时回退到旧的只增不减 ShrinkModLoader。")]
public bool useContextHost = true;
@@ -51,10 +62,10 @@ namespace ShrinkModFramework
public string[] assemblyNamePrefixes = new string[0];
[Header("External Mods")]
public bool enableExternalDllMods = true;
public bool enableExternalDllMods;
public bool autoCreateExternalModsDirectory = true;
public string externalModsFolderName = "Mods";
public bool watchExternalModsDirectory = true;
public bool watchExternalModsDirectory;
public float externalModsReloadDelaySeconds = 0.5f;
[Min(1)]
[Tooltip("Mono 下外部程序集 revision 会常驻;历史数量达到该软阈值后提示 Domain Reload/重启。")]
+11 -2
View File
@@ -4,6 +4,15 @@ namespace ShrinkModFramework
{
public static class ShrinkModRuntimeBootstrap
{
/// <summary>
/// 显式创建或更新模组运行时驱动。安全启动链可先调用此入口,再调用
/// ShrinkModLoader.LoadAuthorized 提交已校验的 DLL 白名单。
/// </summary>
public static void InitializeDriver(ShrinkModFrameworkSettings settings = null)
{
ShrinkModRuntimeDriver.EnsureCreated(settings ?? ShrinkModFrameworkSettings.Instance);
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
private static void ResetStaticStateForPlayMode()
{
@@ -15,11 +24,11 @@ namespace ShrinkModFramework
private static void AutoLoad()
{
var settings = ShrinkModFrameworkSettings.Instance;
ShrinkModRuntimeDriver.EnsureCreated(settings);
if (settings && !settings.autoLoadOnStartup)
return;
InitializeDriver(settings);
try
{
ShrinkModLoader.LoadAll(settings);
+5 -5
View File
@@ -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();
+28 -5
View File
@@ -10,12 +10,35 @@ namespace ShrinkModFramework
/// 把工程内程序集和外部 DLL 的当前 revision 投影为延迟组件源。
/// 同一路径的旧外部程序集无法从 Mono AppDomain 卸载,但不会再进入候选集合。
/// </summary>
internal static class ShrinkModComponentDiscovery
public static class ShrinkModComponentDiscovery
{
public static IReadOnlyList<ShrinkModComponentSource> Discover(ShrinkModFrameworkSettings settings,
bool verboseLogging)
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)
{
ShrinkExternalModAssemblyLoader.ScanExternalAssemblyRevisions(settings, verboseLogging);
if (authorizedDllPaths == null) throw new ArgumentNullException(nameof(authorizedDllPaths));
var previous = ShrinkExternalModAssemblyLoader.CaptureState();
try
{
var sources = DiscoverCurrent(settings, verboseLogging, authorizedDllPaths);
var state = ShrinkExternalModAssemblyLoader.CaptureState();
foreach (var source in sources) source.DiscoveryState = state;
return sources;
}
finally { ShrinkExternalModAssemblyLoader.RestoreState(previous); }
}
internal static IReadOnlyList<ShrinkModComponentSource> DiscoverCurrent(
ShrinkModFrameworkSettings settings,
bool verboseLogging,
IEnumerable<string> authorizedDllPaths)
{
ShrinkExternalModAssemblyLoader.ScanExternalAssemblyRevisions(
settings, verboseLogging, authorizedDllPaths);
var results = new List<ShrinkModComponentSource>();
var prefixes = settings?.assemblyNamePrefixes;
@@ -50,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,
+29 -1
View File
@@ -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;
}
}
}
+21 -56
View File
@@ -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);
}
}
}
+43 -3
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Cysharp.Threading.Tasks;
namespace ShrinkModFramework
@@ -19,7 +20,8 @@ namespace ShrinkModFramework
new Dictionary<string, ShrinkModHandle>();
public static async UniTask<IReadOnlyDictionary<string, ShrinkModHandle>> ApplyDiscoveredAsync(
ShrinkModFrameworkSettings settings = null)
ShrinkModFrameworkSettings settings = null,
IEnumerable<string> authorizedDllPaths = null)
{
settings ??= ShrinkModFrameworkSettings.Instance;
var verboseLogging = settings == null || settings.verboseLogging;
@@ -34,8 +36,10 @@ namespace ShrinkModFramework
ShrinkModNetworkManager.Configure(settings == null || settings.enableNetworkSync, verboseLogging);
try
{
var sources = ShrinkModComponentDiscovery.Discover(settings, verboseLogging);
await _host.ApplyAsync(sources);
var authorizedPaths = authorizedDllPaths?.ToArray() ?? Array.Empty<string>();
var sources = ShrinkModComponentDiscovery.DiscoverCurrent(
settings, verboseLogging, authorizedPaths);
await _host.ApplyAsync(sources, () => ShrinkExternalModAssemblyLoader.RestoreState(revisionState));
}
catch
{
@@ -50,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)
{
@@ -34,17 +34,22 @@ namespace ShrinkModFramework
private static bool _resolveRegistered;
private static int _lastWarnedResidentCount;
public static IReadOnlyList<Assembly> LoadExternalAssemblies(ShrinkModFrameworkSettings settings, bool verboseLogging)
public static IReadOnlyList<Assembly> LoadExternalAssemblies(
ShrinkModFrameworkSettings settings,
bool verboseLogging,
IEnumerable<string> authorizedDllPaths = null)
{
return ScanExternalAssemblyRevisions(settings, verboseLogging)
return ScanExternalAssemblyRevisions(settings, verboseLogging, authorizedDllPaths)
.Select(revision => revision.Assembly)
.ToArray();
}
internal static IReadOnlyList<ExternalAssemblyRevision> ScanExternalAssemblyRevisions(
ShrinkModFrameworkSettings settings, bool verboseLogging)
ShrinkModFrameworkSettings settings,
bool verboseLogging,
IEnumerable<string> authorizedDllPaths = null)
{
if (settings != null && !settings.enableExternalDllMods)
if (settings == null || !settings.enableExternalDllMods)
{
CurrentAssemblyRevisions.Clear();
KnownAssemblyFiles.Clear();
@@ -52,27 +57,23 @@ namespace ShrinkModFramework
}
#if ENABLE_IL2CPP && !UNITY_EDITOR
Debug.LogWarning("[ShrinkModFramework] IL2CPP 运行时不支持外部 DLL 热加载,已跳过外部模组扫描。");
Debug.LogWarning("[ShrinkModFramework] IL2CPP 运行时不支持外部 DLL 加载,已跳过授权模组。");
return Array.Empty<ExternalAssemblyRevision>();
#else
var modsDirectory = GetExternalModsDirectory(settings);
if (settings == null || settings.autoCreateExternalModsDirectory)
Directory.CreateDirectory(modsDirectory);
RegisterAssemblyResolve();
var dllPaths = Directory.GetFiles(modsDirectory, "*.dll", SearchOption.AllDirectories)
.Select(Path.GetFullPath)
.OrderBy(path => path, StringComparer.OrdinalIgnoreCase)
.ToArray();
var presentPaths = new HashSet<string>(dllPaths, StringComparer.OrdinalIgnoreCase);
var dllPaths = NormalizeAuthorizedPaths(authorizedDllPaths);
var presentPaths = new HashSet<string>(
dllPaths.Where(File.Exists),
StringComparer.OrdinalIgnoreCase);
foreach (var dllPath in dllPaths
KnownAssemblyFiles.Clear();
foreach (var dllPath in presentPaths)
KnownAssemblyFiles[Path.GetFileNameWithoutExtension(dllPath)] = dllPath;
foreach (var dllPath in presentPaths
.OrderBy(path => path, StringComparer.OrdinalIgnoreCase))
{
var assemblyName = Path.GetFileNameWithoutExtension(dllPath);
KnownAssemblyFiles[assemblyName] = dllPath;
try
{
var bytes = File.ReadAllBytes(dllPath);
@@ -131,6 +132,41 @@ namespace ShrinkModFramework
#endif
}
private static string[] NormalizeAuthorizedPaths(IEnumerable<string> authorizedDllPaths)
{
if (authorizedDllPaths == null)
return Array.Empty<string>();
var normalized = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var rawPath in authorizedDllPaths)
{
if (string.IsNullOrWhiteSpace(rawPath))
continue;
string fullPath;
try
{
fullPath = Path.GetFullPath(rawPath.Trim());
}
catch (Exception exception)
{
throw new ArgumentException($"授权 DLL 路径无效:{rawPath}",
nameof(authorizedDllPaths), exception);
}
if (!string.Equals(Path.GetExtension(fullPath), ".dll",
StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException($"授权路径不是 DLL:{fullPath}",
nameof(authorizedDllPaths));
}
normalized.Add(fullPath);
}
return normalized.OrderBy(path => path, StringComparer.OrdinalIgnoreCase).ToArray();
}
internal static bool IsExternalAssembly(Assembly assembly) =>
assembly != null && ExternalAssemblyHistory.ContainsKey(assembly);
@@ -259,7 +295,7 @@ namespace ShrinkModFramework
}
}
private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
internal static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
var requestedName = new AssemblyName(args.Name).Name;
if (string.IsNullOrWhiteSpace(requestedName))
@@ -268,13 +304,42 @@ namespace ShrinkModFramework
if (!KnownAssemblyFiles.TryGetValue(requestedName, out var path) || !File.Exists(path))
return null;
try
{
return Assembly.Load(File.ReadAllBytes(path));
}
catch
{
if (ShrinkModLoader.AssemblyResolvePolicy != null &&
!ShrinkModLoader.AssemblyResolvePolicy(args.RequestingAssembly, new AssemblyName(args.Name), path))
return null;
lock (ResolveLock)
{
try
{
var bytes = File.ReadAllBytes(path);
var revision = ComputeSha256(bytes);
if (CurrentAssemblyRevisions.TryGetValue(path, out var current) &&
string.Equals(current.Revision, revision, StringComparison.Ordinal))
{
return current.Assembly;
}
var pdbPath = Path.ChangeExtension(path, ".pdb");
var pdbBytes = File.Exists(pdbPath) ? File.ReadAllBytes(pdbPath) : null;
var assembly = pdbBytes != null
? Assembly.Load(bytes, pdbBytes)
: Assembly.Load(bytes);
var loadedRevision = new ExternalAssemblyRevision
{
Path = path,
Revision = revision,
Assembly = assembly,
LoadedBytes = bytes.LongLength + (pdbBytes?.LongLength ?? 0L)
};
CurrentAssemblyRevisions[path] = loadedRevision;
ExternalAssemblyHistory[assembly] = loadedRevision;
return assembly;
}
catch
{
return null;
}
}
}
}
+1 -1
View File
@@ -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");
+89 -56
View File
@@ -18,6 +18,25 @@ namespace ShrinkModFramework
private static readonly Dictionary<string, ShrinkModHandle> LoadedMods = new(StringComparer.Ordinal);
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 =>
@@ -27,8 +46,36 @@ namespace ShrinkModFramework
public static event Action<IReadOnlyDictionary<string, ShrinkModHandle>> OnAllModsReady;
public static IReadOnlyDictionary<string, ShrinkModHandle> LoadAll(ShrinkModFrameworkSettings settings = null)
=> LoadInternal(settings, Array.Empty<string>());
/// <summary>
/// 加载工程内模组,并且只加载调用方显式授权的外部 DLL 路径。
/// 路径集合是完整白名单,不会递归扫描模组目录;后续 revision 刷新也只复用该白名单。
/// </summary>
public static IReadOnlyDictionary<string, ShrinkModHandle> LoadAuthorized(
ShrinkModFrameworkSettings settings,
IEnumerable<string> authorizedDllPaths)
{
if (authorizedDllPaths == null)
throw new ArgumentNullException(nameof(authorizedDllPaths));
return LoadInternal(settings, authorizedDllPaths);
}
private static IReadOnlyDictionary<string, ShrinkModHandle> LoadInternal(
ShrinkModFrameworkSettings settings,
IEnumerable<string> authorizedDllPaths)
{
if (_hostComposed) throw new InvalidOperationException("Use LoadComposed to update a host composition.");
settings ??= ShrinkModFrameworkSettings.Instance;
_authorizedDllPaths = authorizedDllPaths
.Where(path => !string.IsNullOrWhiteSpace(path))
.Select(path => path.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
if (settings == null || settings.useContextHost)
return ApplyContextComposition(settings, _authorizedDllPaths);
if (IsLoaded)
{
@@ -36,15 +83,13 @@ namespace ShrinkModFramework
return Mods;
}
if (settings == null || settings.useContextHost)
return ApplyContextComposition(settings);
var verboseLogging = settings == null || settings.verboseLogging;
try
{
ShrinkModNetworkManager.Configure(settings == null || settings.enableNetworkSync, verboseLogging);
ShrinkExternalModAssemblyLoader.LoadExternalAssemblies(settings, verboseLogging);
ShrinkExternalModAssemblyLoader.LoadExternalAssemblies(
settings, verboseLogging, _authorizedDllPaths);
var discovered = DiscoverMods(settings);
var ordered = ResolveLoadOrder(discovered, allowExistingLoadedDependencies: true);
@@ -71,14 +116,16 @@ 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);
return ApplyContextComposition(settings, _authorizedDllPaths);
if (!IsLoaded)
return LoadAll(settings);
return LoadInternal(settings, _authorizedDllPaths);
var verboseLogging = settings == null || settings.verboseLogging;
ShrinkExternalModAssemblyLoader.LoadExternalAssemblies(settings, verboseLogging);
ShrinkExternalModAssemblyLoader.LoadExternalAssemblies(
settings, verboseLogging, _authorizedDllPaths);
var discovered = DiscoverMods(settings)
.Where(mod => !LoadedMods.ContainsKey(mod.Info.ModId))
@@ -145,6 +192,9 @@ namespace ShrinkModFramework
ShrinkModNetworkManager.ResetForDomainReload();
ShrinkExternalModAssemblyLoader.ResetForTesting();
ShrinkHarmonyPatchService.ResetForTesting();
_authorizedDllPaths = Array.Empty<string>();
_hostComposed = false;
AssemblyResolvePolicy = null;
}
internal static void ResetForDomainReload()
@@ -160,17 +210,31 @@ namespace ShrinkModFramework
ShrinkModNetworkManager.ResetForDomainReload();
ShrinkExternalModAssemblyLoader.ResetForDomainReload();
ShrinkHarmonyPatchService.ResetForTesting();
_authorizedDllPaths = Array.Empty<string>();
_hostComposed = false;
AssemblyResolvePolicy = null;
}
private static IReadOnlyDictionary<string, ShrinkModHandle> ApplyContextComposition(
ShrinkModFrameworkSettings settings)
ShrinkModFrameworkSettings settings,
IEnumerable<string> authorizedDllPaths)
{
var previousGenerations = Mods.ToDictionary(
pair => pair.Key,
pair => pair.Value.Generation,
StringComparer.Ordinal);
var result = ShrinkModCordisRuntime.ApplyDiscoveredAsync(settings).GetAwaiter().GetResult();
var result = ShrinkModCordisRuntime
.ApplyDiscoveredAsync(settings, authorizedDllPaths)
.GetAwaiter()
.GetResult();
PublishReady(result, previousGenerations);
return result;
}
private static void PublishReady(IReadOnlyDictionary<string, ShrinkModHandle> result,
IReadOnlyDictionary<string, long> previousGenerations)
{
IsLoaded = true;
foreach (var pair in result.OrderBy(pair => pair.Key, StringComparer.Ordinal))
{
@@ -181,7 +245,6 @@ namespace ShrinkModFramework
}
}
OnAllModsReady?.Invoke(result);
return result;
}
private static ShrinkModHandle InstantiateAndTrack(DiscoveredMod discoveredMod,
@@ -206,6 +269,11 @@ namespace ShrinkModFramework
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (ShrinkExternalModAssemblyLoader.IsExternalAssembly(assembly) &&
!ShrinkExternalModAssemblyLoader.TryGetCurrentRevision(assembly, out _))
{
continue;
}
if (!ShouldScanAssembly(assembly, prefixes))
continue;
@@ -229,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
@@ -311,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
+18 -9
View File
@@ -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" : "")})";
}
}
+78
View File
@@ -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
+2
View File
@@ -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);
}
+312
View File
@@ -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(); }
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 44e4b1f576a745fe9c36b173015b98a3
+76 -3
View File
@@ -286,7 +286,23 @@ namespace ShrinkModFramework.Tests
}
[Test]
public void ExternalDllRevision_FailedReplacementRestoresPreviousAndBrokenBytesDoNotReplaceIt()
public void Settings_Defaults_DoNotAutoLoadOrWatchExternalDlls()
{
var settings = ScriptableObject.CreateInstance<ShrinkModFrameworkSettings>();
try
{
Assert.IsFalse(settings.autoLoadOnStartup);
Assert.IsFalse(settings.enableExternalDllMods);
Assert.IsFalse(settings.watchExternalModsDirectory);
}
finally
{
Object.DestroyImmediate(settings);
}
}
[Test]
public void ExternalDll_IsIgnoredUntilItsExactPathIsAuthorized()
{
ResetExternalRuntime();
var settings = CreateExternalSettings();
@@ -299,6 +315,62 @@ namespace ShrinkModFramework.Tests
CopyFixture("ExternalFixture.Mod.V1.dll.bytes", target);
ShrinkModLoader.LoadAll(settings);
Assert.IsEmpty(ShrinkModLoader.Mods);
Assert.AreEqual(0,
ShrinkModDiagnostics.CaptureExternalAssemblies(settings).CurrentRevisionCount);
ShrinkModLoader.LoadAuthorized(settings, new[] { target });
AssertExternalFixture("1.0.0", "v1");
}
finally
{
CleanupExternalRuntime(settings, directory);
}
}
[Test]
public void LegacyLoader_OnlyLoadsExplicitlyAuthorizedDllPaths()
{
ResetExternalRuntime();
var settings = CreateExternalSettings();
settings.useContextHost = false;
var directory = ShrinkExternalModAssemblyLoader.GetExternalModsDirectory(settings);
var authorized = Path.Combine(directory, "Authorized.Mod.dll");
var unauthorized = Path.Combine(directory, "Unauthorized.Mod.dll");
try
{
Directory.CreateDirectory(directory);
CopyFixture("ExternalFixture.Mod.V1.dll.bytes", authorized);
CopyFixture("ExternalFixture.Mod.V3.dll.bytes", unauthorized);
ShrinkModLoader.LoadAuthorized(settings, new[] { authorized });
AssertExternalFixture("1.0.0", "v1");
Assert.AreEqual(1,
ShrinkModDiagnostics.CaptureExternalAssemblies(settings).CurrentRevisionCount);
}
finally
{
CleanupExternalRuntime(settings, directory);
}
}
[Test]
public void ExternalDllRevision_FailedReplacementRestoresPreviousAndBrokenBytesDoNotReplaceIt()
{
ResetExternalRuntime();
var settings = CreateExternalSettings();
var directory = ShrinkExternalModAssemblyLoader.GetExternalModsDirectory(settings);
var target = Path.Combine(directory, "ExternalFixture.Mod.dll");
try
{
Directory.CreateDirectory(directory);
CopyFixture("ExternalFixture.Mod.V1.dll.bytes", target);
ShrinkModLoader.LoadAuthorized(settings, new[] { target });
AssertExternalFixture("1.0.0", "v1");
var restoredGeneration = ShrinkModLoader.Mods["external.fixture"].Generation;
@@ -358,7 +430,7 @@ namespace ShrinkModFramework.Tests
Assert.IsTrue(ShrinkModRuntimeDriver.InstanceForTesting!.HasWatcherForTesting);
CopyFixture("ExternalFixture.Mod.V1.dll.bytes", target);
ShrinkModLoader.LoadAll(settings);
ShrinkModLoader.LoadAuthorized(settings, new[] { target });
AssertExternalFixture("1.0.0", "v1");
// Two writes arrive as one debounce window; only the final valid revision should commit.
@@ -395,7 +467,7 @@ namespace ShrinkModFramework.Tests
CopyFixture("ExternalFixture.Provider.dll.bytes", providerPath);
CopyFixture("ExternalFixture.Consumer.dll.bytes", consumerPath);
ShrinkModLoader.LoadAll(settings);
ShrinkModLoader.LoadAuthorized(settings, new[] { providerPath, consumerPath });
Assert.AreEqual(2, ShrinkModLoader.Mods.Count);
Assert.AreEqual(ShrinkModState.Ready, ShrinkModLoader.Mods["external.provider"].State);
Assert.AreEqual(ShrinkModState.Ready, ShrinkModLoader.Mods["external.consumer"].State);
@@ -475,6 +547,7 @@ namespace ShrinkModFramework.Tests
settings.useContextHost = true;
settings.enableExternalDllMods = true;
settings.autoCreateExternalModsDirectory = false;
settings.watchExternalModsDirectory = true;
settings.externalModsFolderName = "ShrinkModFrameworkTests_" + Guid.NewGuid().ToString("N");
settings.assemblyNamePrefixes = new[] { "ExternalFixture." };
settings.enableHarmonyPatching = false;
+1
View File
@@ -3,6 +3,7 @@
"rootNamespace": "ShrinkModFramework.Tests",
"references": [
"ShrinkModFramework.Runtime",
"ShrinkEventBus.Runtime",
"ShrinkContext.Core.Runtime",
"UniTask",
"UnityEngine.TestRunner",
+9
View File
@@ -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。
+13
View File
@@ -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>
+49
View File
@@ -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) { } }
}
+55
View File
@@ -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");
}
}
+13
View File
@@ -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
View File
@@ -1,13 +1,13 @@
{
"name": "com.cneicy.shrink-mod-framework",
"version": "0.2.1",
"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.1.0",
"com.cneicy.shrink-eventbus": "2.0.0",
"com.cneicy.shrink-context-core": "0.3.1",
"com.cneicy.shrink-eventbus": "2.3.1",
"com.cysharp.unitask": "2.5.10"
},
"keywords": [