chore: initialize standalone UPM package
Publish UPM package / publish (push) Failing after 1s

This commit is contained in:
2026-08-26 02:48:49 +08:00
commit ee385a4107
32 changed files with 897 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
{
"name": "ShrinkApp.Core.Runtime",
"rootNamespace": "ShrinkApp",
"references": [
"ShrinkEventBus.Runtime",
"UniTask"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: b5b7047dbc0ca2e438a92daa2baa200c
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+81
View File
@@ -0,0 +1,81 @@
#nullable enable
using System;
using Cysharp.Threading.Tasks;
using UnityEngine;
namespace ShrinkApp
{
public static class ShrinkApp
{
public static ShrinkAppHost? Host { get; private set; }
public static ShrinkAppContext? Context { get; private set; }
public static ShrinkAppSettings Settings => ShrinkAppSettings.Instance;
public static ShrinkAppServices Services => Context?.Services ?? throw new System.InvalidOperationException("ShrinkApp is not initialized.");
public static bool IsRunning => (Host != null && Host.IsRunning) || _externalHostRunning;
private static bool _externalHostRunning;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
private static void ResetStaticState()
{
Host = null;
Context = null;
_externalHostRunning = false;
ShrinkAppSettings.ResetCachedInstance();
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void Bootstrap()
{
if (Host != null)
return;
var settings = ShrinkAppSettings.Instance;
if (settings.hostingMode == ShrinkAppHostingMode.ContextLoader)
{
// 阶段 2 过渡:经典宿主让位,由 ShrinkContext 加载器宿主(ShrinkContext.AppAdapter)接管启动
return;
}
var hostGameObject = new GameObject("ShrinkAppHost");
var host = hostGameObject.AddComponent<ShrinkAppHost>();
if (settings.dontDestroyOnLoad)
UnityEngine.Object.DontDestroyOnLoad(hostGameObject);
var services = new ShrinkAppServices();
var context = new ShrinkAppContext(host, settings, services);
host.Configure(context);
Host = host;
Context = context;
host.StartAppAsync().Forget(ex =>
{
Debug.LogException(ex);
Debug.LogError("[ShrinkApp] 启动失败: " + ex.Message);
});
}
/// <summary>
/// 阶段 2 过渡:由外部宿主(如 ShrinkContext 加载器宿主)提供已初始化的服务容器。
/// Host 保持 null——外部宿主不经过 ShrinkAppHost 生命周期,IsRunning 以外部宿主为准。
/// </summary>
public static void InitializeForExternalHost(ShrinkAppServices services, ShrinkAppSettings? settings = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
Context = new ShrinkAppContext(null!, settings ?? Settings, services);
_externalHostRunning = false;
}
/// <summary>
/// Lets a non-<see cref="ShrinkAppHost"/> orchestrator expose its lifecycle through
/// the legacy static facade while the migration is in progress.
/// </summary>
public static void SetExternalHostRunning(bool running)
{
_externalHostRunning = running;
}
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 10523dad09cece4438f29620b3253fdb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+53
View File
@@ -0,0 +1,53 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
namespace ShrinkApp
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class ShrinkAppInstallerRegistryAttribute : Attribute
{
public ShrinkAppInstallerRegistryAttribute(params Type[] installerTypes)
{
InstallerTypes = installerTypes ?? Array.Empty<Type>();
}
public Type[] InstallerTypes { get; }
}
internal static class ShrinkAppGeneratedRegistry
{
public static IReadOnlyList<Type> GetInstallerTypes()
{
var types = new List<Type>();
var seen = new HashSet<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
object[] attributes;
try
{
attributes = assembly.GetCustomAttributes(typeof(ShrinkAppInstallerRegistryAttribute), false);
}
catch
{
continue;
}
foreach (var attribute in attributes.OfType<ShrinkAppInstallerRegistryAttribute>())
{
foreach (var installerType in attribute.InstallerTypes ?? Array.Empty<Type>())
{
if (installerType == null || !seen.Add(installerType))
continue;
types.Add(installerType);
}
}
}
return types;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1818116c8e85f5e489c0c4955f506ff2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+167
View File
@@ -0,0 +1,167 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Cysharp.Threading.Tasks;
using ShrinkEventBus;
using UnityEngine;
namespace ShrinkApp
{
public sealed class ShrinkAppHost : MonoBehaviour
{
private readonly List<string> _startedModules = new();
private ShrinkAppContext? _context;
private bool _unityStarted;
private bool _publishedStartedEvent;
public bool IsRunning { get; private set; }
public bool HasFailed { get; private set; }
public string LastError { get; private set; } = string.Empty;
public IReadOnlyList<string> StartedModules => _startedModules;
internal void Configure(ShrinkAppContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
internal async UniTask StartAppAsync()
{
if (IsRunning || HasFailed)
return;
if (_context == null)
throw new InvalidOperationException("ShrinkAppHost is not configured.");
var installers = CreateInstallerInstances();
var orderedInstallers = SortInstallers(installers, _context.Settings);
try
{
foreach (var installer in orderedInstallers)
installer.RegisterServices(_context);
foreach (var installer in orderedInstallers)
{
await installer.InitializeAsync(_context);
_startedModules.Add(installer.ModuleId);
}
IsRunning = true;
PublishStartedEventIfReady();
}
catch (Exception ex)
{
HasFailed = true;
LastError = ex.Message;
EventBus.Post(new ShrinkAppStartFailedEvent
{
ErrorMessage = ex.Message,
FailedModuleId = _startedModules.LastOrDefault() ?? string.Empty
});
throw;
}
}
private void Start()
{
_unityStarted = true;
PublishStartedEventIfReady();
}
private void PublishStartedEventIfReady()
{
if (_publishedStartedEvent || !_unityStarted || !IsRunning)
return;
_publishedStartedEvent = true;
EventBus.Post(new ShrinkAppStartedEvent
{
ModuleIds = _startedModules.ToArray()
});
}
private static IReadOnlyList<IShrinkAppModuleInstaller> CreateInstallerInstances()
{
var installers = new List<IShrinkAppModuleInstaller>();
foreach (var installerType in ShrinkAppGeneratedRegistry.GetInstallerTypes())
{
if (installerType == null)
continue;
if (!typeof(IShrinkAppModuleInstaller).IsAssignableFrom(installerType))
throw new InvalidOperationException($"Installer type does not implement IShrinkAppModuleInstaller: {installerType.FullName}");
if (installerType.IsAbstract)
throw new InvalidOperationException($"Installer type cannot be abstract: {installerType.FullName}");
if (Activator.CreateInstance(installerType) is not IShrinkAppModuleInstaller installer)
throw new InvalidOperationException($"Failed to create installer: {installerType.FullName}");
installers.Add(installer);
}
return installers;
}
private static IReadOnlyList<IShrinkAppModuleInstaller> SortInstallers(
IReadOnlyList<IShrinkAppModuleInstaller> installers,
ShrinkAppSettings settings)
{
var disabled = new HashSet<string>(
settings.disabledModuleIds?.Where(id => !string.IsNullOrWhiteSpace(id)).Select(id => id.Trim()) ??
Enumerable.Empty<string>(),
StringComparer.OrdinalIgnoreCase);
var enabledInstallers = installers
.Where(installer => !disabled.Contains(installer.ModuleId))
.ToArray();
var byId = new Dictionary<string, IShrinkAppModuleInstaller>(StringComparer.OrdinalIgnoreCase);
foreach (var installer in enabledInstallers)
{
if (string.IsNullOrWhiteSpace(installer.ModuleId))
throw new InvalidOperationException($"Installer {installer.GetType().FullName} has an empty ModuleId.");
if (!byId.TryAdd(installer.ModuleId.Trim(), installer))
throw new InvalidOperationException($"Duplicate installer ModuleId: {installer.ModuleId}");
}
var visitState = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var ordered = new List<IShrinkAppModuleInstaller>();
foreach (var installer in enabledInstallers.OrderBy(item => item.Order).ThenBy(item => item.ModuleId, StringComparer.OrdinalIgnoreCase))
{
Visit(installer, byId, visitState, ordered);
}
return ordered;
}
private static void Visit(
IShrinkAppModuleInstaller installer,
IReadOnlyDictionary<string, IShrinkAppModuleInstaller> byId,
IDictionary<string, int> visitState,
IList<IShrinkAppModuleInstaller> ordered)
{
var state = visitState.TryGetValue(installer.ModuleId, out var existingState) ? existingState : 0;
if (state == 2)
return;
if (state == 1)
throw new InvalidOperationException($"Circular installer dependency detected at module: {installer.ModuleId}");
visitState[installer.ModuleId] = 1;
foreach (var dependencyId in installer.DependsOn ?? Array.Empty<string>())
{
if (string.IsNullOrWhiteSpace(dependencyId))
continue;
if (!byId.TryGetValue(dependencyId.Trim(), out var dependency))
throw new InvalidOperationException(
$"Installer dependency missing. Module={installer.ModuleId}, DependsOn={dependencyId}");
Visit(dependency, byId, visitState, ordered);
}
visitState[installer.ModuleId] = 2;
if (!ordered.Contains(installer))
ordered.Add(installer);
}
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: df43c81d962edd64cbd214b2697b4179
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+16
View File
@@ -0,0 +1,16 @@
#nullable enable
using System;
using System.Collections.Generic;
namespace ShrinkApp
{
/// <summary>
/// 编译期发现的应用模块安装器类型(公共入口)。
/// 经典 ShrinkAppHost 与外部宿主(ShrinkContext 加载器宿主)共用同一份发现结果。
/// </summary>
public static class ShrinkAppInstallers
{
public static IReadOnlyList<Type> GetDiscoveredInstallerTypes() =>
ShrinkAppGeneratedRegistry.GetInstallerTypes();
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c22f2e857d66bae458ff3dd6d9519d0d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+181
View File
@@ -0,0 +1,181 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Cysharp.Threading.Tasks;
using ShrinkEventBus;
using UnityEngine;
namespace ShrinkApp
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class ShrinkAppModuleInstallerAttribute : Attribute
{
}
public interface IShrinkAppModuleInstaller
{
string ModuleId { get; }
int Order { get; }
IReadOnlyList<string> DependsOn { get; }
void RegisterServices(ShrinkAppContext context);
UniTask InitializeAsync(ShrinkAppContext context);
}
public sealed class ShrinkAppContext
{
internal ShrinkAppContext(ShrinkAppHost host, ShrinkAppSettings settings, ShrinkAppServices services)
{
Host = host;
Settings = settings;
Services = services;
}
/// <summary>
/// 为非 MonoBehaviour 宿主(如 ShrinkContext 纤程适配器)构建上下文。
/// Host 为 null:适用于不经过 ShrinkAppHost 启动流的独立编排场景。
/// </summary>
public static ShrinkAppContext CreateStandalone(ShrinkAppServices services, ShrinkAppSettings? settings = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
return new ShrinkAppContext(null!, settings ?? ShrinkAppSettings.Instance, services);
}
public ShrinkAppHost Host { get; }
public ShrinkAppSettings Settings { get; }
public ShrinkAppServices Services { get; }
}
public sealed class ShrinkAppServices
{
private readonly Dictionary<Type, object> _services = new();
public void Register<TService>(TService service) where TService : class
{
if (service == null)
throw new ArgumentNullException(nameof(service));
_services[typeof(TService)] = service;
}
public bool TryGet<TService>(out TService? service) where TService : class
{
if (_services.TryGetValue(typeof(TService), out var boxed) && boxed is TService typed)
{
service = typed;
return true;
}
service = null;
return false;
}
/// <summary>
/// Removes a service only when the current registration is the supplied instance.
/// This lets context-driven components expose the legacy service facade as a
/// reversible effect without removing a newer replacement during teardown.
/// </summary>
public bool TryUnregister<TService>(TService service) where TService : class
{
if (service == null)
throw new ArgumentNullException(nameof(service));
if (!_services.TryGetValue(typeof(TService), out var current) ||
!ReferenceEquals(current, service))
return false;
return _services.Remove(typeof(TService));
}
public TService GetRequired<TService>() where TService : class
{
if (!TryGet<TService>(out var service) || service == null)
throw new InvalidOperationException($"Required service is not registered: {typeof(TService).FullName}");
return service;
}
public IReadOnlyList<string> GetRegisteredServiceTypeNames()
{
return _services.Keys
.Select(type => type.FullName ?? type.Name)
.OrderBy(name => name, StringComparer.OrdinalIgnoreCase)
.ToArray();
}
}
/// <summary>ShrinkApp 的宿主模式(阶段 2 过渡:两种模式并存,按项目选择)。</summary>
public enum ShrinkAppHostingMode
{
/// <summary>经典模式:ShrinkAppHost 在 BeforeSceneLoad 自动创建并按拓扑序启动安装器。</summary>
ClassicHost = 0,
/// <summary>加载器模式:经典宿主让位,由 ShrinkContext 加载器宿主(ShrinkContext.AppAdapter)接管启动,
/// 支持运行中按模块 disable/enable 与依赖响应式等待。</summary>
ContextLoader = 1,
}
[CreateAssetMenu(fileName = "ShrinkAppSettings", menuName = "ShrinkApp/Settings")]
public class ShrinkAppSettings : ScriptableObject
{
private static ShrinkAppSettings? _instance;
public static ShrinkAppSettings Instance
{
get
{
if (_instance != null)
return _instance;
_instance = Resources.Load<ShrinkAppSettings>("ShrinkAppSettings");
#if UNITY_EDITOR
if (!_instance)
{
var guids = UnityEditor.AssetDatabase.FindAssets("t:ShrinkAppSettings");
if (guids.Length > 0)
{
var path = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[0]);
_instance = UnityEditor.AssetDatabase.LoadAssetAtPath<ShrinkAppSettings>(path);
}
}
#endif
if (!_instance)
{
_instance = CreateInstance<ShrinkAppSettings>();
Debug.LogWarning(
"[ShrinkApp] 未找到 ShrinkAppSettings,当前使用默认配置。建议通过 Assets -> Create -> ShrinkApp -> Settings 创建配置。");
}
return _instance!;
}
internal set => _instance = value;
}
internal static void ResetCachedInstance()
{
_instance = null;
}
public bool dontDestroyOnLoad = true;
public bool verboseLogging;
public string[] disabledModuleIds = Array.Empty<string>();
[Tooltip("宿主模式:ClassicHost 为经典自动启动;ContextLoader 由 ShrinkContext 加载器宿主接管(阶段 2 过渡)")]
public ShrinkAppHostingMode hostingMode = ShrinkAppHostingMode.ClassicHost;
}
public sealed class ShrinkAppStartedEvent : IShrinkEvent
{
public IReadOnlyList<string> ModuleIds { get; set; } = Array.Empty<string>();
}
public sealed class ShrinkAppStartFailedEvent : IShrinkEvent
{
public string ErrorMessage { get; set; } = string.Empty;
public string FailedModuleId { get; set; } = string.Empty;
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 384dd878beec6b848b64aa843b464e95
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: