Decompiled source of Spherewright v0.3.3

plugins/Newtonsoft.Json.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")]
[assembly: AssemblyCompany("Newtonsoft")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © James Newton-King 2008")]
[assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")]
[assembly: AssemblyFileVersion("13.0.4.30916")]
[assembly: AssemblyInformationalVersion("13.0.4+4e13299d4b0ec96bd4df9954ef646bd2d1b5bf2a")]
[assembly: AssemblyProduct("Json.NET")]
[assembly: AssemblyTitle("Json.NET .NET 4.5")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("13.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	internal enum DynamicallyAccessedMemberTypes
	{
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class FeatureGuardAttribute : Attribute
	{
		public Type FeatureType { get; }

		public FeatureGuardAttribute(Type featureType)
		{
			FeatureType = featureType;
		}
	}
	[AttributeUsage(AttributeTargets.Property, Inherited = false)]
	internal sealed class FeatureSwitchDefinitionAttribute : Attribute
	{
		public string SwitchName { get; }

		public FeatureSwitchDefinitionAttribute(string switchName)
		{
			SwitchName = switchName;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
}
namespace Newtonsoft.Json
{
	public enum ConstructorHandling
	{
		Default,
		AllowNonPublicDefaultConstructor
	}
	public enum DateFormatHandling
	{
		IsoDateFormat,
		MicrosoftDateFormat
	}
	public enum DateParseHandling
	{
		None,
		DateTime,
		DateTimeOffset
	}
	public enum DateTimeZoneHandling
	{
		Local,
		Utc,
		Unspecified,
		RoundtripKind
	}
	public class DefaultJsonNameTable : JsonNameTable
	{
		private class Entry
		{
			internal readonly string Value;

			internal readonly int HashCode;

			internal Entry Next;

			internal Entry(string value, int hashCode, Entry next)
			{
				Value = value;
				HashCode = hashCode;
				Next = next;
			}
		}

		private static readonly int HashCodeRandomizer;

		private int _count;

		private Entry[] _entries;

		private int _mask = 31;

		static DefaultJsonNameTable()
		{
			HashCodeRandomizer = Environment.TickCount;
		}

		public DefaultJsonNameTable()
		{
			_entries = new Entry[_mask + 1];
		}

		public override string? Get(char[] key, int start, int length)
		{
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			num += (num << 7) ^ key[start];
			int num2 = start + length;
			for (int i = start + 1; i < num2; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			int num3 = Volatile.Read(ref _mask);
			int num4 = num & num3;
			for (Entry entry = _entries[num4]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && TextEquals(entry.Value, key, start, length))
				{
					return entry.Value;
				}
			}
			return null;
		}

		public string Add(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			int length = key.Length;
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			for (int i = 0; i < key.Length; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal))
				{
					return entry.Value;
				}
			}
			return AddEntry(key, num);
		}

		private string AddEntry(string str, int hashCode)
		{
			int num = hashCode & _mask;
			Entry entry = new Entry(str, hashCode, _entries[num]);
			_entries[num] = entry;
			if (_count++ == _mask)
			{
				Grow();
			}
			return entry.Value;
		}

		private void Grow()
		{
			Entry[] entries = _entries;
			int num = _mask * 2 + 1;
			Entry[] array = new Entry[num + 1];
			for (int i = 0; i < entries.Length; i++)
			{
				Entry entry = entries[i];
				while (entry != null)
				{
					int num2 = entry.HashCode & num;
					Entry next = entry.Next;
					entry.Next = array[num2];
					array[num2] = entry;
					entry = next;
				}
			}
			_entries = array;
			Volatile.Write(ref _mask, num);
		}

		private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)
		{
			if (str1.Length != str2Length)
			{
				return false;
			}
			for (int i = 0; i < str1.Length; i++)
			{
				if (str1[i] != str2[str2Start + i])
				{
					return false;
				}
			}
			return true;
		}
	}
	[Flags]
	public enum DefaultValueHandling
	{
		Include = 0,
		Ignore = 1,
		Populate = 2,
		IgnoreAndPopulate = 3
	}
	public enum FloatFormatHandling
	{
		String,
		Symbol,
		DefaultValue
	}
	public enum FloatParseHandling
	{
		Double,
		Decimal
	}
	public enum Formatting
	{
		None,
		Indented
	}
	public interface IArrayPool<T>
	{
		T[] Rent(int minimumLength);

		void Return(T[]? array);
	}
	public interface IJsonLineInfo
	{
		int LineNumber { get; }

		int LinePosition { get; }

		bool HasLineInfo();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonArrayAttribute : JsonContainerAttribute
	{
		private bool _allowNullItems;

		public bool AllowNullItems
		{
			get
			{
				return _allowNullItems;
			}
			set
			{
				_allowNullItems = value;
			}
		}

		public JsonArrayAttribute()
		{
		}

		public JsonArrayAttribute(bool allowNullItems)
		{
			_allowNullItems = allowNullItems;
		}

		public JsonArrayAttribute(string id)
			: base(id)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)]
	public sealed class JsonConstructorAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public abstract class JsonContainerAttribute : Attribute
	{
		internal bool? _isReference;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		private Type? _namingStrategyType;

		private object[]? _namingStrategyParameters;

		public string? Id { get; set; }

		public string? Title { get; set; }

		public string? Description { get; set; }

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType
		{
			get
			{
				return _namingStrategyType;
			}
			set
			{
				_namingStrategyType = value;
				NamingStrategyInstance = null;
			}
		}

		public object[]? NamingStrategyParameters
		{
			get
			{
				return _namingStrategyParameters;
			}
			set
			{
				_namingStrategyParameters = value;
				NamingStrategyInstance = null;
			}
		}

		internal NamingStrategy? NamingStrategyInstance { get; set; }

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		protected JsonContainerAttribute()
		{
		}

		protected JsonContainerAttribute(string id)
		{
			Id = id;
		}
	}
	public static class JsonConvert
	{
		public static readonly string True = "true";

		public static readonly string False = "false";

		public static readonly string Null = "null";

		public static readonly string Undefined = "undefined";

		public static readonly string PositiveInfinity = "Infinity";

		public static readonly string NegativeInfinity = "-Infinity";

		public static readonly string NaN = "NaN";

		public static Func<JsonSerializerSettings>? DefaultSettings { get; set; }

		public static string ToString(DateTime value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
		}

		public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
		{
			DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(DateTimeOffset value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat);
		}

		public static string ToString(DateTimeOffset value, DateFormatHandling format)
		{
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(bool value)
		{
			if (!value)
			{
				return False;
			}
			return True;
		}

		public static string ToString(char value)
		{
			return ToString(char.ToString(value));
		}

		public static string ToString(Enum value)
		{
			return value.ToString("D");
		}

		public static string ToString(int value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(short value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ushort value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(uint value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(long value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		private static string ToStringInternal(BigInteger value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ulong value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(float value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value)))
			{
				return text;
			}
			if (floatFormatHandling == FloatFormatHandling.DefaultValue)
			{
				if (nullable)
				{
					return Null;
				}
				return "0.0";
			}
			return quoteChar + text + quoteChar;
		}

		public static string ToString(double value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureDecimalPlace(double value, string text)
		{
			if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		private static string EnsureDecimalPlace(string text)
		{
			if (StringUtils.IndexOf(text, '.') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		public static string ToString(byte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(sbyte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(decimal value)
		{
			return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
		}

		public static string ToString(Guid value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(Guid value, char quoteChar)
		{
			string text = value.ToString("D", CultureInfo.InvariantCulture);
			string text2 = quoteChar.ToString(CultureInfo.InvariantCulture);
			return text2 + text + text2;
		}

		public static string ToString(TimeSpan value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(TimeSpan value, char quoteChar)
		{
			return ToString(value.ToString(), quoteChar);
		}

		public static string ToString(Uri? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ToString(value, '"');
		}

		internal static string ToString(Uri value, char quoteChar)
		{
			return ToString(value.OriginalString, quoteChar);
		}

		public static string ToString(string? value)
		{
			return ToString(value, '"');
		}

		public static string ToString(string? value, char delimiter)
		{
			return ToString(value, delimiter, StringEscapeHandling.Default);
		}

		public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling)
		{
			if (delimiter != '"' && delimiter != '\'')
			{
				throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
			}
			return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling);
		}

		public static string ToString(object? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ConvertUtils.GetTypeCode(value.GetType()) switch
			{
				PrimitiveTypeCode.String => ToString((string)value), 
				PrimitiveTypeCode.Char => ToString((char)value), 
				PrimitiveTypeCode.Boolean => ToString((bool)value), 
				PrimitiveTypeCode.SByte => ToString((sbyte)value), 
				PrimitiveTypeCode.Int16 => ToString((short)value), 
				PrimitiveTypeCode.UInt16 => ToString((ushort)value), 
				PrimitiveTypeCode.Int32 => ToString((int)value), 
				PrimitiveTypeCode.Byte => ToString((byte)value), 
				PrimitiveTypeCode.UInt32 => ToString((uint)value), 
				PrimitiveTypeCode.Int64 => ToString((long)value), 
				PrimitiveTypeCode.UInt64 => ToString((ulong)value), 
				PrimitiveTypeCode.Single => ToString((float)value), 
				PrimitiveTypeCode.Double => ToString((double)value), 
				PrimitiveTypeCode.DateTime => ToString((DateTime)value), 
				PrimitiveTypeCode.Decimal => ToString((decimal)value), 
				PrimitiveTypeCode.DBNull => Null, 
				PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), 
				PrimitiveTypeCode.Guid => ToString((Guid)value), 
				PrimitiveTypeCode.Uri => ToString((Uri)value), 
				PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), 
				PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), 
				_ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), 
			};
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value)
		{
			return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Formatting formatting)
		{
			return SerializeObject(value, formatting, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			jsonSerializer.Formatting = formatting;
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer)
		{
			StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture);
			using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter))
			{
				jsonTextWriter.Formatting = jsonSerializer.Formatting;
				jsonSerializer.Serialize(jsonTextWriter, value, type);
			}
			return stringWriter.ToString();
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value)
		{
			return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value, JsonSerializerSettings settings)
		{
			return DeserializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value, Type type)
		{
			return DeserializeObject(value, type, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeObject<T>(string value)
		{
			return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
		{
			return DeserializeObject<T>(value);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
		{
			return DeserializeObject<T>(value, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeObject<T>(string value, params JsonConverter[] converters)
		{
			return (T)DeserializeObject(value, typeof(T), converters);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings)
		{
			return (T)DeserializeObject(value, typeof(T), settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return DeserializeObject(value, type, settings);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings)
		{
			ValidationUtils.ArgumentNotNull(value, "value");
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			if (!jsonSerializer.IsCheckAdditionalContentSet())
			{
				jsonSerializer.CheckAdditionalContent = true;
			}
			using JsonTextReader reader = new JsonTextReader(new StringReader(value));
			return jsonSerializer.Deserialize(reader, type);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static void PopulateObject(string value, object target)
		{
			PopulateObject(value, target, null);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static void PopulateObject(string value, object target, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			using JsonReader jsonReader = new JsonTextReader(new StringReader(value));
			jsonSerializer.Populate(jsonReader, target);
			if (settings == null || !settings.CheckAdditionalContent)
			{
				return;
			}
			while (jsonReader.Read())
			{
				if (jsonReader.TokenType != JsonToken.Comment)
				{
					throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
				}
			}
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXmlNode(XmlNode? node)
		{
			return SerializeXmlNode(node, Formatting.None);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXmlNode(XmlNode? node, Formatting formatting)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value)
		{
			return DeserializeXmlNode(value, null);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXNode(XObject? node)
		{
			return SerializeXNode(node, Formatting.None);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXNode(XObject? node, Formatting formatting)
		{
			return SerializeXNode(node, formatting, omitRootObject: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value)
		{
			return DeserializeXNode(value, null);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter);
		}
	}
	public abstract class JsonConverter
	{
		public virtual bool CanRead => true;

		public virtual bool CanWrite => true;

		public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer);

		public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer);

		public abstract bool CanConvert(Type objectType);
	}
	public abstract class JsonConverter<T> : JsonConverter
	{
		public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
		{
			if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T))))
			{
				throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			WriteJson(writer, (T)value, serializer);
		}

		public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer);

		public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
		{
			bool flag = existingValue == null;
			if (!flag && !(existingValue is T))
			{
				throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer);
		}

		public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer);

		public sealed override bool CanConvert(Type objectType)
		{
			return typeof(T).IsAssignableFrom(objectType);
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonConverterAttribute : Attribute
	{
		private readonly Type _converterType;

		public Type ConverterType => _converterType;

		public object[]? ConverterParameters { get; }

		public JsonConverterAttribute(Type converterType)
		{
			if (converterType == null)
			{
				throw new ArgumentNullException("converterType");
			}
			_converterType = converterType;
		}

		public JsonConverterAttribute(Type converterType, params object[] converterParameters)
			: this(converterType)
		{
			ConverterParameters = converterParameters;
		}
	}
	public class JsonConverterCollection : Collection<JsonConverter>
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonDictionaryAttribute : JsonContainerAttribute
	{
		public JsonDictionaryAttribute()
		{
		}

		public JsonDictionaryAttribute(string id)
			: base(id)
		{
		}
	}
	[Serializable]
	public class JsonException : Exception
	{
		public JsonException()
		{
		}

		public JsonException(string message)
			: base(message)
		{
		}

		public JsonException(string message, Exception? innerException)
			: base(message, innerException)
		{
		}

		public JsonException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			return new JsonException(message);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class JsonExtensionDataAttribute : Attribute
	{
		public bool WriteData { get; set; }

		public bool ReadData { get; set; }

		public JsonExtensionDataAttribute()
		{
			WriteData = true;
			ReadData = true;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonIgnoreAttribute : Attribute
	{
	}
	public abstract class JsonNameTable
	{
		public abstract string? Get(char[] key, int start, int length);
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonObjectAttribute : JsonContainerAttribute
	{
		private MemberSerialization _memberSerialization;

		internal MissingMemberHandling? _missingMemberHandling;

		internal Required? _itemRequired;

		internal NullValueHandling? _itemNullValueHandling;

		public MemberSerialization MemberSerialization
		{
			get
			{
				return _memberSerialization;
			}
			set
			{
				_memberSerialization = value;
			}
		}

		public MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling.GetValueOrDefault();
			}
			set
			{
				_missingMemberHandling = value;
			}
		}

		public NullValueHandling ItemNullValueHandling
		{
			get
			{
				return _itemNullValueHandling.GetValueOrDefault();
			}
			set
			{
				_itemNullValueHandling = value;
			}
		}

		public Required ItemRequired
		{
			get
			{
				return _itemRequired.GetValueOrDefault();
			}
			set
			{
				_itemRequired = value;
			}
		}

		public JsonObjectAttribute()
		{
		}

		public JsonObjectAttribute(MemberSerialization memberSerialization)
		{
			MemberSerialization = memberSerialization;
		}

		public JsonObjectAttribute(string id)
			: base(id)
		{
		}
	}
	internal enum JsonContainerType
	{
		None,
		Object,
		Array,
		Constructor
	}
	internal struct JsonPosition
	{
		private static readonly char[] SpecialCharacters = new char[18]
		{
			'.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t',
			'\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029'
		};

		internal JsonContainerType Type;

		internal int Position;

		internal string? PropertyName;

		internal bool HasIndex;

		public JsonPosition(JsonContainerType type)
		{
			Type = type;
			HasIndex = TypeHasIndex(type);
			Position = -1;
			PropertyName = null;
		}

		internal int CalculateLength()
		{
			switch (Type)
			{
			case JsonContainerType.Object:
				return PropertyName.Length + 5;
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				return MathUtils.IntLength((ulong)Position) + 2;
			default:
				throw new ArgumentOutOfRangeException("Type");
			}
		}

		internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer)
		{
			switch (Type)
			{
			case JsonContainerType.Object:
			{
				string propertyName = PropertyName;
				if (propertyName.IndexOfAny(SpecialCharacters) != -1)
				{
					sb.Append("['");
					if (writer == null)
					{
						writer = new StringWriter(sb);
					}
					JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer);
					sb.Append("']");
				}
				else
				{
					if (sb.Length > 0)
					{
						sb.Append('.');
					}
					sb.Append(propertyName);
				}
				break;
			}
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				sb.Append('[');
				sb.Append(Position);
				sb.Append(']');
				break;
			}
		}

		internal static bool TypeHasIndex(JsonContainerType type)
		{
			if (type != JsonContainerType.Array)
			{
				return type == JsonContainerType.Constructor;
			}
			return true;
		}

		internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition)
		{
			int num = 0;
			if (positions != null)
			{
				for (int i = 0; i < positions.Count; i++)
				{
					num += positions[i].CalculateLength();
				}
			}
			if (currentPosition.HasValue)
			{
				num += currentPosition.GetValueOrDefault().CalculateLength();
			}
			StringBuilder stringBuilder = new StringBuilder(num);
			StringWriter writer = null;
			char[] buffer = null;
			if (positions != null)
			{
				foreach (JsonPosition position in positions)
				{
					position.WriteTo(stringBuilder, ref writer, ref buffer);
				}
			}
			currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer);
			return stringBuilder.ToString();
		}

		internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message)
		{
			if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
			{
				message = message.Trim();
				if (!StringUtils.EndsWith(message, '.'))
				{
					message += ".";
				}
				message += " ";
			}
			message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
			}
			message += ".";
			return message;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonPropertyAttribute : Attribute
	{
		internal NullValueHandling? _nullValueHandling;

		internal DefaultValueHandling? _defaultValueHandling;

		internal ReferenceLoopHandling? _referenceLoopHandling;

		internal ObjectCreationHandling? _objectCreationHandling;

		internal TypeNameHandling? _typeNameHandling;

		internal bool? _isReference;

		internal int? _order;

		internal Required? _required;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType { get; set; }

		public object[]? NamingStrategyParameters { get; set; }

		public NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling.GetValueOrDefault();
			}
			set
			{
				_nullValueHandling = value;
			}
		}

		public DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling.GetValueOrDefault();
			}
			set
			{
				_defaultValueHandling = value;
			}
		}

		public ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_referenceLoopHandling = value;
			}
		}

		public ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling.GetValueOrDefault();
			}
			set
			{
				_objectCreationHandling = value;
			}
		}

		public TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameHandling = value;
			}
		}

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public int Order
		{
			get
			{
				return _order.GetValueOrDefault();
			}
			set
			{
				_order = value;
			}
		}

		public Required Required
		{
			get
			{
				return _required.GetValueOrDefault();
			}
			set
			{
				_required = value;
			}
		}

		public string? PropertyName { get; set; }

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public JsonPropertyAttribute()
		{
		}

		public JsonPropertyAttribute(string propertyName)
		{
			PropertyName = propertyName;
		}
	}
	public abstract class JsonReader : IDisposable
	{
		protected internal enum State
		{
			Start,
			Complete,
			Property,
			ObjectStart,
			Object,
			ArrayStart,
			Array,
			Closed,
			PostValue,
			ConstructorStart,
			Constructor,
			Error,
			Finished
		}

		private JsonToken _tokenType;

		private object? _value;

		internal char _quoteChar;

		internal State _currentState;

		private JsonPosition _currentPosition;

		private CultureInfo? _culture;

		private DateTimeZoneHandling _dateTimeZoneHandling;

		private int? _maxDepth;

		private bool _hasExceededMaxDepth;

		internal DateParseHandling _dateParseHandling;

		internal FloatParseHandling _floatParseHandling;

		private string? _dateFormatString;

		private List<JsonPosition>? _stack;

		protected State CurrentState => _currentState;

		public bool CloseInput { get; set; }

		public bool SupportMultipleContent { get; set; }

		public virtual char QuoteChar
		{
			get
			{
				return _quoteChar;
			}
			protected internal set
			{
				_quoteChar = value;
			}
		}

		public DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling;
			}
			set
			{
				if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateTimeZoneHandling = value;
			}
		}

		public DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling;
			}
			set
			{
				if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateParseHandling = value;
			}
		}

		public FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling;
			}
			set
			{
				if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_floatParseHandling = value;
			}
		}

		public string? DateFormatString
		{
			get
			{
				return _dateFormatString;
			}
			set
			{
				_dateFormatString = value;
			}
		}

		public int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
			}
		}

		public virtual JsonToken TokenType => _tokenType;

		public virtual object? Value => _value;

		public virtual Type? ValueType => _value?.GetType();

		public virtual int Depth
		{
			get
			{
				int num = _stack?.Count ?? 0;
				if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
				{
					return num;
				}
				return num + 1;
			}
		}

		public virtual string Path
		{
			get
			{
				if (_currentPosition.Type == JsonContainerType.None)
				{
					return string.Empty;
				}
				JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null);
				return JsonPosition.BuildPath(_stack, currentPosition);
			}
		}

		public CultureInfo Culture
		{
			get
			{
				return _culture ?? CultureInfo.InvariantCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync();
		}

		public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (TokenType == JsonToken.PropertyName)
			{
				await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth)
				{
				}
			}
		}

		internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken)
		{
			if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
			{
				throw CreateUnexpectedEndException();
			}
		}

		public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean());
		}

		public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes());
		}

		internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken)
		{
			List<byte> buffer = new List<byte>();
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(buffer));
			byte[] array = buffer.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime());
		}

		public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset());
		}

		public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal());
		}

		public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return Task.FromResult(ReadAsDouble());
		}

		public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32());
		}

		public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString());
		}

		internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken)
		{
			bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (flag)
			{
				flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			return flag;
		}

		internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType = TokenType;
			if (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				return MoveToContentFromNonContentAsync(cancellationToken);
			}
			return AsyncUtils.True;
		}

		private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType;
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					return false;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment);
			return true;
		}

		internal JsonPosition GetPosition(int depth)
		{
			if (_stack != null && depth < _stack.Count)
			{
				return _stack[depth];
			}
			return _currentPosition;
		}

		protected JsonReader()
		{
			_currentState = State.Start;
			_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
			_dateParseHandling = DateParseHandling.DateTime;
			_floatParseHandling = FloatParseHandling.Double;
			_maxDepth = 64;
			CloseInput = true;
		}

		private void Push(JsonContainerType value)
		{
			UpdateScopeWithFinishedValue();
			if (_currentPosition.Type == JsonContainerType.None)
			{
				_currentPosition = new JsonPosition(value);
				return;
			}
			if (_stack == null)
			{
				_stack = new List<JsonPosition>();
			}
			_stack.Add(_currentPosition);
			_currentPosition = new JsonPosition(value);
			if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth)
			{
				return;
			}
			_hasExceededMaxDepth = true;
			throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
		}

		private JsonContainerType Pop()
		{
			JsonPosition currentPosition;
			if (_stack != null && _stack.Count > 0)
			{
				currentPosition = _currentPosition;
				_currentPosition = _stack[_stack.Count - 1];
				_stack.RemoveAt(_stack.Count - 1);
			}
			else
			{
				currentPosition = _currentPosition;
				_currentPosition = default(JsonPosition);
			}
			if (_maxDepth.HasValue && Depth <= _maxDepth)
			{
				_hasExceededMaxDepth = false;
			}
			return currentPosition.Type;
		}

		private JsonContainerType Peek()
		{
			return _currentPosition.Type;
		}

		public abstract bool Read();

		public virtual int? ReadAsInt32()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is int)
				{
					return (int)value;
				}
				int num;
				if (value is BigInteger bigInteger)
				{
					num = (int)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToInt32(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Integer, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadInt32String(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal int? ReadInt32String(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (int.TryParse(s, NumberStyles.Integer, Culture, out var result))
			{
				SetToken(JsonToken.Integer, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual string? ReadAsString()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.String:
				return (string)Value;
			default:
				if (JsonTokenUtils.IsPrimitiveToken(contentToken))
				{
					object value = Value;
					if (value != null)
					{
						string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture));
						SetToken(JsonToken.String, text, updateIndex: false);
						return text;
					}
				}
				throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		public virtual byte[]? ReadAsBytes()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.StartObject:
			{
				ReadIntoWrappedTypeObject();
				byte[] array2 = ReadAsBytes();
				ReaderReadAndAssert();
				if (TokenType != JsonToken.EndObject)
				{
					throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
				}
				SetToken(JsonToken.Bytes, array2, updateIndex: false);
				return array2;
			}
			case JsonToken.String:
			{
				string text = (string)Value;
				Guid g;
				byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray()));
				SetToken(JsonToken.Bytes, array3, updateIndex: false);
				return array3;
			}
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Bytes:
				if (Value is Guid guid)
				{
					byte[] array = guid.ToByteArray();
					SetToken(JsonToken.Bytes, array, updateIndex: false);
					return array;
				}
				return (byte[])Value;
			case JsonToken.StartArray:
				return ReadArrayIntoByteArray();
			default:
				throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal byte[] ReadArrayIntoByteArray()
		{
			List<byte> list = new List<byte>();
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(list));
			byte[] array = list.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer)
		{
			switch (TokenType)
			{
			case JsonToken.None:
				throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
			case JsonToken.Integer:
				buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
				return false;
			case JsonToken.EndArray:
				return true;
			case JsonToken.Comment:
				return false;
			default:
				throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		public virtual double? ReadAsDouble()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is double)
				{
					return (double)value;
				}
				double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger));
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDoubleString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal double? ReadDoubleString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual bool? ReadAsBoolean()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L));
				SetToken(JsonToken.Boolean, flag, updateIndex: false);
				return flag;
			}
			case JsonToken.String:
				return ReadBooleanString((string)Value);
			case JsonToken.Boolean:
				return (bool)Value;
			default:
				throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal bool? ReadBooleanString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (bool.TryParse(s, out var result))
			{
				SetToken(JsonToken.Boolean, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual decimal? ReadAsDecimal()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is decimal)
				{
					return (decimal)value;
				}
				decimal num;
				if (value is BigInteger bigInteger)
				{
					num = (decimal)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDecimalString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal decimal? ReadDecimalString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success)
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTime? ReadAsDateTime()
		{
			switch (GetContentToken())
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTimeOffset dateTimeOffset)
				{
					SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false);
				}
				return (DateTime)Value;
			case JsonToken.String:
				return ReadDateTimeString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		internal DateTime? ReadDateTimeString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTimeOffset? ReadAsDateTimeOffset()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTime dateTime)
				{
					SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false);
				}
				return (DateTimeOffset)Value;
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadDateTimeOffsetString(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal DateTimeOffset? ReadDateTimeOffsetString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		internal void ReaderReadAndAssert()
		{
			if (!Read())
			{
				throw CreateUnexpectedEndException();
			}
		}

		internal JsonReaderException CreateUnexpectedEndException()
		{
			return JsonReaderException.Create(this, "Unexpected end when reading JSON.");
		}

		internal void ReadIntoWrappedTypeObject()
		{
			ReaderReadAndAssert();
			if (Value != null && Value.ToString() == "$type")
			{
				ReaderReadAndAssert();
				if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
				{
					ReaderReadAndAssert();
					if (Value.ToString() == "$value")
					{
						return;
					}
				}
			}
			throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
		}

		public void Skip()
		{
			if (TokenType == JsonToken.PropertyName)
			{
				Read();
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (Read() && depth < Depth)
				{
				}
			}
		}

		protected void SetToken(JsonToken newToken)
		{
			SetToken(newToken, null, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value)
		{
			SetToken(newToken, value, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value, bool updateIndex)
		{
			_tokenType = newToken;
			_value = value;
			switch (newToken)
			{
			case JsonToken.StartObject:
				_currentState = State.ObjectStart;
				Push(JsonContainerType.Object);
				break;
			case JsonToken.StartArray:
				_currentState = State.ArrayStart;
				Push(JsonContainerType.Array);
				break;
			case JsonToken.StartConstructor:
				_currentState = State.ConstructorStart;
				Push(JsonContainerType.Constructor);
				break;
			case JsonToken.EndObject:
				ValidateEnd(JsonToken.EndObject);
				break;
			case JsonToken.EndArray:
				ValidateEnd(JsonToken.EndArray);
				break;
			case JsonToken.EndConstructor:
				ValidateEnd(JsonToken.EndConstructor);
				break;
			case JsonToken.PropertyName:
				_currentState = State.Property;
				_currentPosition.PropertyName = (string)value;
				break;
			case JsonToken.Raw:
			case JsonToken.Integer:
			case JsonToken.Float:
			case JsonToken.String:
			case JsonToken.Boolean:
			case JsonToken.Null:
			case JsonToken.Undefined:
			case JsonToken.Date:
			case JsonToken.Bytes:
				SetPostValueState(updateIndex);
				break;
			case JsonToken.Comment:
				break;
			}
		}

		internal void SetPostValueState(bool updateIndex)
		{
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
			if (updateIndex)
			{
				UpdateScopeWithFinishedValue();
			}
		}

		private void UpdateScopeWithFinishedValue()
		{
			if (_currentPosition.HasIndex)
			{
				_currentPosition.Position++;
			}
		}

		private void ValidateEnd(JsonToken endToken)
		{
			JsonContainerType jsonContainerType = Pop();
			if (GetTypeForCloseToken(endToken) != jsonContainerType)
			{
				throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType));
			}
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
		}

		protected void SetStateBasedOnCurrent()
		{
			JsonContainerType jsonContainerType = Peek();
			switch (jsonContainerType)
			{
			case JsonContainerType.Object:
				_currentState = State.Object;
				break;
			case JsonContainerType.Array:
				_currentState = State.Array;
				break;
			case JsonContainerType.Constructor:
				_currentState = State.Constructor;
				break;
			case JsonContainerType.None:
				SetFinished();
				break;
			default:
				throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType));
			}
		}

		private void SetFinished()
		{
			_currentState = ((!SupportMultipleContent) ? State.Finished : State.Start);
		}

		private JsonContainerType GetTypeForCloseToken(JsonToken token)
		{
			return token switch
			{
				JsonToken.EndObject => JsonContainerType.Object, 
				JsonToken.EndArray => JsonContainerType.Array, 
				JsonToken.EndConstructor => JsonContainerType.Constructor, 
				_ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), 
			};
		}

		void IDisposable.Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (_currentState != State.Closed && disposing)
			{
				Close();
			}
		}

		public virtual void Close()
		{
			_currentState = State.Closed;
			_tokenType = JsonToken.None;
			_value = null;
		}

		internal void ReadAndAssert()
		{
			if (!Read())
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter)
		{
			if (!ReadForType(contract, hasConverter))
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal bool ReadForType(JsonContract? contract, bool hasConverter)
		{
			if (hasConverter)
			{
				return Read();
			}
			switch (contract?.InternalReadType ?? ReadType.Read)
			{
			case ReadType.Read:
				return ReadAndMoveToContent();
			case ReadType.ReadAsInt32:
				ReadAsInt32();
				break;
			case ReadType.ReadAsInt64:
			{
				bool result = ReadAndMoveToContent();
				if (TokenType == JsonToken.Undefined)
				{
					throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long)));
				}
				return result;
			}
			case ReadType.ReadAsDecimal:
				ReadAsDecimal();
				break;
			case ReadType.ReadAsDouble:
				ReadAsDouble();
				break;
			case ReadType.ReadAsBytes:
				ReadAsBytes();
				break;
			case ReadType.ReadAsBoolean:
				ReadAsBoolean();
				break;
			case ReadType.ReadAsString:
				ReadAsString();
				break;
			case ReadType.ReadAsDateTime:
				ReadAsDateTime();
				break;
			case ReadType.ReadAsDateTimeOffset:
				ReadAsDateTimeOffset();
				break;
			default:
				throw new ArgumentOutOfRangeException();
			}
			return TokenType != JsonToken.None;
		}

		internal bool ReadAndMoveToContent()
		{
			if (Read())
			{
				return MoveToContent();
			}
			return false;
		}

		internal bool MoveToContent()
		{
			JsonToken tokenType = TokenType;
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				if (!Read())
				{
					return false;
				}
				tokenType = TokenType;
			}
			return true;
		}

		private JsonToken GetContentToken()
		{
			JsonToken tokenType;
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
					return JsonToken.None;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.Comment);
			return tokenType;
		}
	}
	[Serializable]
	public class JsonReaderException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonReaderException()
		{
		}

		public JsonReaderException(string message)
			: base(message)
		{
		}

		public JsonReaderException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public JsonReaderException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonReaderException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonReaderException(message, path, lineNumber, linePosition, ex);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonRequiredAttribute : Attribute
	{
	}
	[Serializable]
	public class JsonSerializationException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonSerializationException()
		{
		}

		public JsonSerializationException(string message)
			: base(message)
		{
		}

		public JsonSerializationException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public JsonSerializationException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonSerializationException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonSerializationException(message, path, lineNumber, linePosition, ex);
		}
	}
	[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
	[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
	public class JsonSerializer
	{
		internal TypeNameHandling _typeNameHandling;

		internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling;

		internal PreserveReferencesHandling _preserveReferencesHandling;

		internal ReferenceLoopHandling _referenceLoopHandling;

		internal MissingMemberHandling _missingMemberHandling;

		internal ObjectCreationHandling _objectCreationHandling;

		internal NullValueHandling _nullValueHandling;

		internal DefaultValueHandling _defaultValueHandling;

		internal ConstructorHandling _constructorHandling;

		internal MetadataPropertyHandling _metadataPropertyHandling;

		internal JsonConverterCollection? _converters;

		internal IContractResolver _contractResolver;

		internal ITraceWriter? _traceWriter;

		internal IEqualityComparer? _equalityComparer;

		internal ISerializationBinder _serializationBinder;

		internal StreamingContext _context;

		private IReferenceResolver? _referenceResolver;

		private Formatting? _formatting;

		private DateFormatHandling? _dateFormatHandling;

		private DateTimeZoneHandling? _dateTimeZoneHandling;

		private DateParseHandling? _dateParseHandling;

		private FloatFormatHandling? _floatFormatHandling;

		private FloatParseHandling? _floatParseHandling;

		private StringEscapeHandling? _stringEscapeHandling;

		private CultureInfo _culture;

		private int? _maxDepth;

		private bool _maxDepthSet;

		private bool? _checkAdditionalContent;

		private string? _dateFormatString;

		private bool _dateFormatStringSet;

		public virtual IReferenceResolver? ReferenceResolver
		{
			get
			{
				return GetReferenceResolver();
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Reference resolver cannot be null.");
				}
				_referenceResolver = value;
			}
		}

		[Obsolete("Binder is obsolete. Use SerializationBinder instead.")]
		public virtual SerializationBinder Binder
		{
			get
			{
				if (_serializationBinder is SerializationBinder result)
				{
					return result;
				}
				if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter)
				{
					return serializationBinderAdapter.SerializationBinder;
				}
				throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set.");
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value);
			}
		}

		public virtual ISerializationBinder SerializationBinder
		{
			get
			{
				return _serializationBinder;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = value;
			}
		}

		public virtual ITraceWriter? TraceWriter
		{
			get
			{
				return _traceWriter;
			}
			set
			{
				_traceWriter = value;
			}
		}

		public virtual IEqualityComparer? EqualityComparer
		{
			get
			{
				return _equalityComparer;
			}
			set
			{
				_equalityComparer = value;
			}
		}

		public virtual TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling;
			}
			set
			{
				if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameHandling = value;
			}
		}

		[Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")]
		public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
		{
			get
			{
				return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value;
			}
		}

		public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling
		{
			get
			{
				return _typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = value;
			}
		}

		public virtual PreserveReferencesHandling PreserveReferencesHandling
		{
			get
			{
				return _preserveReferencesHandling;
			}
			set
			{
				if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_preserveReferencesHandling = value;
			}
		}

		public virtual ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling;
			}
			set
			{
				if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_referenceLoopHandling = value;
			}
		}

		public virtual MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling;
			}
			set
			{
				if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_missingMemberHandling = value;
			}
		}

		public virtual NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling;
			}
			set
			{
				if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_nullValueHandling = value;
			}
		}

		public virtual DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling;
			}
			set
			{
				if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_defaultValueHandling = value;
			}
		}

		public virtual ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling;
			}
			set
			{
				if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_objectCreationHandling = value;
			}
		}

		public virtual ConstructorHandling ConstructorHandling
		{
			get
			{
				return _constructorHandling;
			}
			set
			{
				if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_constructorHandling = value;
			}
		}

		public virtual MetadataPropertyHandling MetadataPropertyHandling
		{
			get
			{
				return _metadataPropertyHandling;
			}
			set
			{
				if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_metadataPropertyHandling = value;
			}
		}

		public virtual JsonConverterCollection Converters
		{
			get
			{
				if (_converters == null)
				{
					_converters = new JsonConverterCollection();
				}
				return _converters;
			}
		}

		public virtual IContractResolver ContractResolver
		{
			get
			{
				return _contractResolver;
			}
			set
			{
				_contractResolver = value ?? DefaultContractResolver.Instance;
			}
		}

		public virtual StreamingContext Context
		{
			get
			{
				return _context;
			}
			set
			{
				_context = value;
			}
		}

		public virtual Formatting Formatting
		{
			get
			{
				return _formatting.GetValueOrDefault();
			}
			set
			{
				_formatting = value;
			}
		}

		public virtual DateFormatHandling DateFormatHandling
		{
			get
			{
				return _dateFormatHandling.GetValueOrDefault();
			}
			set
			{
				_dateFormatHandling = value;
			}
		}

		public virtual DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling.GetValueOrDefault(DateTimeZoneHandling.RoundtripKind);
			}
			set
			{
				_dateTimeZoneHandling = value;
			}
		}

		public virtual DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling.GetValueOrDefault(DateParseHandling.DateTime);
			}
			set
			{
				_dateParseHandling = value;
			}
		}

		public virtual FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling.GetValueOrDefault();
			}
			set
			{
				_floatParseHandling = value;
			}
		}

		public virtual FloatFormatHandling FloatFormatHandling
		{
			get
			{
				return _floatFormatHandling.GetValueOrDefault();
			}
			set
			{
				_floatFormatHandling = value;
			}
		}

		public virtual StringEscapeHandling StringEscapeHandling
		{
			get
			{
				return _stringEscapeHandling.GetValueOrDefault();
			}
			set
			{
				_stringEscapeHandling = value;
			}
		}

		public virtual string DateFormatString
		{
			get
			{
				return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
			}
			set
			{
				_dateFormatString = value;
				_dateFormatStringSet = true;
			}
		}

		public virtual CultureInfo Culture
		{
			get
			{
				return _culture ?? JsonSerializerSettings.DefaultCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
				_maxDepthSet = true;
			}
		}

		public virtual bool CheckAdditionalContent
		{
			get
			{
				return _checkAdditionalContent.GetValueOrDefault();
			}
			set
			{
				_checkAdditionalContent = value;
			}
		}

		public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error;

		internal bool IsCheckAdditionalContentSet()
		{
			return _checkAdditionalContent.HasValue;
		}

		public JsonSerializer()
		{
			_referenceLoopHandling = ReferenceLoopHandling.Error;
			_missingMemberHandling = MissingMemberHandling.Ignore;
			_nullValueHandling = NullValueHandling.Include;
			_defaultValueHandling = DefaultValueHandling.Include;
			_objectCreationHandling = ObjectCreationHandling.Auto;
			_preserveReferencesHandling = PreserveReferencesHandling.None;
			_constructorHandling = ConstructorHandling.Default;
			_typeNameHandling = TypeNameHandling.None;
			_metadataPropertyHandling = MetadataPropertyHandling.Default;
			_context = JsonSerializerSettings.DefaultContext;
			_serializationBinder = DefaultSerializationBinder.Instance;
			_culture = JsonSerializerSettings.DefaultCulture;
			_contractResolver = DefaultContractResolver.Instance;
		}

		public static JsonSerializer Create()
		{
			return new JsonSerializer();
		}

		public static JsonSerializer Create(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = Create();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		public static JsonSerializer CreateDefault()
		{
			return Create(JsonConvert.DefaultSettings?.Invoke());
		}

		public static JsonSerializer CreateDefault(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = CreateDefault();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings)
		{
			if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
			{
				for (int i = 0; i < settings.Converters.Count; i++)
				{
					serializer.Converters.Insert(i, settings.Converters[i]);
				}
			}
			if (settings._typeNameHandling.HasValue)
			{
				serializer.TypeNameHandling = settings.TypeNameHandling;
			}
			if (settings._metadataPropertyHandling.HasValue)
			{
				serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling;
			}
			if (settings._typeNameAssemblyFormatHandling.HasValue)
			{
				serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling;
			}
			if (settings._preserveReferencesHandling.HasValue)
			{
				serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
			}
			if (settings._referenceLoopHandling.HasValue)
			{
				serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
			}
			if (settings._missingMemberHandling.HasValue)
			{
				serializer.MissingMemberHandling = settings.MissingMemberHandling;
			}
			if (settings._objectCreationHandling.HasValue)
			{
				serializer.ObjectCreationHandling = settings.ObjectCreationHandling;
			}
			if (settings._nullValueHandling.HasValue)
			{
				serializer.NullValueHandling = settings.NullValueHandling;
			}
			if (settings._defaultValueHandling.HasValue)
			{
				serializer.DefaultValueHandling = settings.DefaultValueHandling;
			}
			if (settings._constructorHandling.HasValue)
			{
				serializer.ConstructorHandling = settings.ConstructorHandling;
			}
			if (settings._context.HasValue)
			{
				serializer.Context = settings.Context;
			}
			if (settings._checkAdditionalContent.HasValue)
			{
				serializer._checkAdditionalContent = settings._checkAdditionalContent;
			}
			if (settings.Error != null)
			{
				serializer.Error += settings.Error;
			}
			if (settings.ContractResolver != null)
			{
				serializer.ContractResolver = settings.ContractResolver;
			}
			if (settings.ReferenceResolverProvider != null)
			{
				serializer.ReferenceResolver = settings.ReferenceResolverProvider();
			}
			if (settings.TraceWriter != null)
			{
				serializer.TraceWriter = settings.TraceWriter;
			}
			if (settings.EqualityComparer != null)
			{
				serializer.EqualityComparer = settings.EqualityComparer;
			}
			if (settings.SerializationBinder != null)
			{
				serializer.SerializationBinder = settings.SerializationBinder;
			}
			if (settings._formatting.HasValue)
			{
				serializer._formatting = settings._formatting;
			}
			if (settings._dateFormatHandling.HasValue)
			{
				serializer._dateFormatHandling = settings._dateFormatHandling;
			}
			if (settings._dateTimeZoneHandling.HasValue)
			{
				serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling;
			}
			if (settings._dateParseHandling.HasValue)
			{
				serializer._dateParseHandling = settings._dateParseHandling;
			}
			if (settings._dateFormatStringSet)
			{
				serializer._dateFormatString = settings._dateFormatString;
				serializer._dateFormatStringSet = settings._dateFormatStringSet;
			}
			if (settings._floatFormatHandling.HasValue)
			{
				serializer._floatFormatHandling = settings._floatFormatHandling;
			}
			if (settings._floatParseHandling.HasValue)
			{
				serializer._floatParseHandling = settings._floatParseHandling;
			}
			if (settings._stringEscapeHandling.HasValue)
			{
				serializer._stringEscapeHandling = settings._stringEscapeHandling;
			}
			if (settings._culture != null)
			{
				serializer._culture = settings._culture;
			}
			if (settings._maxDepthSet)
			{
				serializer._maxDepth = settings._maxDepth;
				serializer._maxDepthSet = settings._maxDepthSet;
			}
		}

		[DebuggerStepThrough]
		public void Populate(TextReader reader, object target)
		{
			Populate(new JsonTextReader(reader), target);
		}

		[DebuggerStepThrough]
		public void Populate(JsonReader reader, object target)
		{
			PopulateInternal(reader, target);
		}

		internal virtual void PopulateInternal(JsonReader reader, object target)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			ValidationUtils.ArgumentNotNull(target, "target");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader)
		{
			return Deserialize(reader, null);
		}

		[DebuggerStepThrough]
		public object? Deserialize(TextReader reader, Type objectType)
		{
			return Deserialize(new JsonTextReader(reader), objectType);
		}

		[DebuggerStepThrough]
		public T? Deserialize<T>(JsonReader reader)
		{
			return (T)Deserialize(reader, typeof(T));
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader, Type? objectType)
		{
			return DeserializeInternal(reader, objectType);
		}

		internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
			return result;
		}

		internal void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString)
		{
			if (_culture != null && !_culture.Equals(reader.Culture))
			{
				previousCulture = reader.Culture;
				reader.Culture = _culture

plugins/Spherewright.Bridge.Core.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Spherewright.Bridge.Core.Snapshots;
using Spherewright.Contracts.Errors;
using Spherewright.Contracts.Factory;
using Spherewright.Contracts.Logistics;
using Spherewright.Contracts.Players;
using Spherewright.Contracts.Progression;
using Spherewright.Contracts.Protocol;
using Spherewright.Contracts.Resources;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Spherewright.Bridge.Core")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.3.0")]
[assembly: AssemblyInformationalVersion("0.3.3+f0cd11105957ae63cb4b45fd5756b0a42508857f")]
[assembly: AssemblyProduct("Spherewright.Bridge.Core")]
[assembly: AssemblyTitle("Spherewright.Bridge.Core")]
[assembly: AssemblyVersion("0.3.3.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Spherewright.Bridge.Core.Snapshots
{
	public static class OpaqueToken
	{
		public static string Create(int byteCount = 32)
		{
			if (byteCount < 32)
			{
				throw new ArgumentOutOfRangeException("byteCount", "Opaque tokens must contain at least 256 bits of entropy.");
			}
			byte[] array = new byte[byteCount];
			using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create())
			{
				randomNumberGenerator.GetBytes(array);
			}
			return Convert.ToBase64String(array).TrimEnd(new char[1] { '=' }).Replace('+', '-')
				.Replace('/', '_');
		}
	}
	public enum SnapshotCursorStatus
	{
		Success,
		Missing,
		Stale,
		Expired
	}
	public sealed class SnapshotPage<T>
	{
		public string SnapshotId { get; }

		public DateTimeOffset ExpiresAtUtc { get; }

		public IReadOnlyList<T> Items { get; }

		public string? NextCursor { get; }

		public SnapshotPage(string snapshotId, DateTimeOffset expiresAtUtc, IReadOnlyList<T> items, string? nextCursor)
		{
			SnapshotId = snapshotId;
			ExpiresAtUtc = expiresAtUtc;
			Items = items;
			NextCursor = nextCursor;
		}
	}
	public sealed class SnapshotPageStore<T>
	{
		private sealed class SnapshotRecord
		{
			public string Id { get; }

			public string SessionId { get; }

			public int PlanetId { get; }

			public string FilterHash { get; }

			public int PageSize { get; }

			public DateTimeOffset ExpiresAtUtc { get; }

			public IReadOnlyList<T> Items { get; }

			public Dictionary<int, string> CursorsByOffset { get; } = new Dictionary<int, string>();

			public SnapshotRecord(string id, string sessionId, int planetId, string filterHash, int pageSize, DateTimeOffset expiresAtUtc, IReadOnlyList<T> items)
			{
				Id = id;
				SessionId = sessionId;
				PlanetId = planetId;
				FilterHash = filterHash;
				PageSize = pageSize;
				ExpiresAtUtc = expiresAtUtc;
				Items = items;
			}
		}

		private sealed class CursorRecord
		{
			public string SnapshotId { get; }

			public int Offset { get; }

			public CursorRecord(string snapshotId, int offset)
			{
				SnapshotId = snapshotId;
				Offset = offset;
			}
		}

		private readonly object _gate = new object();

		private readonly Dictionary<string, SnapshotRecord> _snapshots = new Dictionary<string, SnapshotRecord>(StringComparer.Ordinal);

		private readonly Dictionary<string, CursorRecord> _cursors = new Dictionary<string, CursorRecord>(StringComparer.Ordinal);

		private readonly TimeSpan _lifetime;

		private readonly int _capacity;

		private readonly Func<DateTimeOffset> _utcNow;

		public SnapshotPageStore(TimeSpan lifetime, int capacity, Func<DateTimeOffset>? utcNow = null)
		{
			if (lifetime <= TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("lifetime");
			}
			if (capacity <= 0)
			{
				throw new ArgumentOutOfRangeException("capacity");
			}
			_lifetime = lifetime;
			_capacity = capacity;
			_utcNow = utcNow ?? ((Func<DateTimeOffset>)(() => DateTimeOffset.UtcNow));
		}

		public bool TryCreate(string sessionId, int planetId, string filterHash, IReadOnlyList<T> items, int pageSize, out SnapshotPage<T>? page)
		{
			ValidateBinding(sessionId, planetId, filterHash, pageSize);
			if (items == null)
			{
				throw new ArgumentNullException("items");
			}
			lock (_gate)
			{
				RemoveExpiredUnsafe();
				if (_snapshots.Count >= _capacity)
				{
					page = null;
					return false;
				}
				DateTimeOffset dateTimeOffset = _utcNow();
				SnapshotRecord snapshotRecord = new SnapshotRecord(OpaqueToken.Create(), sessionId, planetId, filterHash, pageSize, dateTimeOffset.Add(_lifetime), items.ToArray());
				_snapshots.Add(snapshotRecord.Id, snapshotRecord);
				page = CreatePageUnsafe(snapshotRecord, 0);
				return true;
			}
		}

		public SnapshotCursorStatus TryGetPage(string? cursor, string sessionId, int planetId, string filterHash, int pageSize, out SnapshotPage<T>? page)
		{
			ValidateBinding(sessionId, planetId, filterHash, pageSize);
			page = null;
			if (string.IsNullOrWhiteSpace(cursor))
			{
				return SnapshotCursorStatus.Missing;
			}
			lock (_gate)
			{
				if (!_cursors.TryGetValue(cursor, out CursorRecord value) || !_snapshots.TryGetValue(value.SnapshotId, out SnapshotRecord value2))
				{
					return SnapshotCursorStatus.Missing;
				}
				if (value2.ExpiresAtUtc <= _utcNow())
				{
					RemoveSnapshotUnsafe(value2.Id);
					return SnapshotCursorStatus.Expired;
				}
				if (!string.Equals(value2.SessionId, sessionId, StringComparison.Ordinal) || value2.PlanetId != planetId || !string.Equals(value2.FilterHash, filterHash, StringComparison.Ordinal) || value2.PageSize != pageSize)
				{
					return SnapshotCursorStatus.Stale;
				}
				page = CreatePageUnsafe(value2, value.Offset);
				return SnapshotCursorStatus.Success;
			}
		}

		public void Clear()
		{
			lock (_gate)
			{
				_cursors.Clear();
				_snapshots.Clear();
			}
		}

		private SnapshotPage<T> CreatePageUnsafe(SnapshotRecord snapshot, int offset)
		{
			int num = Math.Min(snapshot.PageSize, Math.Max(0, snapshot.Items.Count - offset));
			T[] array = new T[num];
			for (int i = 0; i < num; i++)
			{
				array[i] = snapshot.Items[offset + i];
			}
			int num2 = offset + num;
			string text = null;
			if (num2 < snapshot.Items.Count)
			{
				text = (snapshot.CursorsByOffset.TryGetValue(num2, out string value) ? value : OpaqueToken.Create());
				snapshot.CursorsByOffset[num2] = text;
				_cursors[text] = new CursorRecord(snapshot.Id, num2);
			}
			return new SnapshotPage<T>(snapshot.Id, snapshot.ExpiresAtUtc, array, text);
		}

		private void RemoveExpiredUnsafe()
		{
			DateTimeOffset now = _utcNow();
			string[] array = (from pair in _snapshots
				where pair.Value.ExpiresAtUtc <= now
				select pair.Key).ToArray();
			foreach (string snapshotId in array)
			{
				RemoveSnapshotUnsafe(snapshotId);
			}
		}

		private void RemoveSnapshotUnsafe(string snapshotId)
		{
			if (!_snapshots.TryGetValue(snapshotId, out SnapshotRecord value))
			{
				return;
			}
			_snapshots.Remove(snapshotId);
			foreach (string value2 in value.CursorsByOffset.Values)
			{
				_cursors.Remove(value2);
			}
		}

		private static void ValidateBinding(string sessionId, int planetId, string filterHash, int pageSize)
		{
			if (string.IsNullOrWhiteSpace(sessionId))
			{
				throw new ArgumentException("A snapshot session ID is required.", "sessionId");
			}
			if (planetId <= 0)
			{
				throw new ArgumentOutOfRangeException("planetId");
			}
			if (string.IsNullOrWhiteSpace(filterHash))
			{
				throw new ArgumentException("A snapshot filter hash is required.", "filterHash");
			}
			if (pageSize <= 0)
			{
				throw new ArgumentOutOfRangeException("pageSize");
			}
		}
	}
}
namespace Spherewright.Bridge.Core.Safety
{
	public static class BeltConnectionProof
	{
		public static bool OutputMatches(int expectedObjectId, bool actualIsOutput, int actualObjectId)
		{
			if (expectedObjectId > 0)
			{
				if (actualIsOutput)
				{
					return actualObjectId == expectedObjectId;
				}
				return false;
			}
			return actualObjectId == 0;
		}
	}
	public static class BuildConnectionSlots
	{
		public static IReadOnlyList<int> SelectAvailable(int slotCount, IEnumerable<int> occupiedSlots)
		{
			if (slotCount < 0)
			{
				throw new ArgumentOutOfRangeException("slotCount");
			}
			if (occupiedSlots == null)
			{
				throw new ArgumentNullException("occupiedSlots");
			}
			HashSet<int> hashSet = new HashSet<int>(occupiedSlots.Where((int slot) => slot >= 0 && slot < slotCount));
			List<int> list = new List<int>(Math.Max(0, slotCount - hashSet.Count));
			for (int num = 0; num < slotCount; num++)
			{
				if (!hashSet.Contains(num))
				{
					list.Add(num);
				}
			}
			return list;
		}

		public static IReadOnlyList<int> SelectVerificationCandidates(int preparedSlot, int connectionSlotCount)
		{
			if (connectionSlotCount < 0)
			{
				throw new ArgumentOutOfRangeException("connectionSlotCount");
			}
			if (preparedSlot >= 0)
			{
				if (preparedSlot >= connectionSlotCount)
				{
					return Array.Empty<int>();
				}
				return new int[1] { preparedSlot };
			}
			return Enumerable.Range(0, connectionSlotCount).ToArray();
		}
	}
	public readonly struct BuildEntityCandidate
	{
		public int EntityId { get; }

		public float SquaredDistance { get; }

		public BuildEntityCandidate(int entityId, float squaredDistance)
		{
			EntityId = entityId;
			SquaredDistance = squaredDistance;
		}
	}
	public readonly struct DirectedBuildEntityCandidate
	{
		public int EntityId { get; }

		public int InputObjectId { get; }

		public int OutputObjectId { get; }

		public float SquaredDistance { get; }

		public DirectedBuildEntityCandidate(int entityId, int inputObjectId, int outputObjectId, float squaredDistance)
		{
			EntityId = entityId;
			InputObjectId = inputObjectId;
			OutputObjectId = outputObjectId;
			SquaredDistance = squaredDistance;
		}
	}
	public static class BuildEntityAttribution
	{
		public static int SelectNearestNewCandidate(IEnumerable<BuildEntityCandidate> candidates, IReadOnlyCollection<int> preexistingEntityIds, IReadOnlyCollection<int> alreadySelectedEntityIds, float maximumSquaredDistance)
		{
			if (candidates == null)
			{
				throw new ArgumentNullException("candidates");
			}
			if (preexistingEntityIds == null)
			{
				throw new ArgumentNullException("preexistingEntityIds");
			}
			if (alreadySelectedEntityIds == null)
			{
				throw new ArgumentNullException("alreadySelectedEntityIds");
			}
			if (maximumSquaredDistance <= 0f || float.IsNaN(maximumSquaredDistance) || float.IsInfinity(maximumSquaredDistance))
			{
				throw new ArgumentOutOfRangeException("maximumSquaredDistance");
			}
			int result = 0;
			float num = maximumSquaredDistance;
			foreach (BuildEntityCandidate candidate in candidates)
			{
				if (candidate.EntityId > 0 && !(candidate.SquaredDistance < 0f) && !float.IsNaN(candidate.SquaredDistance) && !float.IsInfinity(candidate.SquaredDistance) && !preexistingEntityIds.Contains(candidate.EntityId) && !alreadySelectedEntityIds.Contains(candidate.EntityId) && candidate.SquaredDistance < num)
				{
					num = candidate.SquaredDistance;
					result = candidate.EntityId;
				}
			}
			return result;
		}

		public static bool TrySelectUniqueDirectedPath(IReadOnlyList<IReadOnlyList<DirectedBuildEntityCandidate>> candidatesByStep, IReadOnlyCollection<int> excludedEntityIds, int sourceObjectId, int destinationObjectId, float maximumSquaredDistance, out IReadOnlyList<int> selectedEntityIds)
		{
			if (candidatesByStep == null)
			{
				throw new ArgumentNullException("candidatesByStep");
			}
			if (excludedEntityIds == null)
			{
				throw new ArgumentNullException("excludedEntityIds");
			}
			if (maximumSquaredDistance <= 0f || float.IsNaN(maximumSquaredDistance) || float.IsInfinity(maximumSquaredDistance))
			{
				throw new ArgumentOutOfRangeException("maximumSquaredDistance");
			}
			selectedEntityIds = Array.Empty<int>();
			if (candidatesByStep.Count == 0 || candidatesByStep.Any((IReadOnlyList<DirectedBuildEntityCandidate> step) => step == null))
			{
				return false;
			}
			int[] current = new int[candidatesByStep.Count];
			int[] unique = null;
			int solutionCount = 0;
			Search(0, sourceObjectId);
			if (solutionCount != 1 || unique == null)
			{
				return false;
			}
			selectedEntityIds = unique;
			return true;
			void Search(int stepIndex, int expectedInputObjectId)
			{
				if (solutionCount <= 1)
				{
					if (stepIndex != candidatesByStep.Count)
					{
						foreach (DirectedBuildEntityCandidate item in candidatesByStep[stepIndex])
						{
							if (item.EntityId > 0 && !(item.SquaredDistance < 0f) && !(item.SquaredDistance >= maximumSquaredDistance) && !float.IsNaN(item.SquaredDistance) && !float.IsInfinity(item.SquaredDistance) && !excludedEntityIds.Contains(item.EntityId) && !current.Take(stepIndex).Contains(item.EntityId) && (expectedInputObjectId <= 0 || item.InputObjectId == expectedInputObjectId))
							{
								if (stepIndex + 1 < candidatesByStep.Count)
								{
									if (item.OutputObjectId <= 0)
									{
										continue;
									}
								}
								else if (destinationObjectId > 0 && item.OutputObjectId != destinationObjectId)
								{
									continue;
								}
								current[stepIndex] = item.EntityId;
								Search(stepIndex + 1, item.EntityId);
								current[stepIndex] = 0;
							}
						}
						return;
					}
					if (destinationObjectId <= 0 || candidatesByStep.Count <= 0 || candidatesByStep[candidatesByStep.Count - 1].Any((DirectedBuildEntityCandidate candidate) => candidate.EntityId == current[current.Length - 1] && candidate.OutputObjectId == destinationObjectId))
					{
						solutionCount++;
						unique = current.ToArray();
					}
				}
			}
		}
	}
	public static class CanonicalStateHash
	{
		public const int Version = 1;

		public static string Player(PlayerStateSnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, "player-v1", snapshot.SessionId, snapshot.PlanetId, snapshot.IsAlive, snapshot.IsOnPlanet, snapshot.MovementState, F(snapshot.Position.X), F(snapshot.Position.Y), F(snapshot.Position.Z), F(snapshot.CoreEnergy), F(snapshot.CoreEnergyCapacity), snapshot.InventorySlotCount, snapshot.InventoryOccupiedSlotCount, F(snapshot.ReactorEnergy), snapshot.ReactorItemId, snapshot.ReactorItemInc, snapshot.AutoReplenishFuel, snapshot.FuelStorageSlotCount, snapshot.FuelStorageOccupiedSlotCount);
			foreach (PlayerInventoryItem item in snapshot.Inventory.OrderBy((PlayerInventoryItem item) => item.ItemId))
			{
				Append(stringBuilder, "inventory", item.ItemId, item.Count, item.Inc, item.SlotCount);
			}
			foreach (PlayerInventoryItem item2 in snapshot.FuelStorage.OrderBy((PlayerInventoryItem item) => item.ItemId))
			{
				Append(stringBuilder, "fuel", item2.ItemId, item2.Count, item2.Inc, item2.SlotCount);
			}
			if (snapshot.InHandItem != null)
			{
				Append(stringBuilder, "hand", snapshot.InHandItem.ItemId, snapshot.InHandItem.Count, snapshot.InHandItem.Inc, snapshot.InHandItem.SlotCount);
			}
			foreach (HandcraftTaskSnapshot item3 in snapshot.HandcraftQueue.OrderBy((HandcraftTaskSnapshot task) => task.QueueIndex))
			{
				Append(stringBuilder, "forge", item3.QueueIndex, item3.RecipeId, item3.RemainingCraftCount, item3.Progress, item3.ProgressRequired, item3.ParentTaskIndex, item3.IngredientsReserved);
				foreach (PlayerItemAmount item4 in item3.Inputs.OrderBy((PlayerItemAmount item) => item.ItemId))
				{
					Append(stringBuilder, "forge-in", item4.ItemId, item4.Count, item4.BufferedCount);
				}
				foreach (PlayerItemAmount item5 in item3.Outputs.OrderBy((PlayerItemAmount item) => item.ItemId))
				{
					Append(stringBuilder, "forge-out", item5.ItemId, item5.Count, item5.BufferedCount);
				}
			}
			Append(stringBuilder, "drones", snapshot.ConstructionDrones.Enabled, snapshot.ConstructionDrones.ConstructionEnabled, snapshot.ConstructionDrones.Total, snapshot.ConstructionDrones.Alive, snapshot.ConstructionDrones.Idle, snapshot.ConstructionDrones.PendingBuildTargets, snapshot.ConstructionDrones.PendingRepairTargets);
			return Hash(stringBuilder);
		}

		public static string PlayerAction(PlayerStateSnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, "player-action-v1", snapshot.SessionId, snapshot.PlanetId, snapshot.IsAlive, snapshot.IsOnPlanet, snapshot.MovementState, Q(snapshot.Position.X), Q(snapshot.Position.Y), Q(snapshot.Position.Z), snapshot.CoreEnergy > 0.0, snapshot.CoreEnergyCapacity > 0.0, snapshot.InventorySlotCount, snapshot.InventoryOccupiedSlotCount, snapshot.ReactorEnergy > 0.0, snapshot.ReactorItemId, snapshot.ReactorItemInc, snapshot.AutoReplenishFuel, snapshot.FuelStorageSlotCount, snapshot.FuelStorageOccupiedSlotCount);
			foreach (PlayerInventoryItem item in snapshot.Inventory.OrderBy((PlayerInventoryItem item) => item.ItemId))
			{
				Append(stringBuilder, "inventory", item.ItemId, item.Count, item.Inc, item.SlotCount);
			}
			foreach (PlayerInventoryItem item2 in snapshot.FuelStorage.OrderBy((PlayerInventoryItem item) => item.ItemId))
			{
				Append(stringBuilder, "fuel", item2.ItemId, item2.Count, item2.Inc, item2.SlotCount);
			}
			if (snapshot.InHandItem != null)
			{
				Append(stringBuilder, "hand", snapshot.InHandItem.ItemId, snapshot.InHandItem.Count, snapshot.InHandItem.Inc, snapshot.InHandItem.SlotCount);
			}
			foreach (HandcraftTaskSnapshot item3 in snapshot.HandcraftQueue.OrderBy((HandcraftTaskSnapshot task) => task.QueueIndex))
			{
				Append(stringBuilder, "forge", item3.QueueIndex, item3.RecipeId, item3.RemainingCraftCount, item3.Progress, item3.ProgressRequired, item3.ParentTaskIndex, item3.IngredientsReserved);
			}
			Append(stringBuilder, "drones", snapshot.ConstructionDrones.Enabled, snapshot.ConstructionDrones.ConstructionEnabled, snapshot.ConstructionDrones.Total, snapshot.ConstructionDrones.Alive, snapshot.ConstructionDrones.Idle, snapshot.ConstructionDrones.PendingBuildTargets, snapshot.ConstructionDrones.PendingRepairTargets);
			return Hash(stringBuilder);
		}

		public static string Resource(ResourceNodeSnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, "resource-v1", snapshot.SessionId, snapshot.PlanetId, snapshot.Kind, snapshot.NodeId, snapshot.ResourceType, snapshot.ProtoId, snapshot.RemainingAmount, snapshot.GroupIndex, snapshot.MinerCount, F(snapshot.Position.X), F(snapshot.Position.Y), F(snapshot.Position.Z));
			foreach (ResourceYieldSnapshot item in snapshot.Yields.OrderBy((ResourceYieldSnapshot item) => item.ItemId))
			{
				Append(stringBuilder, "yield", item.ItemId, item.Count, F(item.Chance));
			}
			return Hash(stringBuilder);
		}

		public static string Progression(ProgressionStateSnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, "progression-v1", snapshot.SessionId, snapshot.PlanetId, snapshot.CurrentTechId);
			foreach (int item in snapshot.TechQueue)
			{
				Append(stringBuilder, "queue", item);
			}
			foreach (TechStateSnapshot item2 in snapshot.Technologies.OrderBy((TechStateSnapshot tech) => tech.TechId))
			{
				Append(stringBuilder, "tech", item2.TechId, item2.Unlocked, item2.CurrentLevel, item2.MaximumLevel, item2.HashUploaded, item2.HashRequired, item2.IsLabTech, item2.IsQueued);
			}
			return Hash(stringBuilder);
		}

		public static string Factory(FactoryEntitySnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, "factory-v1", snapshot.SessionId, snapshot.PlanetId, snapshot.ObjectId, snapshot.ObjectKind, snapshot.ItemId, snapshot.ComponentKind, F(snapshot.Position.X), F(snapshot.Position.Y), F(snapshot.Position.Z), snapshot.RecipeId, snapshot.IsWorking, snapshot.Progress, snapshot.ProgressRequired, snapshot.PowerNetworkId, snapshot.PickTargetObjectId, snapshot.InsertTargetObjectId, snapshot.FilterItemId, snapshot.InserterStage, snapshot.InserterStackCount, snapshot.RequiredBuildItemCount, snapshot.ConstructionProgress.HasValue ? F(snapshot.ConstructionProgress.Value) : string.Empty);
			foreach (FactoryConnectionSnapshot item in snapshot.Connections.OrderBy((FactoryConnectionSnapshot connection) => connection.Slot))
			{
				Append(stringBuilder, "connection", item.Slot, item.IsOutput, item.OtherObjectId, item.OtherSlot);
			}
			foreach (FactoryBufferSnapshot item2 in snapshot.Buffers.OrderBy<FactoryBufferSnapshot, string>((FactoryBufferSnapshot buffer) => buffer.Role, StringComparer.Ordinal).ThenBy((FactoryBufferSnapshot buffer) => buffer.ItemId))
			{
				Append(stringBuilder, "buffer", item2.Role, item2.ItemId, item2.Count, item2.Inc);
			}
			foreach (int item3 in snapshot.ResourceNodeIds.OrderBy((int id) => id))
			{
				Append(stringBuilder, "node", item3);
			}
			return Hash(stringBuilder);
		}

		public static string FactoryEndpoint(FactoryEntitySnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, "factory-endpoint-v1", snapshot.SessionId, snapshot.PlanetId, snapshot.ObjectId, snapshot.ObjectKind, snapshot.ItemId, snapshot.ComponentKind, F(snapshot.Position.X), F(snapshot.Position.Y), F(snapshot.Position.Z), F(snapshot.Rotation.X), F(snapshot.Rotation.Y), F(snapshot.Rotation.Z), F(snapshot.Rotation.W));
			foreach (FactoryConnectionSnapshot item in snapshot.Connections.OrderBy((FactoryConnectionSnapshot connection) => connection.Slot))
			{
				Append(stringBuilder, "connection", item.Slot, item.IsOutput, item.OtherObjectId, item.OtherSlot);
			}
			return Hash(stringBuilder);
		}

		public static string FactoryConfiguration(FactoryEntitySnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, "factory-configuration-v1", snapshot.SessionId, snapshot.PlanetId, snapshot.ObjectId, snapshot.ObjectKind, snapshot.ItemId, snapshot.ComponentKind, F(snapshot.Position.X), F(snapshot.Position.Y), F(snapshot.Position.Z), F(snapshot.Rotation.X), F(snapshot.Rotation.Y), F(snapshot.Rotation.Z), F(snapshot.Rotation.W), snapshot.RecipeId, snapshot.PickTargetObjectId, snapshot.InsertTargetObjectId, snapshot.FilterItemId, snapshot.InserterStackCount);
			foreach (FactoryConnectionSnapshot item in snapshot.Connections.OrderBy((FactoryConnectionSnapshot connection) => connection.Slot))
			{
				Append(stringBuilder, "connection", item.Slot, item.IsOutput, item.OtherObjectId, item.OtherSlot);
			}
			foreach (FactoryBufferSnapshot item2 in snapshot.Buffers.OrderBy<FactoryBufferSnapshot, string>((FactoryBufferSnapshot buffer) => buffer.Role, StringComparer.Ordinal).ThenBy((FactoryBufferSnapshot buffer) => buffer.ItemId))
			{
				Append(stringBuilder, "buffer", item2.Role, item2.ItemId, item2.Count, item2.Inc);
			}
			return Hash(stringBuilder);
		}

		public static string ProgressionSelection(ProgressionStateSnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, "progression-selection-v1", snapshot.SessionId, snapshot.PlanetId, snapshot.CurrentTechId);
			foreach (int item in snapshot.TechQueue)
			{
				Append(stringBuilder, "queue", item);
			}
			foreach (TechStateSnapshot item2 in snapshot.Technologies.OrderBy((TechStateSnapshot tech) => tech.TechId))
			{
				Append(stringBuilder, "tech", item2.TechId, item2.Unlocked, item2.CurrentLevel, item2.MaximumLevel, item2.HashRequired, item2.IsLabTech, item2.IsQueued);
				foreach (int item3 in item2.PrerequisiteTechIds.OrderBy((int id) => id))
				{
					Append(stringBuilder, "prerequisite", item2.TechId, item3);
				}
			}
			return Hash(stringBuilder);
		}

		public static string LogisticsStation(LogisticsStationSnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			AppendLogisticsStationConfiguration(stringBuilder, snapshot, "logistics-station-v1");
			Append(stringBuilder, "live", snapshot.PowerServeRatio, snapshot.Energy, snapshot.RequestedChargeEnergyPerTick, snapshot.RequestedChargePowerWatts, snapshot.WarperCount, snapshot.IdleDroneCount, snapshot.WorkingDroneCount, snapshot.IdleVesselCount, snapshot.WorkingVesselCount);
			foreach (LogisticsStationStorageSlotSnapshot item in snapshot.StorageSlots.OrderBy((LogisticsStationStorageSlotSnapshot slot) => slot.Index))
			{
				Append(stringBuilder, "storage-live", item.Index, item.Count, item.Inc, item.LocalOrder, item.RemoteOrder, item.TotalOrdered, item.LocalSupplyCount, item.LocalDemandCount, item.RemoteSupplyCount, item.RemoteDemandCount);
			}
			foreach (int item2 in snapshot.NeededItemIds.OrderBy((int itemId) => itemId))
			{
				Append(stringBuilder, "need", item2);
			}
			foreach (LogisticsStationBeltSlotSnapshot item3 in snapshot.BeltSlots.OrderBy((LogisticsStationBeltSlotSnapshot slot) => slot.Index))
			{
				Append(stringBuilder, "belt-live", item3.Index, item3.Counter);
			}
			return Hash(stringBuilder);
		}

		public static string LogisticsStationConfiguration(LogisticsStationSnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			AppendLogisticsStationConfiguration(stringBuilder, snapshot, "logistics-station-config-v1");
			return Hash(stringBuilder);
		}

		public static string LogisticsStationFleet(LogisticsStationSnapshot snapshot)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, "logistics-station-fleet-v1", snapshot.SessionId, snapshot.PlanetId, snapshot.EntityId, snapshot.StationId, snapshot.GalacticStationId, snapshot.BuildingItemId, F(snapshot.Position.X), F(snapshot.Position.Y), F(snapshot.Position.Z), snapshot.IsInterstellar, snapshot.IsCollector, snapshot.IsVeinCollector, snapshot.DroneCapacity, snapshot.VesselCapacity, snapshot.IdleDroneCount, snapshot.WorkingDroneCount, snapshot.IdleVesselCount, snapshot.WorkingVesselCount, snapshot.DroneAutoReplenish, snapshot.VesselAutoReplenish);
			return Hash(stringBuilder);
		}

		private static void AppendLogisticsStationConfiguration(StringBuilder value, LogisticsStationSnapshot snapshot, string domain)
		{
			Append(value, domain, snapshot.SessionId, snapshot.PlanetId, snapshot.EntityId, snapshot.StationId, snapshot.GalacticStationId, snapshot.BuildingItemId, F(snapshot.Position.X), F(snapshot.Position.Y), F(snapshot.Position.Z), snapshot.IsInterstellar, snapshot.IsCollector, snapshot.IsVeinCollector, snapshot.PowerNetworkId, snapshot.EnergyCapacity, snapshot.MaximumChargeEnergyPerTick, snapshot.MaximumChargePowerWatts, snapshot.WarperCapacity, F(snapshot.DroneTripRangeRaw), F(snapshot.VesselTripRangeRaw), snapshot.IncludeOrbitCollectors, F(snapshot.WarpEnableDistanceRaw), snapshot.WarpersRequired, snapshot.DroneDeliverySetting, snapshot.VesselDeliverySetting, snapshot.PilerCount, snapshot.DroneAutoReplenish, snapshot.VesselAutoReplenish, snapshot.RemoteGroupMask, snapshot.RemoteRoutePriority);
			foreach (LogisticsStationStorageSlotSnapshot item in snapshot.StorageSlots.OrderBy((LogisticsStationStorageSlotSnapshot slot) => slot.Index))
			{
				Append(value, "storage-config", item.Index, item.ItemId, item.MaximumCount, item.LocalLogic, item.RemoteLogic, item.KeepMode, F(item.KeepIncRatio));
			}
			foreach (LogisticsStationBeltSlotSnapshot item2 in snapshot.BeltSlots.OrderBy((LogisticsStationBeltSlotSnapshot slot) => slot.Index))
			{
				Append(value, "belt-slot", item2.Index, item2.Direction, item2.BeltComponentId, item2.BeltEntityId, item2.StorageIndex);
			}
		}

		public static string Combine(string actionKind, params object?[] fields)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, "action-v1", actionKind);
			Append(stringBuilder, fields);
			return Hash(stringBuilder);
		}

		private static string F(float value)
		{
			return value.ToString("R", CultureInfo.InvariantCulture);
		}

		private static string F(double value)
		{
			return value.ToString("R", CultureInfo.InvariantCulture);
		}

		private static string Q(float value)
		{
			return value.ToString("0.00", CultureInfo.InvariantCulture);
		}

		private static void Append(StringBuilder builder, params object?[] fields)
		{
			foreach (object obj in fields)
			{
				string text = ((obj == null) ? string.Empty : ((!(obj is IFormattable formattable)) ? (obj.ToString() ?? string.Empty) : formattable.ToString(null, CultureInfo.InvariantCulture)));
				string text2 = text;
				builder.Append(text2.Length.ToString(CultureInfo.InvariantCulture));
				builder.Append(':');
				builder.Append(text2);
				builder.Append('|');
			}
		}

		private static string Hash(StringBuilder canonical)
		{
			using SHA256 sHA = SHA256.Create();
			byte[] array = sHA.ComputeHash(Encoding.UTF8.GetBytes(canonical.ToString()));
			StringBuilder stringBuilder = new StringBuilder(array.Length * 2);
			byte[] array2 = array;
			foreach (byte b in array2)
			{
				stringBuilder.Append(b.ToString("x2", CultureInfo.InvariantCulture));
			}
			return "sha256:" + stringBuilder;
		}
	}
	public static class GameplayModePolicy
	{
		public static bool AllowsNormalActions(bool descriptorAvailable, bool isPeaceful, bool isSandboxMode, bool sandboxToolsEnabled, float resourceMultiplier)
		{
			return descriptorAvailable && isPeaceful;
		}
	}
	public sealed class IdempotencyCache<T>
	{
		private sealed class Entry
		{
			public string Fingerprint { get; }

			public T Result { get; }

			public DateTimeOffset ExpiresAtUtc { get; }

			public Entry(string fingerprint, T result, DateTimeOffset expiresAtUtc)
			{
				Fingerprint = fingerprint;
				Result = result;
				ExpiresAtUtc = expiresAtUtc;
			}
		}

		private readonly object _gate = new object();

		private readonly Dictionary<string, Dictionary<string, Entry>> _entriesByScope = new Dictionary<string, Dictionary<string, Entry>>(StringComparer.Ordinal);

		private readonly int _capacityPerScope;

		private readonly TimeSpan _retention;

		private readonly Func<DateTimeOffset> _utcNow;

		public IdempotencyCache(int capacity)
			: this(capacity, TimeSpan.FromMinutes(30.0), (Func<DateTimeOffset>?)null)
		{
		}

		public IdempotencyCache(int capacity, TimeSpan retention, Func<DateTimeOffset>? utcNow = null)
		{
			if (capacity <= 0)
			{
				throw new ArgumentOutOfRangeException("capacity");
			}
			if (retention <= TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("retention");
			}
			_capacityPerScope = capacity;
			_retention = retention;
			_utcNow = utcNow ?? ((Func<DateTimeOffset>)(() => DateTimeOffset.UtcNow));
		}

		public bool TryGet(string key, string fingerprint, out T? result, out bool conflict)
		{
			return TryGetCore(string.Empty, key, fingerprint, out result, out conflict);
		}

		public bool TryGet(string scope, string key, string fingerprint, out T? result, out bool conflict)
		{
			if (string.IsNullOrWhiteSpace(scope))
			{
				throw new ArgumentException("An idempotency scope is required.", "scope");
			}
			return TryGetCore(scope, key, fingerprint, out result, out conflict);
		}

		public bool TryAdd(string key, string fingerprint, T result)
		{
			return TryAddCore(string.Empty, key, fingerprint, result);
		}

		public bool TryAdd(string scope, string key, string fingerprint, T result)
		{
			if (string.IsNullOrWhiteSpace(scope))
			{
				throw new ArgumentException("An idempotency scope is required.", "scope");
			}
			return TryAddCore(scope, key, fingerprint, result);
		}

		public bool HasCapacity()
		{
			return HasCapacityCore(string.Empty);
		}

		public bool HasCapacity(string scope)
		{
			if (string.IsNullOrWhiteSpace(scope))
			{
				throw new ArgumentException("An idempotency scope is required.", "scope");
			}
			return HasCapacityCore(scope);
		}

		private bool TryGetCore(string scope, string key, string fingerprint, out T? result, out bool conflict)
		{
			result = default(T);
			conflict = false;
			if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(fingerprint))
			{
				throw new ArgumentException("Idempotency key and fingerprint are required.");
			}
			lock (_gate)
			{
				DateTimeOffset now = _utcNow();
				RemoveExpiredUnsafe(now);
				if (!_entriesByScope.TryGetValue(scope, out Dictionary<string, Entry> value))
				{
					return false;
				}
				if (!value.TryGetValue(key, out var value2))
				{
					return false;
				}
				if (!string.Equals(value2.Fingerprint, fingerprint, StringComparison.Ordinal))
				{
					conflict = true;
					return false;
				}
				result = value2.Result;
				return true;
			}
		}

		private bool TryAddCore(string scope, string key, string fingerprint, T result)
		{
			if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(fingerprint))
			{
				throw new ArgumentException("Idempotency key and fingerprint are required.");
			}
			lock (_gate)
			{
				DateTimeOffset now = _utcNow();
				RemoveExpiredUnsafe(now);
				if (!_entriesByScope.TryGetValue(scope, out Dictionary<string, Entry> value))
				{
					value = new Dictionary<string, Entry>(StringComparer.Ordinal);
					_entriesByScope.Add(scope, value);
				}
				if (value.ContainsKey(key))
				{
					return false;
				}
				if (value.Count >= _capacityPerScope)
				{
					return false;
				}
				value.Add(key, new Entry(fingerprint, result, now.Add(_retention)));
				return true;
			}
		}

		private bool HasCapacityCore(string scope)
		{
			lock (_gate)
			{
				RemoveExpiredUnsafe(_utcNow());
				Dictionary<string, Entry> value;
				return !_entriesByScope.TryGetValue(scope, out value) || value.Count < _capacityPerScope;
			}
		}

		private void RemoveExpiredUnsafe(DateTimeOffset now)
		{
			string[] array = _entriesByScope.Keys.ToArray();
			foreach (string key in array)
			{
				Dictionary<string, Entry> dictionary = _entriesByScope[key];
				string[] array2 = (from pair in dictionary
					where pair.Value.ExpiresAtUtc <= now
					select pair.Key).ToArray();
				foreach (string key2 in array2)
				{
					dictionary.Remove(key2);
				}
				if (dictionary.Count == 0)
				{
					_entriesByScope.Remove(key);
				}
			}
		}
	}
	public readonly struct FlightPathPoint
	{
		public double X { get; }

		public double Y { get; }

		public double Z { get; }

		public FlightPathPoint(double x, double y, double z)
		{
			X = x;
			Y = y;
			Z = z;
		}
	}
	public readonly struct FlightPathDetour
	{
		public int ObstacleBodyId { get; }

		public FlightPathPoint AimPoint { get; }

		public double AlongRouteDistance { get; }

		public double DirectClearance { get; }

		public double RequiredClearance { get; }

		public double DetourRadius { get; }

		public FlightPathDetour(int obstacleBodyId, FlightPathPoint aimPoint, double alongRouteDistance, double directClearance, double requiredClearance, double detourRadius)
		{
			ObstacleBodyId = obstacleBodyId;
			AimPoint = aimPoint;
			AlongRouteDistance = alongRouteDistance;
			DirectClearance = directClearance;
			RequiredClearance = requiredClearance;
			DetourRadius = detourRadius;
		}
	}
	public static class InterplanetaryFlightPathAvoidance
	{
		public const double MinimumSafetyMargin = 1000.0;

		public const double RelativeSafetyMargin = 0.75;

		public const double DetourRadiusFactor = 1.5;

		private const double MinimumRouteLength = 1.0;

		private const double MinimumVectorLengthSquared = 1E-12;

		private const double SegmentSafetyFactor = 1.05;

		private const int MaximumDetourExpansionAttempts = 8;

		public static bool TryCreateDetour(FlightPathPoint currentPosition, FlightPathPoint destinationPosition, int obstacleBodyId, FlightPathPoint obstacleCenter, double obstacleRadius, out FlightPathDetour detour)
		{
			ValidateFinite(currentPosition, "currentPosition");
			ValidateFinite(destinationPosition, "destinationPosition");
			detour = default(FlightPathDetour);
			if (obstacleBodyId <= 0 || !IsFinite(obstacleRadius) || obstacleRadius <= 0.0 || !IsFinite(obstacleCenter))
			{
				return false;
			}
			FlightPathPoint flightPathPoint = Subtract(destinationPosition, currentPosition);
			double num = LengthSquared(flightPathPoint);
			if (num < 1.0)
			{
				return false;
			}
			double num2 = Dot(Subtract(obstacleCenter, currentPosition), flightPathPoint) / num;
			if (num2 <= 0.0 || num2 >= 1.0)
			{
				return false;
			}
			FlightPathPoint value = Subtract(Add(currentPosition, Scale(flightPathPoint, num2)), obstacleCenter);
			double num3 = Length(value);
			double num4 = obstacleRadius + Math.Max(1000.0, obstacleRadius * 0.75);
			if (num3 >= num4)
			{
				return false;
			}
			double num5 = Math.Sqrt(num);
			FlightPathPoint direction = Scale(flightPathPoint, 1.0 / num5);
			FlightPathPoint normalized;
			FlightPathPoint value2 = (TryNormalize(value, out normalized) ? normalized : SelectStablePerpendicular(direction));
			double num6 = num4 * 1.5;
			double num7 = num4 * 1.05;
			FlightPathPoint flightPathPoint2 = Add(obstacleCenter, Scale(value2, num6));
			for (int i = 0; i < 8; i++)
			{
				double num8 = DistanceToSegment(obstacleCenter, currentPosition, flightPathPoint2);
				double num9 = DistanceToSegment(obstacleCenter, flightPathPoint2, destinationPosition);
				if (num8 >= num7 && num9 >= num7)
				{
					detour = new FlightPathDetour(obstacleBodyId, flightPathPoint2, num2 * num5, num3, num4, num6);
					return true;
				}
				num6 *= 1.25;
				flightPathPoint2 = Add(obstacleCenter, Scale(value2, num6));
			}
			return false;
		}

		public static bool IsPreferred(FlightPathDetour candidate, FlightPathDetour? current)
		{
			if (!current.HasValue)
			{
				return true;
			}
			int num = candidate.AlongRouteDistance.CompareTo(current.Value.AlongRouteDistance);
			if (num == 0)
			{
				return candidate.ObstacleBodyId < current.Value.ObstacleBodyId;
			}
			return num < 0;
		}

		private static FlightPathPoint SelectStablePerpendicular(FlightPathPoint direction)
		{
			FlightPathPoint right = ((Math.Abs(direction.X) <= Math.Abs(direction.Y) && Math.Abs(direction.X) <= Math.Abs(direction.Z)) ? new FlightPathPoint(1.0, 0.0, 0.0) : ((Math.Abs(direction.Y) <= Math.Abs(direction.Z)) ? new FlightPathPoint(0.0, 1.0, 0.0) : new FlightPathPoint(0.0, 0.0, 1.0)));
			if (!TryNormalize(Cross(direction, right), out var normalized))
			{
				return new FlightPathPoint(0.0, 1.0, 0.0);
			}
			return normalized;
		}

		private static double DistanceToSegment(FlightPathPoint point, FlightPathPoint segmentStart, FlightPathPoint segmentEnd)
		{
			FlightPathPoint flightPathPoint = Subtract(segmentEnd, segmentStart);
			double num = LengthSquared(flightPathPoint);
			if (num < 1E-12)
			{
				return Length(Subtract(point, segmentStart));
			}
			double val = Dot(Subtract(point, segmentStart), flightPathPoint) / num;
			val = Math.Max(0.0, Math.Min(1.0, val));
			FlightPathPoint right = Add(segmentStart, Scale(flightPathPoint, val));
			return Length(Subtract(point, right));
		}

		private static bool TryNormalize(FlightPathPoint value, out FlightPathPoint normalized)
		{
			double num = LengthSquared(value);
			if (num < 1E-12)
			{
				normalized = default(FlightPathPoint);
				return false;
			}
			normalized = Scale(value, 1.0 / Math.Sqrt(num));
			return true;
		}

		private static FlightPathPoint Add(FlightPathPoint left, FlightPathPoint right)
		{
			return new FlightPathPoint(left.X + right.X, left.Y + right.Y, left.Z + right.Z);
		}

		private static FlightPathPoint Subtract(FlightPathPoint left, FlightPathPoint right)
		{
			return new FlightPathPoint(left.X - right.X, left.Y - right.Y, left.Z - right.Z);
		}

		private static FlightPathPoint Scale(FlightPathPoint value, double scale)
		{
			return new FlightPathPoint(value.X * scale, value.Y * scale, value.Z * scale);
		}

		private static FlightPathPoint Cross(FlightPathPoint left, FlightPathPoint right)
		{
			return new FlightPathPoint(left.Y * right.Z - left.Z * right.Y, left.Z * right.X - left.X * right.Z, left.X * right.Y - left.Y * right.X);
		}

		private static double Dot(FlightPathPoint left, FlightPathPoint right)
		{
			return left.X * right.X + left.Y * right.Y + left.Z * right.Z;
		}

		private static double Length(FlightPathPoint value)
		{
			return Math.Sqrt(LengthSquared(value));
		}

		private static double LengthSquared(FlightPathPoint value)
		{
			return Dot(value, value);
		}

		private static void ValidateFinite(FlightPathPoint value, string parameterName)
		{
			if (!IsFinite(value))
			{
				throw new ArgumentOutOfRangeException(parameterName);
			}
		}

		private static bool IsFinite(FlightPathPoint value)
		{
			if (IsFinite(value.X) && IsFinite(value.Y))
			{
				return IsFinite(value.Z);
			}
			return false;
		}

		private static bool IsFinite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}
	}
	public sealed class LandingShoreCandidateScore
	{
		public int Index { get; set; }

		public double SurfaceDistance { get; set; }

		public double TerrainClearance { get; set; }
	}
	public static class LandingShoreSelection
	{
		public static bool IsEligible(LandingShoreCandidateScore candidate, double minimumDistance, double maximumDistance, double minimumTerrainClearance)
		{
			if (candidate == null)
			{
				throw new ArgumentNullException("candidate");
			}
			if (IsFinite(candidate.SurfaceDistance) && IsFinite(candidate.TerrainClearance) && candidate.SurfaceDistance >= minimumDistance && candidate.SurfaceDistance <= maximumDistance)
			{
				return candidate.TerrainClearance >= minimumTerrainClearance;
			}
			return false;
		}

		public static bool IsPreferred(LandingShoreCandidateScore candidate, LandingShoreCandidateScore? current)
		{
			if (candidate == null)
			{
				throw new ArgumentNullException("candidate");
			}
			if (current == null)
			{
				return true;
			}
			int num = candidate.SurfaceDistance.CompareTo(current.SurfaceDistance);
			if (num != 0)
			{
				return num < 0;
			}
			int num2 = candidate.TerrainClearance.CompareTo(current.TerrainClearance);
			if (num2 == 0)
			{
				return candidate.Index < current.Index;
			}
			return num2 > 0;
		}

		private static bool IsFinite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}
	}
	public sealed class MovementFailureRecoveryAdvice
	{
		public string FailureKind { get; set; } = string.Empty;

		public long StalledGameTicks { get; set; }

		public double RemainingDistance { get; set; }

		public bool DoNotRetrySameTarget { get; set; }

		public string RecommendedRecovery { get; set; } = string.Empty;

		public double RecommendedShortMoveDistanceMeters { get; set; }

		public double OrthogonalProbeDistanceMeters { get; set; }

		public int MaximumOrthogonalProbeAttempts { get; set; }
	}
	public static class MovementFailureRecoveryAdvisor
	{
		public const double SingleObstacleMoveDistanceMeters = 5.0;

		public const double OrthogonalProbeDistanceMeters = 4.0;

		public const int MaximumOrthogonalProbeAttempts = 4;

		public const string RecoverySummary = "Fresh-read the player and nearby geometry. If one obstacle is identifiable, prepare and commit one local-tangent target about 5 m away from it. Otherwise try at most four orthogonal local-tangent targets about 4 m away, each direction once. Poll every returned actionId to terminal; after success fresh-read Walk, low speed, and sufficient energy.";

		public static MovementFailureRecoveryAdvice ForStall(MovementProgressObservation observation)
		{
			return Create(observation.Status switch
			{
				MovementProgressStatus.PositionStalled => "position_stalled", 
				MovementProgressStatus.RouteStalled => "route_stalled", 
				_ => throw new ArgumentException("A progressing observation has no movement-failure recovery advice.", "observation"), 
			}, observation.StalledGameTicks, observation.RemainingDistance);
		}

		public static MovementFailureRecoveryAdvice ForBoundedTimeout(long elapsedGameTicks, double remainingDistance)
		{
			return Create("bounded_timeout", elapsedGameTicks, remainingDistance);
		}

		private static MovementFailureRecoveryAdvice Create(string failureKind, long stalledGameTicks, double remainingDistance)
		{
			return new MovementFailureRecoveryAdvice
			{
				FailureKind = failureKind,
				StalledGameTicks = stalledGameTicks,
				RemainingDistance = remainingDistance,
				DoNotRetrySameTarget = true,
				RecommendedRecovery = "Fresh-read the player and nearby geometry. If one obstacle is identifiable, prepare and commit one local-tangent target about 5 m away from it. Otherwise try at most four orthogonal local-tangent targets about 4 m away, each direction once. Poll every returned actionId to terminal; after success fresh-read Walk, low speed, and sufficient energy.",
				RecommendedShortMoveDistanceMeters = 5.0,
				OrthogonalProbeDistanceMeters = 4.0,
				MaximumOrthogonalProbeAttempts = 4
			};
		}
	}
	public enum MovementProgressStatus
	{
		Progressing,
		PositionStalled,
		RouteStalled
	}
	public readonly struct MovementProgressObservation
	{
		public MovementProgressStatus Status { get; }

		public long StalledGameTicks { get; }

		public double RemainingDistance { get; }

		public MovementProgressObservation(MovementProgressStatus status, long stalledGameTicks, double remainingDistance)
		{
			Status = status;
			StalledGameTicks = stalledGameTicks;
			RemainingDistance = remainingDistance;
		}
	}
	public sealed class MovementProgressWatchdog
	{
		public const long DefaultPositionStallTicks = 180L;

		public const long DefaultRouteStallTicks = 600L;

		public const double DefaultMinimumDisplacement = 0.75;

		public const double DefaultMinimumTargetProgress = 1.0;

		private readonly long _positionStallTicks;

		private readonly long _routeStallTicks;

		private readonly double _minimumDisplacementSquared;

		private readonly double _minimumTargetProgress;

		private double _checkpointX;

		private double _checkpointY;

		private double _checkpointZ;

		private long _lastDisplacementGameTick;

		private double _bestRemainingDistance;

		private long _lastTargetProgressGameTick;

		public MovementProgressWatchdog(long startedAtGameTick, double initialX, double initialY, double initialZ, double initialRemainingDistance, long positionStallTicks = 180L, long routeStallTicks = 600L, double minimumDisplacement = 0.75, double minimumTargetProgress = 1.0)
		{
			if (startedAtGameTick < 0)
			{
				throw new ArgumentOutOfRangeException("startedAtGameTick");
			}
			if (positionStallTicks <= 0)
			{
				throw new ArgumentOutOfRangeException("positionStallTicks");
			}
			if (routeStallTicks < positionStallTicks)
			{
				throw new ArgumentOutOfRangeException("routeStallTicks");
			}
			ValidateFinite(initialX, "initialX");
			ValidateFinite(initialY, "initialY");
			ValidateFinite(initialZ, "initialZ");
			ValidateNonNegativeFinite(initialRemainingDistance, "initialRemainingDistance");
			ValidatePositiveFinite(minimumDisplacement, "minimumDisplacement");
			ValidatePositiveFinite(minimumTargetProgress, "minimumTargetProgress");
			_positionStallTicks = positionStallTicks;
			_routeStallTicks = routeStallTicks;
			_minimumDisplacementSquared = minimumDisplacement * minimumDisplacement;
			_minimumTargetProgress = minimumTargetProgress;
			_checkpointX = initialX;
			_checkpointY = initialY;
			_checkpointZ = initialZ;
			_lastDisplacementGameTick = startedAtGameTick;
			_bestRemainingDistance = initialRemainingDistance;
			_lastTargetProgressGameTick = startedAtGameTick;
		}

		public MovementProgressObservation Observe(long gameTick, double x, double y, double z, double remainingDistance)
		{
			if (gameTick < _lastDisplacementGameTick || gameTick < _lastTargetProgressGameTick)
			{
				throw new ArgumentOutOfRangeException("gameTick");
			}
			ValidateFinite(x, "x");
			ValidateFinite(y, "y");
			ValidateFinite(z, "z");
			ValidateNonNegativeFinite(remainingDistance, "remainingDistance");
			double num = x - _checkpointX;
			double num2 = y - _checkpointY;
			double num3 = z - _checkpointZ;
			if (num * num + num2 * num2 + num3 * num3 >= _minimumDisplacementSquared)
			{
				_checkpointX = x;
				_checkpointY = y;
				_checkpointZ = z;
				_lastDisplacementGameTick = gameTick;
			}
			if (remainingDistance <= _bestRemainingDistance - _minimumTargetProgress)
			{
				_bestRemainingDistance = remainingDistance;
				_lastTargetProgressGameTick = gameTick;
			}
			long num4 = gameTick - _lastDisplacementGameTick;
			if (num4 >= _positionStallTicks)
			{
				return new MovementProgressObservation(MovementProgressStatus.PositionStalled, num4, remainingDistance);
			}
			long num5 = gameTick - _lastTargetProgressGameTick;
			if (num5 < _routeStallTicks)
			{
				return new MovementProgressObservation(MovementProgressStatus.Progressing, 0L, remainingDistance);
			}
			return new MovementProgressObservation(MovementProgressStatus.RouteStalled, num5, remainingDistance);
		}

		public void ResetWindow(long gameTick, double x, double y, double z, double remainingDistance)
		{
			if (gameTick < _lastDisplacementGameTick || gameTick < _lastTargetProgressGameTick)
			{
				throw new ArgumentOutOfRangeException("gameTick");
			}
			ValidateFinite(x, "x");
			ValidateFinite(y, "y");
			ValidateFinite(z, "z");
			ValidateNonNegativeFinite(remainingDistance, "remainingDistance");
			_checkpointX = x;
			_checkpointY = y;
			_checkpointZ = z;
			_lastDisplacementGameTick = gameTick;
			_bestRemainingDistance = remainingDistance;
			_lastTargetProgressGameTick = gameTick;
		}

		private static void ValidateFinite(double value, string parameterName)
		{
			if (double.IsNaN(value) || double.IsInfinity(value))
			{
				throw new ArgumentOutOfRangeException(parameterName);
			}
		}

		private static void ValidateNonNegativeFinite(double value, string parameterName)
		{
			ValidateFinite(value, parameterName);
			if (value < 0.0)
			{
				throw new ArgumentOutOfRangeException(parameterName);
			}
		}

		private static void ValidatePositiveFinite(double value, string parameterName)
		{
			ValidateFinite(value, parameterName);
			if (value <= 0.0)
			{
				throw new ArgumentOutOfRangeException(parameterName);
			}
		}
	}
	public static class OwnedWorldProvenancePolicy
	{
		public static bool MatchesProtectedSaveIdentity(string? ticketOwnedSaveName, string? loadedSaveName)
		{
			if (!string.IsNullOrWhiteSpace(ticketOwnedSaveName))
			{
				return string.Equals(ticketOwnedSaveName, loadedSaveName, StringComparison.Ordinal);
			}
			return false;
		}
	}
	public enum OwnedWorldResumeSourceKind
	{
		None,
		LastExit,
		OwnedPrimary
	}
	public static class OwnedWorldResumeSourceSelector
	{
		public static OwnedWorldResumeSourceKind Select(bool quarantineRecovery, long minimumGameTick, DateTimeOffset ticketIssuedAtUtc, DateTimeOffset? lastExitWrittenAtUtc, long? lastExitGameTick, DateTimeOffset? ownedPrimaryWrittenAtUtc, long? ownedPrimaryGameTick, TimeSpan timestampTolerance)
		{
			if (minimumGameTick < 0)
			{
				throw new ArgumentOutOfRangeException("minimumGameTick");
			}
			if (timestampTolerance < TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("timestampTolerance");
			}
			DateTimeOffset dateTimeOffset = ticketIssuedAtUtc - timestampTolerance;
			DateTimeOffset? dateTimeOffset2;
			DateTimeOffset dateTimeOffset3;
			if (quarantineRecovery)
			{
				dateTimeOffset2 = lastExitWrittenAtUtc;
				dateTimeOffset3 = dateTimeOffset;
				if (!dateTimeOffset2.HasValue || !(dateTimeOffset2.GetValueOrDefault() >= dateTimeOffset3) || !(lastExitGameTick >= minimumGameTick))
				{
					return OwnedWorldResumeSourceKind.None;
				}
				return OwnedWorldResumeSourceKind.LastExit;
			}
			dateTimeOffset2 = ownedPrimaryWrittenAtUtc;
			dateTimeOffset3 = dateTimeOffset;
			if (!dateTimeOffset2.HasValue || !(dateTimeOffset2.GetValueOrDefault() >= dateTimeOffset3) || !(ownedPrimaryGameTick >= minimumGameTick))
			{
				return OwnedWorldResumeSourceKind.None;
			}
			return OwnedWorldResumeSourceKind.OwnedPrimary;
		}
	}
	public sealed class PreparedPlan<T>
	{
		public string Token { get; }

		public DateTimeOffset ExpiresAtUtc { get; }

		public string Fingerprint { get; }

		public T Payload { get; }

		internal PreparedPlan(string token, DateTimeOffset expiresAtUtc, string fingerprint, T payload)
		{
			Token = token;
			ExpiresAtUtc = expiresAtUtc;
			Fingerprint = fingerprint;
			Payload = payload;
		}
	}
	public sealed class PreparedPlanStore<T>
	{
		private readonly object _gate = new object();

		private readonly Dictionary<string, PreparedPlan<T>> _plans = new Dictionary<string, PreparedPlan<T>>(StringComparer.Ordinal);

		private readonly TimeSpan _lifetime;

		private readonly int _capacity;

		private readonly Func<DateTimeOffset> _utcNow;

		public PreparedPlanStore(TimeSpan lifetime, int capacity, Func<DateTimeOffset>? utcNow = null)
		{
			if (lifetime <= TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("lifetime");
			}
			if (capacity <= 0)
			{
				throw new ArgumentOutOfRangeException("capacity");
			}
			_lifetime = lifetime;
			_capacity = capacity;
			_utcNow = utcNow ?? ((Func<DateTimeOffset>)(() => DateTimeOffset.UtcNow));
		}

		public PreparedPlan<T> Add(string fingerprint, T payload)
		{
			if (string.IsNullOrWhiteSpace(fingerprint))
			{
				throw new ArgumentException("A plan fingerprint is required.", "fingerprint");
			}
			lock (_gate)
			{
				RemoveExpiredUnsafe();
				if (_plans.Count >= _capacity)
				{
					throw new InvalidOperationException("Prepared-plan capacity has been reached.");
				}
				PreparedPlan<T> preparedPlan = new PreparedPlan<T>(OpaqueToken.Create(), _utcNow().Add(_lifetime), fingerprint, payload);
				_plans.Add(preparedPlan.Token, preparedPlan);
				return preparedPlan;
			}
		}

		public bool TryTake(string token, out PreparedPlan<T>? plan, out bool expired)
		{
			plan = null;
			expired = false;
			if (string.IsNullOrWhiteSpace(token))
			{
				return false;
			}
			lock (_gate)
			{
				if (!_plans.TryGetValue(token, out PreparedPlan<T> value))
				{
					return false;
				}
				_plans.Remove(token);
				if (value.ExpiresAtUtc <= _utcNow())
				{
					expired = true;
					return false;
				}
				plan = value;
				return true;
			}
		}

		public bool TryGet(string token, out PreparedPlan<T>? plan, out bool expired)
		{
			plan = null;
			expired = false;
			if (string.IsNullOrWhiteSpace(token))
			{
				return false;
			}
			lock (_gate)
			{
				if (!_plans.TryGetValue(token, out PreparedPlan<T> value))
				{
					return false;
				}
				if (value.ExpiresAtUtc <= _utcNow())
				{
					_plans.Remove(token);
					expired = true;
					return false;
				}
				plan = value;
				return true;
			}
		}

		public bool Remove(string token)
		{
			if (string.IsNullOrWhiteSpace(token))
			{
				return false;
			}
			lock (_gate)
			{
				return _plans.Remove(token);
			}
		}

		private void RemoveExpiredUnsafe()
		{
			DateTimeOffset now = _utcNow();
			string[] array = (from pair in _plans
				where pair.Value.ExpiresAtUtc <= now
				select pair.Key).ToArray();
			foreach (string key in array)
			{
				_plans.Remove(key);
			}
		}
	}
	public sealed class ResourceCoverageCandidateScore
	{
		public int Index { get; set; }

		public int CoveredNodeCount { get; set; }

		public double DistanceToBoundNode { get; set; }

		public double Yaw { get; set; }
	}
	public static class ResourceCoverageSelection
	{
		public static int SelectBestIndex(IReadOnlyList<ResourceCoverageCandidateScore> candidates)
		{
			if (candidates == null || candidates.Count == 0)
			{
				return -1;
			}
			return (from candidate in candidates
				orderby candidate.CoveredNodeCount descending, candidate.DistanceToBoundNode, candidate.Yaw, candidate.Index
				select candidate).First().Index;
		}
	}
	public static class SorterFilterPolicy
	{
		public static bool IsSafeAssignmentWindow(int filterItemId, int pickTargetObjectId, int insertTargetObjectId, int heldItemId, int heldItemCount, int heldStackCount, int heldItemInc)
		{
			if (filterItemId >= 0 && pickTargetObjectId != 0 && insertTargetObjectId != 0 && heldItemId == 0 && heldItemCount == 0 && heldStackCount == 0)
			{
				return heldItemInc == 0;
			}
			return false;
		}
	}
	public static class SpherewrightSaveNameFactory
	{
		public const string NewWorldPrefix = "Spherewright_New_";

		public const string ImportedWorldPrefix = "Spherewright_Imported_";

		public static string CreateNewWorldName(DateTimeOffset createdAtUtc, Guid uniqueness)
		{
			return Create("Spherewright_New_", createdAtUtc, uniqueness);
		}

		public static string CreateImportedWorldName(DateTimeOffset createdAtUtc, Guid uniqueness)
		{
			return Create("Spherewright_Imported_", createdAtUtc, uniqueness);
		}

		private static string Create(string prefix, DateTimeOffset createdAtUtc, Guid uniqueness)
		{
			return $"{prefix}{createdAtUtc.UtcDateTime:yyyyMMdd_HHmmss}_{uniqueness:N}";
		}
	}
	public static class UserSaveImportConfirmationPolicy
	{
		public static bool IsCommitDeclared(bool userConfirmedInConversation, bool acknowledgeOriginalSaveRemainsUnchanged, bool acknowledgeJournalStartsAtImport)
		{
			return userConfirmedInConversation && acknowledgeOriginalSaveRemainsUnchanged && acknowledgeJournalStartsAtImport;
		}
	}
	public static class UserSaveImportSafetyPolicy
	{
		public static bool IsEnabled(bool allowWrites, bool allowUserSaveImport)
		{
			return allowWrites && allowUserSaveImport;
		}

		public static bool MatchesPreparedCandidate(string? expectedSessionId, string? currentSessionId, long expectedRevision, long currentRevision, object? expectedGameData, object? currentGameData)
		{
			if (!string.IsNullOrWhiteSpace(expectedSessionId) && string.Equals(expectedSessionId, currentSessionId, StringComparison.Ordinal) && expectedRevision == currentRevision && expectedGameData != null)
			{
				return expectedGameData == currentGameData;
			}
			return false;
		}

		public static bool HasVerifiedCopyHeader(bool saveReturnedTrue, long expectedGameTick, long? headerGameTick)
		{
			if (saveReturnedTrue && expectedGameTick >= 0)
			{
				return headerGameTick == expectedGameTick;
			}
			return false;
		}
	}
}
namespace Spherewright.Bridge.Core.Routing
{
	public static class ProtocolValidator
	{
		public static BridgeError? ValidateHeader(BridgeEnvelopeHeader? header, string expectedMessageType)
		{
			if (header == null)
			{
				return Invalid("The bridge envelope is missing.");
			}
			if (header.ProtocolVersion != 1)
			{
				return BridgeError.Create("INVALID_REQUEST", $"Protocol version {header.ProtocolVersion} is not supported.", false, $"Use protocol version {1}.");
			}
			if (!string.Equals(header.MessageType, expectedMessageType, StringComparison.Ordinal))
			{
				return Invalid("Expected message type '" + expectedMessageType + "'.");
			}
			if (!Guid.TryParse(header.RequestId, out var _))
			{
				return Invalid("requestId must be a UUID.");
			}
			return null;
		}

		private static BridgeError Invalid(string message)
		{
			return BridgeError.Create("INVALID_REQUEST", message, false, "Create a new request that matches the Spherewright bridge schema.");
		}
	}
}
namespace Spherewright.Bridge.Core.Progression
{
	public static class RuntimeDependencyGraphBuilder
	{
		public static RuntimeDependencyGraph Build(int targetItemId, string targetItemName, IReadOnlyList<RecipeCatalogEntry> recipes)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Expected O, but got Unknown
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Expected O, but got Unknown
			RuntimeDependencyGraph val = new RuntimeDependencyGraph
			{
				TargetItemId = targetItemId,
				TargetItemName = (targetItemName ?? string.Empty)
			};
			if (targetItemId <= 0)
			{
				return val;
			}
			Dictionary<int, List<RecipeCatalogEntry>> dictionary = new Dictionary<int, List<RecipeCatalogEntry>>();
			foreach (RecipeCatalogEntry recipe in recipes)
			{
				foreach (CatalogItemAmount output in recipe.Outputs)
				{
					if (!dictionary.TryGetValue(output.ItemId, out var value))
					{
						value = new List<RecipeCatalogEntry>();
						dictionary.Add(output.ItemId, value);
					}
					value.Add(recipe);
				}
			}
			Stack<int> stack = new Stack<int>();
			HashSet<int> hashSet = new HashSet<int>();
			HashSet<int> hashSet2 = new HashSet<int>();
			stack.Push(targetItemId);
			while (stack.Count > 0)
			{
				int num = stack.Pop();
				if (!hashSet.Add(num) || !dictionary.TryGetValue(num, out var value2))
				{
					continue;
				}
				foreach (RecipeCatalogEntry item in value2.OrderBy((RecipeCatalogEntry entry) => entry.RecipeId))
				{
					if (!hashSet2.Add(item.RecipeId))
					{
						continue;
					}
					foreach (CatalogItemAmount input in item.Inputs)
					{
						val.Edges.Add(new RuntimeDependencyEdge
						{
							FromKind = "item",
							FromId = input.ItemId,
							ToKind = "recipe",
							ToId = item.RecipeId
						});
						stack.Push(input.ItemId);
					}
					foreach (CatalogItemAmount output2 in item.Outputs)
					{
						val.Edges.Add(new RuntimeDependencyEdge
						{
							FromKind = "recipe",
							FromId = item.RecipeId,
							ToKind = "item",
							ToId = output2.ItemId
						});
					}
				}
			}
			val.ItemIds = (from id in (from id in val.Edges.SelectMany((RuntimeDependencyEdge edge) => new int[2]
					{
						(edge.FromKind == "item") ? edge.FromId : 0,
						(edge.ToKind == "item") ? edge.ToId : 0
					})
					where id > 0
					select id).Append(targetItemId).Distinct()
				orderby id
				select id).ToList();
			val.RecipeIds = hashSet2.OrderBy((int id) => id).ToList();
			val.Edges = val.Edges.OrderBy<RuntimeDependencyEdge, string>((RuntimeDependencyEdge edge) => edge.FromKind, StringComparer.Ordinal).ThenBy((RuntimeDependencyEdge edge) => edge.FromId).ThenBy<RuntimeDependencyEdge, string>((RuntimeDependencyEdge edge) => edge.ToKind, StringComparer.Ordinal)
				.ThenBy((RuntimeDependencyEdge edge) => edge.ToId)
				.ToList();
			return val;
		}
	}
}
namespace Spherewright.Bridge.Core.Logistics
{
	public static class LogisticsStationChargePolicy
	{
		public const long EnergyPerTickStep = 50000L;

		public const long PowerWattsStep = 3000000L;

		public static bool TryNormalizeUiPower(long prefabWorkEnergyPerTick, long requestedPowerWatts, out long requestedEnergyPerTick, out long minimumEnergyPerTick, out long maximumEnergyPerTick)
		{
			requestedEnergyPerTick = 0L;
			minimumEnergyPerTick = 0L;
			maximumEnergyPerTick = 0L;
			if (prefabWorkEnergyPerTick <= 0 || prefabWorkEnergyPerTick > 30744573456182586L || requestedPowerWatts <= 0 || requestedPowerWatts % 3000000 != 0L)
			{
				return false;
			}
			minimumEnergyPerTick = prefabWorkEnergyPerTick / 2 / 50000 * 50000;
			maximumEnergyPerTick = prefabWorkEnergyPerTick * 5 / 50000 * 50000;
			requestedEnergyPerTick = requestedPowerWatts / 60;
			if (minimumEnergyPerTick > 0 && maximumEnergyPerTick >= minimumEnergyPerTick && requestedEnergyPerTick >= minimumEnergyPerTick)
			{
				return requestedEnergyPerTick <= maximumEnergyPerTick;
			}
			return false;
		}
	}
	public static class LogisticsStationFleetTransferPolicy
	{
		public static bool TryValidate(bool isInterstellar, bool isCollector, bool isVeinCollector, string direction, int itemId, int count, int playerItemCount, int playerItemInc, int idleDroneCount, int workingDroneCount, int droneCapacity, int idleVesselCount, int workingVesselCount, int vesselCapacity, bool playerCanAcceptWithdrawal, out string rejection)
		{
			rejection = string.Empty;
			if (isCollector || isVeinCollector)
			{
				rejection = "Orbital and vein collectors do not expose an ordinary player fleet slot.";
				return false;
			}
			if (direction != "player-to-station" && direction != "station-to-player")
			{
				rejection = "Fleet transfer direction must be player-to-station or station-to-player.";
				return false;
			}
			if (count <= 0 || count > 100)
			{
				rejection = "Fleet transfer count must be from 1 through 100.";
				return false;
			}
			bool flag = itemId == 5001;
			bool flag2 = itemId == 5002;
			if (!flag && !flag2)
			{
				rejection = "Only logistics drones (5001) or logistics vessels (5002) belong in station fleet slots.";
				return false;
			}
			if (flag2 && !isInterstellar)
			{
				rejection = "A planetary logistics station has no logistics-vessel slot.";
				return false;
			}
			int num = (flag ? idleDroneCount : idleVesselCount);
			int num2 = (flag ? workingDroneCount : workingVesselCount);
			int num3 = (flag ? droneCapacity : vesselCapacity);
			if (num < 0 || num2 < 0 || num3 <= 0 || num + num2 > num3)
			{
				rejection = "The station fleet counters or current-version prefab capacity are inconsistent.";
				return false;
			}
			if (direction == "player-to-station")
			{
				if (playerItemCount < count)
				{
					rejection = "The player package contains fewer than the requested fleet items.";
					return false;
				}
				if (playerItemInc != 0)
				{
					rejection = "Proliferated fleet items are rejected because the normal station UI discards their proliferator points.";
					return false;
				}
				if (num + num2 + count > num3)
				{
					rejection = "The requested items exceed the station fleet capacity after working craft are included.";
					return false;
				}
				return true;
			}
			if (num < count)
			{
				rejection = "Only idle station craft can be withdrawn, and fewer than the requested count are idle.";
				return false;
			}
			if (!playerCanAcceptWithdrawal)
			{
				rejection = "The player package cannot accept the exact requested withdrawal.";
				return false;
			}
			return true;
		}
	}
	public static class LogisticsStationIdentityPolicy
	{
		public static bool MatchesLocalPlanet(bool isInterstellar, int stationPlanetId, int factoryPlanetId)
		{
			if (factoryPlanetId <= 0)
			{
				return false;
			}
			if (isInterstellar)
			{
				return stationPlanetId == factoryPlanetId;
			}
			if (stationPlanetId != 0)
			{
				return stationPlanetId == factoryPlanetId;
			}
			return true;
		}
	}
}
namespace Spherewright.Bridge.Core.Journals
{
	public sealed class GameplayFirstOccurrenceDetector
	{
		private readonly HashSet<int> _manualItemIds;

		private readonly HashSet<int> _productionLineItemIds;

		private readonly HashSet<int> _researchIds;

		public GameplayFirstOccurrenceDetector(IEnumerable<int>? knownManualItemIds = null, IEnumerable<int>? knownProductionLineItemIds = null, IEnumerable<int>? knownResearchIds = null)
		{
			_manualItemIds = new HashSet<int>(knownManualItemIds ?? Enumerable.Empty<int>());
			_productionLineItemIds = new HashSet<int>(knownProductionLineItemIds ?? Enumerable.Empty<int>());
			_researchIds = new HashSet<int>(knownResearchIds ?? Enumerable.Empty<int>());
		}

		public IReadOnlyList<GameplayItemFirstOccurrence> ObserveManualCounts(IReadOnlyDictionary<int, long> cumulativeCounts)
		{
			return ObserveItemCounts(cumulativeCounts, _manualItemIds, "manual_item_first");
		}

		public IReadOnlyList<GameplayItemFirstOccurrence> ObserveProductionLineCounts(IReadOnlyDictionary<int, long> producedThisTick)
		{
			return ObserveItemCounts(producedThisTick, _productionLineItemIds, "production_line_item_first");
		}

		public bool TryObserveResearchSelection(int techId)
		{
			if (techId > 0)
			{
				return _researchIds.Add(techId);
			}
			return false;
		}

		private static IReadOnlyList<GameplayItemFirstOccurrence> ObserveItemCounts(IReadOnlyDictionary<int, long> counts, HashSet<int> knownIds, string kind)
		{
			List<GameplayItemFirstOccurrence> list = new List<GameplayItemFirstOccurrence>();
			foreach (KeyValuePair<int, long> item in counts.OrderBy((KeyValuePair<int, long> pair) => pair.Key))
			{
				if (item.Key > 0 && item.Value > 0 && knownIds.Add(item.Key))
				{
					list.Add(new GameplayItemFirstOccurrence(item.Key, item.Value, kind));
				}
			}
			return list;
		}
	}
	public sealed class GameplayItemFirstOccurrence
	{
		public int ItemId { get; }

		public long ObservedCount { get; }

		public string Kind { get; }

		public GameplayItemFirstOccurrence(int itemId, long observedCount, string kind)
		{
			ItemId = itemId;
			ObservedCount = observedCount;
			Kind = kind;
		}
	}
}
namespace Spherewright.Bridge.Core.Framing
{
	public sealed class FrameCodec
	{
		private static readonly UTF8Encoding StrictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

		private readonly int _maxFrameBytes;

		public FrameCodec(int maxFrameBytes)
		{
			if (maxFrameBytes <= 0)
			{
				throw new ArgumentOutOfRangeException("maxFrameBytes");
			}
			_maxFrameBytes = maxFrameBytes;
		}

		public async Task<byte[]?> ReadFrameAsync(Stream stream, CancellationToken cancellationToken)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			byte[] header = new byte[4];
			int num = await stream.ReadAsync(header, 0, header.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (num == 0)
			{
				return null;
			}
			await ReadRemainderAsync(stream, header, num, header.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			int num2 = header[0] | (header[1] << 8) | (header[2] << 16) | (header[3] << 24);
			if (num2 < 0)
			{
				throw new FrameProtocolException("Frame length must not be negative.");
			}
			if (num2 > _maxFrameBytes)
			{
				throw new FrameProtocolException($"Frame length {num2} exceeds the configured maximum {_maxFrameBytes}.");
			}
			byte[] payload = new byte[num2];
			if (num2 > 0)
			{
				await ReadRemainderAsync(stream, payload, 0, num2, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			return payload;
		}

		public async Task WriteFrameAsync(Stream stream, byte[] payload, CancellationToken cancellationToken)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			if (payload == null)
			{
				throw new ArgumentNullException("payload");
			}
			if (payload.Length > _maxFrameBytes)
			{
				throw new FrameProtocolException($"Frame length {payload.Length} exceeds the configured maximum {_maxFrameBytes}.");
			}
			int num = payload.Length;
			byte[] array = new byte[4]
			{
				(byte)num,
				(byte)(num >> 8),
				(byte)(num >> 16),
				(byte)(num >> 24)
			};
			await stream.WriteAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (payload.Length != 0)
			{
				await stream.WriteAsync(payload, 0, payload.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			await stream.FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public static string DecodeUtf8(byte[] payload)
		{
			if (payload == null)
			{
				throw new ArgumentNullException("payload");
			}
			try
			{
				return StrictUtf8.GetString(payload);
			}
			catch (DecoderFallbackException innerException)
			{
				throw new FrameProtocolException("Frame payload is not valid UTF-8.", innerException);
			}
		}

		public static byte[] EncodeUtf8(string text)
		{
			if (text == null)
			{
				throw new ArgumentNullException("text");
			}
			return StrictUtf8.GetBytes(text);
		}

		private static async Task ReadRemainderAsync(Stream stream, byte[] buffer, int offset, int expectedCount, CancellationToken cancellationToken)
		{
			int num;
			for (int readTotal = offset; readTotal < expectedCount; readTotal += num)
			{
				num = await stream.ReadAsync(buffer, readTotal, expectedCount - readTotal, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				if (num == 0)
				{
					throw new EndOfStreamException("Connection ended before the complete frame was received.");
				}
			}
		}
	}
	public sealed class FrameProtocolException : Exception
	{
		public FrameProtocolException(string message)
			: base(message)
		{
		}

		public FrameProtocolException(string message, Exception innerException)
			: base(message, innerException)
		{
		}
	}
}
namespace Spherewright.Bridge.Core.Authentication
{
	public sealed class HandshakeAuthenticator
	{
		private readonly string _bridgeInstanceId;

		private readonly byte[] _authTokenBytes;

		public HandshakeAuthenticator(string bridgeInstanceId, string authToken)
		{
			if (string.IsNullOrWhiteSpace(bridgeInstanceId))
			{
				throw new ArgumentException("Bridge instance ID is required.", "bridgeInstanceId");
			}
			if (string.IsNullOrWhiteSpace(authToken))
			{
				throw new ArgumentException("Authentication token is required.", "authToken");
			}
			_bridgeInstanceId = bridgeInstanceId;
			_authTokenBytes = Encoding.UTF8.GetBytes(authToken);
		}

		public BridgeError? Authenticate(HandshakeRequest? request)
		{
			if (request == null || !string.Equals(request.BridgeInstanceId, _bridgeInstanceId, StringComparison.Ordinal) || !FixedTimeEquals(_authTokenBytes, Encoding.UTF8.GetBytes(request.AuthToken ?? string.Empty)))
			{
				return BridgeError.Create("AUTH_FAILED", "Bridge authentication failed.", false, "Rediscover the active Spherewright bridge descriptor and reconnect.");
			}
			if (string.IsNullOrWhiteSpace(request.ClientName) || string.IsNullOrWhiteSpace(request.ClientVersion))
			{
				return BridgeError.Create("INVALID_REQUEST", "Handshake client name and version are required.", false, "Send a complete handshake request.");
			}
			return null;
		}

		private static bool FixedTimeEquals(byte[] expected, byte[] actual)
		{
			int num = expected.Length ^ actual.Length;
			int num2 = Math.Max(expected.Length, actual.Length);
			for (int i = 0; i < num2; i++)
			{
				byte b = (byte)((i < expected.Length) ? expected[i] : 0);
				byte b2 = (byte)((i < actual.Length) ? actual[i] : 0);
				num |= b ^ b2;
			}
			return num == 0;
		}
	}
}
namespace Spherewright.Bridge.Core.Abstractions
{
	public sealed class BoundedMainThreadDispatcher : IDisposable
	{
		private interface IWorkItem
		{
			void Execute();

			void Cancel();
		}

		private sealed class WorkItem<T> : IWorkItem
		{
			private readonly Func<T> _operation;

			private readonly TaskCompletionSource<T> _completion = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);

			public Task<T> Task => _completion.Task;

			public WorkItem(Func<T> operation)
			{
				_operation = operation;
			}

			public void Execute()
			{
				try
				{
					_completion.TrySetResult(_operation());
				}
				catch (Exception exception)
				{
					_completion.TrySetException(exception);
				}
			}

			public void Cancel()
			{
				_completion.TrySetCanceled();
			}
		}

		private readonly object _gate = new object();

		private readonly Queue<IWorkItem> _queue = new Queue<IWorkItem>();

		private readonly int _capacity;

		private bool _disposed;

		public int Count
		{
			get
			{
				lock (_gate)
				{
					return _queue.Count;
				}
			}
		}

		public BoundedMainThreadDispatcher(int capacity)
		{
			if (capacity <= 0)
			{
				throw new ArgumentOutOfRangeException("capacity");
			}
			_capacity = capacity;
		}

		public bool TryEnqueue<T>(Func<T> operation, out Task<T> completion)
		{
			if (operation == null)
			{
				throw new ArgumentNullException("operation");
			}
			WorkItem<T> workItem = new WorkItem<T>(operation);
			lock (_gate)
			{
				if (_disposed || _queue.Count >= _capacity)
				{
					completion = workItem.Task;
					workItem.Cancel();
					return false;
				}
				_queue.Enqueue(workItem);
				completion = workItem.Task;
				return true;
			}
		}

		public int Pump(int maxItems, TimeSpan budget)
		{
			if (maxItems <= 0)
			{
				throw new ArgumentOutOfRangeException("maxItems");
			}
			if (budget <= TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("budget");
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			int i;
			for (i = 0; i < maxItems; i++)
			{
				if (!(stopwatch.Elapsed < budget))
				{
					break;
				}
				IWorkItem workItem;
				lock (_gate)
				{
					workItem = ((_queue.Count > 0) ? _queue.Dequeue() : null);
				}
				if (workItem == null)
				{
					break;
				}
				workItem.Execute();
			}
			return i;
		}

		public void Dispose()
		{
			IWorkItem[] array;
			lock (_gate)
			{
				if (_disposed)
				{
					return;
				}
				_disposed = true;
				array = _queue.ToArray();
				_queue.Clear();
			}
			IWorkItem[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				array2[i].Cancel();
			}
		}
	}
}

plugins/Spherewright.Contracts.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;
using Spherewright.Contracts.Errors;
using Spherewright.Contracts.Factory;
using Spherewright.Contracts.Logistics;
using Spherewright.Contracts.Sessions;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Spherewright.Contracts")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.3.0")]
[assembly: AssemblyInformationalVersion("0.3.3+f0cd11105957ae63cb4b45fd5756b0a42508857f")]
[assembly: AssemblyProduct("Spherewright.Contracts")]
[assembly: AssemblyTitle("Spherewright.Contracts")]
[assembly: AssemblyVersion("0.3.3.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Spherewright.Contracts.Versioning
{
	public static class SpherewrightProduct
	{
		public const string CurrentVersion = "0.3.3";
	}
}
namespace Spherewright.Contracts.Testing
{
	public sealed class CommitTestWorldRequest
	{
		public string PlanToken { get; set; } = string.Empty;

		public string IdempotencyKey { get; set; } = string.Empty;
	}
	public sealed class PreparedTestWorldPlan
	{
		public string PlanToken { get; set; } = string.Empty;

		public DateTimeOffset ExpiresAtUtc { get; set; }

		public string SaveName { get; set; } = string.Empty;

		public int GalaxySeed { get; set; }

		public int StarCount { get; set; }

		public float ResourceMultiplier { get; set; }

		public bool PeacefulMode { get; set; }

		public bool SandboxMode { get; set; }

		public bool CommitAllowed { get; set; }

		public List<string> Warnings { get; set; } = new List<string>();
	}
	public sealed class PrepareTestWorldRequest
	{
		public int GalaxySeed { get; set; } = 13572468;

		public int StarCount { get; set; } = 32;
	}
	public sealed class TestWorldCreationResult
	{
		public string ActionId { get; set; } = string.Empty;

		public bool Accepted { get; set; }

		public bool IdempotentReplay { get; set; }

		public string SaveName { get; set; } = string.Empty;

		public int GalaxySeed { get; set; }

		public int StarCount { get; set; }

		public string State { get; set; } = string.Empty;
	}
}
namespace Spherewright.Contracts.Sessions
{
	public sealed class BridgeStatus
	{
		public bool BridgeConnected { get; set; }

		public string BridgeInstanceId { get; set; } = string.Empty;

		public string PluginVersion { get; set; } = string.Empty;

		public int ProtocolVersion { get; set; }

		public string GameVersion { get; set; } = string.Empty;

		public bool GameLoaded { get; set; }

		public bool WritesConfigured { get; set; }

		public string WriteHealth { get; set; } = "healthy";
	}
	public sealed class PrepareFlightCheckpointReloadRequest
	{
		public string ReloadToken { get; set; } = string.Empty;
	}
	public sealed class CommitFlightCheckpointReloadRequest
	{
		public string PlanToken { get; set; } = string.Empty;

		public string IdempotencyKey { get; set; } = string.Empty;
	}
	public sealed class PreparedFlightCheckpointReloadPlan
	{
		public bool Prepared { get; set; }

		public string PlanToken { get; set; } = string.Empty;

		public DateTimeOffset ExpiresAtUtc { get; set; }

		public string CheckpointId { get; set; } = string.Empty;

		public int OriginPlanetId { get; set; }

		public int DestinationPlanetId { get; set; }

		public long SavedGameTick { get; set; }

		public bool CommitAllowedNow { get; set; }

		public List<WriteBlocker> CommitBlockers { get; set; } = new List<WriteBlocker>();

		public string CompletionCondition { get; set; } = string.Empty;
	}
	public sealed class FlightCheckpointReloadResult
	{
		public string ActionId { get; set; } = string.Empty;

		public string CheckpointId { get; set; } = string.Empty;

		public bool Accepted { get; set; }

		public bool IdempotentReplay { get; set; }

		public string State { get; set; } = string.Empty;
	}
	public sealed class LocalPlanetRequest
	{
		public int PlanetId { get; set; }
	}
	public static class OwnedSaveStates
	{
		public const string None = "none";

		public const string WaitingForWorld = "waiting_for_world";

		public const string WaitingToSave = "waiting_to_save";

		public const string Saved = "saved";

		public const string SaveFailed = "save_failed";
	}
	public sealed class PrepareOwnedWorldResumeRequest
	{
		public string ResumeToken { get; set; } = string.Empty;
	}
	public sealed class CommitOwnedWorldResumeRequest
	{
		public string PlanToken { get; set; } = string.Empty;

		public string IdempotencyKey { get; set; } = string.Empty;
	}
	public sealed class PreparedOwnedWorldResumePlan
	{
		public bool Prepared { get; set; }

		public string PlanToken { get; set; } = string.Empty;

		public DateTimeOffset ExpiresAtUtc { get; set; }

		public int ExpectedPlanetId { get; set; }

		public long MinimumGameTick { get; set; }

		public bool CommitAllowedNow { get; set; }

		public List<WriteBlocker> CommitBlockers { get; set; } = new List<WriteBlocker>();

		public string CompletionCondition { get; set; } = string.Empty;
	}
	public sealed class OwnedWorldResumeResult
	{
		public string ActionId { get; set; } = string.Empty;

		public bool Accepted { get; set; }

		public bool IdempotentReplay { get; set; }

		public string State { get; set; } = string.Empty;
	}
	public static class PeacefulModeStates
	{
		public const string ConfirmedPeaceful = "confirmed_peaceful";

		public const string ConfirmedCombat = "confirmed_combat";

		public const string Unknown = "unknown";
	}
	public static class SandboxModeStates
	{
		public const string ConfirmedDisabled = "confirmed_disabled";

		public const string Enabled = "enabled";

		public const string Unknown = "unknown";
	}
	public sealed class SessionState
	{
		public bool BridgeConnected { get; set; }

		public bool GameLoaded { get; set; }

		public bool OwnedBySpherewright { get; set; }

		public bool AccessRestricted { get; set; }

		public string GameVersion { get; set; } = string.Empty;

		public string? SessionId { get; set; }

		public string? SaveName { get; set; }

		public long? GameTick { get; set; }

		public long Revision { get; set; }

		public int? LocalPlanetId { get; set; }

		public string? LocalPlanetName { get; set; }

		public string PeacefulMode { get; set; } = "unknown";

		public string SandboxMode { get; set; } = "unknown";

		public float? ResourceMultiplier { get; set; }

		public bool WritesAllowed { get; set; }

		public string WriteHealth { get; set; } = "healthy";

		public string? WriteQuarantineActionId { get; set; }

		public List<WriteBlocker> WriteBlockers { get; set; } = new List<WriteBlocker>();

		public string OwnedSaveState { get; set; } = "none";

		public string? OwnedSaveError { get; set; }

		public long? LastOwnedSaveGameTick { get; set; }

		public bool RestartResumeAvailable { get; set; }

		public string? RestartResumeToken { get; set; }

		public bool FlightCheckpointAvailable { get; set; }

		public string? FlightCheckpointId { get; set; }

		public string? FlightCheckpointReloadToken { get; set; }

		public int? FlightCheckpointOriginPlanetId { get; set; }

		public int? FlightCheckpointDestinationPlanetId { get; set; }

		public long? FlightCheckpointGameTick { get; set; }

		public bool CurrentSessionLoadedFromFlightCheckpoint { get; set; }

		public bool UserSaveImportConfigured { get; set; }

		public List<string> Capabilities { get; set; } = new List<string>();
	}
	public sealed class PrepareUserSaveImportRequest
	{
		public long ExpectedRevision { get; set; }
	}
	public sealed class CommitUserSaveImportRequest
	{
		public string PlanToken { get; set; } = string.Empty;

		public string IdempotencyKey { get; set; } = string.Empty;

		public bool UserConfirmedInConversation { get; set; }

		public bool AcknowledgeOriginalSaveRemainsUnchanged { get; set; }

		public bool AcknowledgeJournalStartsAtImport { get; set; }
	}
	public sealed class PreparedUserSaveImportPlan
	{
		public bool Prepared { get; set; }

		public string PlanToken { get; set; } = string.Empty;

		public DateTimeOffset ExpiresAtUtc { get; set; }

		public long ExpectedRevision { get; set; }

		public bool OriginalSavePreserved { get; set; } = true;

		public string JournalTrackingMode { get; set; } = "attached_existing_save";

		public bool HistoricalCoverageComplete { get; set; }

		public bool UserConfirmationRequired { get; set; } = true;

		public string ConfirmationPrompt { get; set; } = string.Empty;

		public bool CommitAllowedNow { get; set; }

		public List<WriteBlocker> CommitBlockers { get; set; } = new List<WriteBlocker>();

		public string CompletionCondition { get; set; } = string.Empty;
	}
	public sealed class UserSaveImportResult
	{
		public string ActionId { get; set; } = string.Empty;

		public bool Accepted { get; set; }

		public bool IdempotentReplay { get; set; }

		public string State { get; set; } = string.Empty;

		public string? SessionId { get; set; }

		public int? PlanetId { get; set; }

		public long? SavedGameTick { get; set; }

		public bool OriginalSavePreserved { get; set; } = true;

		public string JournalTrackingMode { get; set; } = "attached_existing_save";

		public bool HistoricalCoverageComplete { get; set; }
	}
	public sealed class WriteBlocker
	{
		public string Code { get; set; } = string.Empty;

		public string Message { get; set; } = string.Empty;
	}
	public static class WriteHealthStates
	{
		public const string Healthy = "healthy";

		public const string Quarantined = "quarantined";
	}
}
namespace Spherewright.Contracts.Resources
{
	public static class ResourceNodeKinds
	{
		public const string Vein = "vein";

		public const string Vegetation = "vegetation";
	}
	public sealed class ListResourceNodesRequest
	{
		public int PlanetId { get; set; }

		public string? Kind { get; set; }

		public string? ResourceType { get; set; }

		public int? ProductItemId { get; set; }

		public int Limit { get; set; } = 50;

		public string? Cursor { get; set; }
	}
	public sealed class ListResourceNodesResult
	{
		public string SessionId { get; set; } = string.Empty;

		public int PlanetId { get; set; }

		public long CapturedAtGameTick { get; set; }

		public string SnapshotId { get; set; } = string.Empty;

		public DateTimeOffset SnapshotExpiresAtUtc { get; set; }

		public List<ResourceNodeSnapshot> Nodes { get; set; } = new List<ResourceNodeSnapshot>();

		public string? NextCursor { get; set; }
	}
	public sealed class InspectResourceNodeRequest
	{
		public int PlanetId { get; set; }

		public string Kind { get; set; } = string.Empty;

		public int NodeId { get; set; }
	}
	public sealed class ResourceNodeSnapshot
	{
		public string SessionId { get; set; } = string.Empty;

		public int PlanetId { get; set; }

		public string Kind { get; set; } = string.Empty;

		public int NodeId { get; set; }

		public string ResourceType { get; set; } = string.Empty;

		public int ProtoId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int RemainingAmount { get; set; }

		public int GroupIndex { get; set; }

		public int MinerCount { get; set; }

		public Vector3Snapshot Position { get; set; } = new Vector3Snapshot();

		public float DistanceFromPlayer { get; set; }

		public bool SameLocalPlanet { get; set; }

		public bool WithinPlayerBuildArea { get; set; }

		public List<ResourceYieldSnapshot> Yields { get; set; } = new List<ResourceYieldSnapshot>();

		public long CapturedAtGameTick { get; set; }

		public string StateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class ResourceYieldSnapshot
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int Count { get; set; }

		public float Chance { get; set; }
	}
}
namespace Spherewright.Contracts.Protocol
{
	public sealed class BridgeEnvelopeHeader
	{
		public int ProtocolVersion { get; set; }

		public string MessageType { get; set; } = string.Empty;

		public string RequestId { get; set; } = string.Empty;

		public string? SessionId { get; set; }

		public string? Method { get; set; }
	}
	public static class BridgeMessageTypes
	{
		public const string Handshake = "handshake";

		public const string Request = "request";

		public const string Response = "response";

		public const string Event = "event";
	}
	public static class BridgeMethods
	{
		public const string GetBridgeStatus = "get_bridge_status";

		public const string GetSessionState = "get_session_state";

		public const string GetPlayerState = "get_player_state";

		public const string GetProgressionState = "get_progression_state";

		public const string GetGameplayJournal = "get_gameplay_journal";

		public const string GetLocalStarSystem = "get_local_star_system";

		public const string GetRecipeCatalog = "get_recipe_catalog";

		public const string ListResourceNodes = "list_resource_nodes";

		public const string InspectResourceNode = "inspect_resource_node";

		public const string ListFactoryEntities = "list_factory_entities";

		public const string InspectFactoryEntity = "inspect_factory_entity";

		public const string GetPowerSummary = "get_power_summary";

		public const string GetActionResult = "get_action_result";

		public const string ListAssemblers = "list_assemblers";

		public const string InspectAssembler = "inspect_assembler";

		public const string GetBuildCatalog = "get_build_catalog";

		public const string PrepareNewGame = "prepare_new_game";

		public const string CommitNewGame = "commit_new_game";

		public const string PrepareImportCurrentGame = "prepare_import_current_game";

		public const string CommitImportCurrentGame = "commit_import_current_game";

		public const string PrepareMove = "prepare_move";

		public const string CommitMove = "commit_move";

		public const string PrepareInterplanetaryFlight = "prepare_interplanetary_flight";

		public const string CommitInterplanetaryFlight = "commit_interplanetary_flight";

		public const string PrepareHarvest = "prepare_harvest";

		public const string CommitHarvest = "commit_harvest";

		public const string PrepareHandcraft = "prepare_handcraft";

		public const string CommitHandcraft = "commit_handcraft";

		public const string PrepareSelectResearch = "prepare_select_research";

		public const string CommitSelectResearch = "commit_select_research";

		public const string PrepareBuild = "prepare_build";

		public const string CommitBuild = "commit_build";

		public const string PrepareDismantle = "prepare_dismantle";

		public const string CommitDismantle = "commit_dismantle";

		public const string PrepareConfigureBuilding = "prepare_configure_building";

		public const string CommitConfigureBuilding = "commit_configure_building";

		public const string PrepareTransfer = "prepare_transfer";

		public const string CommitTransfer = "commit_transfer";

		public const string PrepareLogisticsStationFleetTransfer = "prepare_logistics_station_fleet_transfer";

		public const string CommitLogisticsStationFleetTransfer = "commit_logistics_station_fleet_transfer";

		public const string PrepareRefuel = "prepare_refuel";

		public const string CommitRefuel = "commit_refuel";

		public const string PrepareSave = "prepare_save";

		public const string CommitSave = "commit_save";

		public const string PrepareQuarantineReconciliation = "prepare_quarantine_reconciliation";

		public const string CommitQuarantineReconciliation = "commit_quarantine_reconciliation";

		public const string PrepareResumeOwnedGame = "prepare_resume_owned_game";

		public const string CommitResumeOwnedGame = "commit_resume_owned_game";

		public const string PrepareReloadFlightCheckpoint = "prepare_reload_flight_checkpoint";

		public const string CommitReloadFlightCheckpoint = "commit_reload_flight_checkpoint";
	}
	public sealed class BridgeRequestEnvelope<TPayload>
	{
		public int ProtocolVersion { get; set; } = 1;

		public string MessageType { get; set; } = "request";

		public string RequestId { get; set; } = string.Empty;

		public string? SessionId { get; set; }

		public string? Method { get; set; }

		public TPayload Payload { get; set; }
	}
	public sealed class BridgeResponseEnvelope<TResult>
	{
		public int ProtocolVersion { get; set; } = 1;

		public string MessageType { get; set; } = "response";

		public string RequestId { get; set; } = string.Empty;

		public string? SessionId { get; set; }

		public bool Success { get; set; }

		public TResult? Result { get; set; }

		public BridgeError? Error { get; set; }
	}
	public sealed class BridgeRuntimeDescriptor
	{
		public int ProcessId { get; set; }

		public string BridgeInstanceId { get; set; } = string.Empty;

		public string PipeName { get; set; } = string.Empty;

		public string AuthToken { get; set; } = string.Empty;

		public int ProtocolVersion { get; set; } = 1;

		public string PluginVersion { get; set; } = string.Empty;

		public DateTimeOffset CreatedAtUtc { get; set; }
	}
	public sealed class EmptyPayload
	{
	}
	public sealed class HandshakeRequest
	{
		public string BridgeInstanceId { get; set; } = string.Empty;

		public string AuthToken { get; set; } = string.Empty;

		public string ClientName { get; set; } = string.Empty;

		public string ClientVersion { get; set; } = string.Empty;
	}
	public sealed class HandshakeResponse
	{
		public bool Accepted { get; set; }

		public string BridgeInstanceId { get; set; } = string.Empty;

		public int ProtocolVersion { get; set; } = 1;

		public string PluginVersion { get; set; } = string.Empty;
	}
	public static class ProtocolConstants
	{
		public const int CurrentVersion = 1;

		public const int DefaultMaxFrameBytes = 1048576;
	}
}
namespace Spherewright.Contracts.Progression
{
	public sealed class ProgressionStateSnapshot
	{
		public string SessionId { get; set; } = string.Empty;

		public int PlanetId { get; set; }

		public long CapturedAtGameTick { get; set; }

		public string StateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;

		public string SelectionStateHash { get; set; } = string.Empty;

		public int SelectionStateHashVersion { get; set; } = 1;

		public int CurrentTechId { get; set; }

		public string? CurrentTechName { get; set; }

		public List<int> TechQueue { get; set; } = new List<int>();

		public List<TechStateSnapshot> Technologies { get; set; } = new List<TechStateSnapshot>();
	}
	public sealed class TechStateSnapshot
	{
		public int TechId { get; set; }

		public string Name { get; set; } = string.Empty;

		public bool Unlocked { get; set; }

		public int CurrentLevel { get; set; }

		public int MaximumLevel { get; set; }

		public long HashUploaded { get; set; }

		public long HashRequired { get; set; }

		public long UnlockTick { get; set; }

		public bool IsLabTech { get; set; }

		public bool IsQueued { get; set; }

		public List<int> PrerequisiteTechIds { get; set; } = new List<int>();

		public List<int> UnlockRecipeIds { get; set; } = new List<int>();

		public List<TechMatrixRequirement> MatrixRequirements { get; set; } = new List<TechMatrixRequirement>();

		public List<TechItemRequirement> ItemRequirements { get; set; } = new List<TechItemRequirement>();
	}
	public sealed class TechMatrixRequirement
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int PointsPerHash { get; set; }

		public long RequiredItemCount { get; set; }
	}
	public sealed class TechItemRequirement
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int PointsPerHash { get; set; }

		public long RequiredItemCount { get; set; }

		public bool IsMatrix { get; set; }
	}
	public sealed class RecipeCatalogSnapshot
	{
		public string SessionId { get; set; } = string.Empty;

		public int PlanetId { get; set; }

		public long CapturedAtGameTick { get; set; }

		public List<ItemCatalogEntry> Items { get; set; } = new List<ItemCatalogEntry>();

		public List<RecipeCatalogEntry> Recipes { get; set; } = new List<RecipeCatalogEntry>();

		public RuntimeDependencyGraph FirstRedMatrixDependencies { get; set; } = new RuntimeDependencyGraph();
	}
	public sealed class ItemCatalogEntry
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int StackSize { get; set; }

		public bool IsRaw { get; set; }

		public bool CanBuild { get; set; }

		public bool Unlocked { get; set; }

		public int? HandcraftRecipeId { get; set; }
	}
	public sealed class RecipeCatalogEntry
	{
		public int RecipeId { get; set; }

		public string Name { get; set; } = string.Empty;

		public string RecipeType { get; set; } = string.Empty;

		public bool Handcraft { get; set; }

		public bool Unlocked { get; set; }

		public int TimeSpend { get; set; }

		public int? PrerequisiteTechId { get; set; }

		public string? PrerequisiteTechName { get; set; }

		public List<CatalogItemAmount> Inputs { get; set; } = new List<CatalogItemAmount>();

		public List<CatalogItemAmount> Outputs { get; set; } = new List<CatalogItemAmount>();
	}
	public sealed class CatalogItemAmount
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int Count { get; set; }
	}
	public sealed class RuntimeDependencyGraph
	{
		public int TargetItemId { get; set; }

		public string TargetItemName { get; set; } = string.Empty;

		public List<int> ItemIds { get; set; } = new List<int>();

		public List<int> RecipeIds { get; set; } = new List<int>();

		public List<RuntimeDependencyEdge> Edges { get; set; } = new List<RuntimeDependencyEdge>();
	}
	public sealed class RuntimeDependencyEdge
	{
		public string FromKind { get; set; } = string.Empty;

		public int FromId { get; set; }

		public string ToKind { get; set; } = string.Empty;

		public int ToId { get; set; }
	}
}
namespace Spherewright.Contracts.Power
{
	public sealed class PowerSummarySnapshot
	{
		public string SessionId { get; set; } = string.Empty;

		public int PlanetId { get; set; }

		public long CapturedAtGameTick { get; set; }

		public long TotalEnergyRequired { get; set; }

		public long TotalEnergyServed { get; set; }

		public long TotalEnergyCapacity { get; set; }

		public long TotalEnergyGenerated { get; set; }

		public List<PowerNetworkSnapshot> Networks { get; set; } = new List<PowerNetworkSnapshot>();
	}
	public sealed class PowerNetworkSnapshot
	{
		public int NetworkId { get; set; }

		public int NodeCount { get; set; }

		public int ConsumerCount { get; set; }

		public int GeneratorCount { get; set; }

		public int AccumulatorCount { get; set; }

		public int ExchangerCount { get; set; }

		public long EnergyRequired { get; set; }

		public long EnergyServed { get; set; }

		public long EnergyCapacity { get; set; }

		public long EnergyGenerated { get; set; }

		public long EnergyStored { get; set; }

		public double ConsumerRatio { get; set; }

		public double GeneratorRatio { get; set; }
	}
}
namespace Spherewright.Contracts.Players
{
	public sealed class PlayerStateSnapshot
	{
		public string SessionId { get; set; } = string.Empty;

		public int PlanetId { get; set; }

		public long CapturedAtGameTick { get; set; }

		public string StateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;

		public Vector3Snapshot Position { get; set; } = new Vector3Snapshot();

		public string MovementState { get; set; } = string.Empty;

		public bool IsAlive { get; set; }

		public bool IsOnPlanet { get; set; }

		public bool IsFlying { get; set; }

		public bool IsSailing { get; set; }

		public float Speed { get; set; }

		public double CoreEnergy { get; set; }

		public double CoreEnergyCapacity { get; set; }

		public double ReactorEnergy { get; set; }

		public int ReactorItemId { get; set; }

		public string? ReactorItemName { get; set; }

		public int ReactorItemInc { get; set; }

		public bool AutoReplenishFuel { get; set; }

		public int FuelStorageSlotCount { get; set; }

		public int FuelStorageOccupiedSlotCount { get; set; }

		public List<PlayerInventoryItem> FuelStorage { get; set; } = new List<PlayerInventoryItem>();

		public float BuildArea { get; set; }

		public int InventorySlotCount { get; set; }

		public int InventoryOccupiedSlotCount { get; set; }

		public List<PlayerInventoryItem> Inventory { get; set; } = new List<PlayerInventoryItem>();

		public PlayerInventoryItem? InHandItem { get; set; }

		public bool AutoManageResearchItems { get; set; }

		public double MechaResearchPower { get; set; }

		public List<MechaResearchItemSnapshot> MechaResearchItemBuffer { get; set; } = new List<MechaResearchItemSnapshot>();

		public List<HandcraftTaskSnapshot> HandcraftQueue { get; set; } = new List<HandcraftTaskSnapshot>();

		public ConstructionDroneSnapshot ConstructionDrones { get; set; } = new ConstructionDroneSnapshot();
	}
	public sealed class MechaResearchItemSnapshot
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int PointCount { get; set; }

		public int WholeItemCount { get; set; }

		public int RemainderPoints { get; set; }
	}
	public sealed class PlayerInventoryItem
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int Count { get; set; }

		public int Inc { get; set; }

		public int SlotCount { get; set; }
	}
	public sealed class HandcraftTaskSnapshot
	{
		public int QueueIndex { get; set; }

		public int RecipeId { get; set; }

		public string RecipeName { get; set; } = string.Empty;

		public int RemainingCraftCount { get; set; }

		public int Progress { get; set; }

		public int ProgressRequired { get; set; }

		public int ParentTaskIndex { get; set; }

		public bool IngredientsReserved { get; set; }

		public List<PlayerItemAmount> Inputs { get; set; } = new List<PlayerItemAmount>();

		public List<PlayerItemAmount> Outputs { get; set; } = new List<PlayerItemAmount>();
	}
	public sealed class PlayerItemAmount
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int Count { get; set; }

		public int BufferedCount { get; set; }
	}
	public sealed class ConstructionDroneSnapshot
	{
		public bool Enabled { get; set; }

		public bool ConstructionEnabled { get; set; }

		public int Total { get; set; }

		public int Alive { get; set; }

		public int Idle { get; set; }

		public int Working { get; set; }

		public int PendingBuildTargets { get; set; }

		public int PendingRepairTargets { get; set; }
	}
}
namespace Spherewright.Contracts.Logistics
{
	public sealed class LogisticsStationSnapshot
	{
		public string SessionId { get; set; } = string.Empty;

		public int PlanetId { get; set; }

		public int EntityId { get; set; }

		public int StationId { get; set; }

		public int GalacticStationId { get; set; }

		public int BuildingItemId { get; set; }

		public string BuildingName { get; set; } = string.Empty;

		public Vector3Snapshot Position { get; set; } = new Vector3Snapshot();

		public bool IsInterstellar { get; set; }

		public bool IsCollector { get; set; }

		public bool IsVeinCollector { get; set; }

		public int? PowerNetworkId { get; set; }

		public double? PowerServeRatio { get; set; }

		public long Energy { get; set; }

		public long EnergyCapacity { get; set; }

		public long RequestedChargeEnergyPerTick { get; set; }

		public long RequestedChargePowerWatts { get; set; }

		public long MaximumChargeEnergyPerTick { get; set; }

		public long MaximumChargePowerWatts { get; set; }

		public int WarperCount { get; set; }

		public int WarperCapacity { get; set; }

		public int IdleDroneCount { get; set; }

		public int DroneCapacity { get; set; }

		public int WorkingDroneCount { get; set; }

		public int IdleVesselCount { get; set; }

		public int VesselCapacity { get; set; }

		public int WorkingVesselCount { get; set; }

		public double DroneTripRangeRaw { get; set; }

		public double VesselTripRangeRaw { get; set; }

		public bool IncludeOrbitCollectors { get; set; }

		public double WarpEnableDistanceRaw { get; set; }

		public bool WarpersRequired { get; set; }

		public int DroneDeliverySetting { get; set; }

		public int VesselDeliverySetting { get; set; }

		public int PilerCount { get; set; }

		public bool DroneAutoReplenish { get; set; }

		public bool VesselAutoReplenish { get; set; }

		public long RemoteGroupMask { get; set; }

		public string RemoteRoutePriority { get; set; } = string.Empty;

		public List<int> NeededItemIds { get; set; } = new List<int>();

		public List<LogisticsStationStorageSlotSnapshot> StorageSlots { get; set; } = new List<LogisticsStationStorageSlotSnapshot>();

		public List<LogisticsStationBeltSlotSnapshot> BeltSlots { get; set; } = new List<LogisticsStationBeltSlotSnapshot>();

		public long CapturedAtGameTick { get; set; }

		public string StateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;

		public string ConfigurationStateHash { get; set; } = string.Empty;

		public int ConfigurationStateHashVersion { get; set; } = 1;

		public string FleetStateHash { get; set; } = string.Empty;

		public int FleetStateHashVersion { get; set; } = 1;
	}
	public sealed class LogisticsStationStorageSlotSnapshot
	{
		public int Index { get; set; }

		public int ItemId { get; set; }

		public string? ItemName { get; set; }

		public int Count { get; set; }

		public int Inc { get; set; }

		public int MaximumCount { get; set; }

		public int LocalOrder { get; set; }

		public int RemoteOrder { get; set; }

		public int TotalOrdered { get; set; }

		public int LocalSupplyCount { get; set; }

		public int LocalDemandCount { get; set; }

		public int RemoteSupplyCount { get; set; }

		public int RemoteDemandCount { get; set; }

		public string LocalLogic { get; set; } = string.Empty;

		public string RemoteLogic { get; set; } = string.Empty;

		public int KeepMode { get; set; }

		public float KeepIncRatio { get; set; }
	}
	public sealed class LogisticsStationBeltSlotSnapshot
	{
		public int Index { get; set; }

		public string Direction { get; set; } = string.Empty;

		public int BeltComponentId { get; set; }

		public int BeltEntityId { get; set; }

		public int StorageIndex { get; set; }

		public int Counter { get; set; }
	}
}
namespace Spherewright.Contracts.Journals
{
	public static class GameplayJournalEventKinds
	{
		public const string ManualItemFirst = "manual_item_first";

		public const string ProductionLineItemFirst = "production_line_item_first";

		public const string TechnologyFirstSelected = "technology_first_selected";

		public const string UpgradeFirstSelected = "upgrade_first_selected";
	}
	public static class GameplayJournalTrackingModes
	{
		public const string FromNewGame = "from_new_game";

		public const string AttachedExistingSave = "attached_existing_save";
	}
	public sealed class GameplayJournalSnapshot
	{
		public string SessionId { get; set; } = string.Empty;

		public string JournalId { get; set; } = string.Empty;

		public string TrackingMode { get; set; } = string.Empty;

		public bool HistoricalCoverageComplete { get; set; }

		public string CreatedAtActualTime { get; set; } = string.Empty;

		public long TrackingStartedAtGameTick { get; set; }

		public string TrackingStartedAtGameTime { get; set; } = string.Empty;

		public long CapturedAtGameTick { get; set; }

		public long DurableThroughSequence { get; set; }

		public bool PersistencePending { get; set; }

		public string? PersistenceError { get; set; }

		public List<GameplayJournalEntry> Entries { get; set; } = new List<GameplayJournalEntry>();
	}
	public sealed class GameplayJournalEntry
	{
		public long Sequence { get; set; }

		public string Kind { get; set; } = string.Empty;

		public int ItemId { get; set; }

		public int TechId { get; set; }

		public string Name { get; set; } = string.Empty;

		public long ObservedCount { get; set; }

		public string ActualTime { get; set; } = string.Empty;

		public long GameTick { get; set; }

		public string GameTime { get; set; } = string.Empty;

		public string Source { get; set; } = string.Empty;
	}
}
namespace Spherewright.Contracts.Factory
{
	public sealed class AssemblerSnapshot
	{
		public int PlanetId { get; set; }

		public int EntityId { get; set; }

		public int ComponentId { get; set; }

		public int BuildingItemId { get; set; }

		public string BuildingName { get; set; } = string.Empty;

		public int RecipeId { get; set; }

		public string? RecipeName { get; set; }

		public int TimeSpent { get; set; }

		public int TimeRequired { get; set; }

		public bool IsWorking { get; set; }

		public Vector3Snapshot Position { get; set; } = new Vector3Snapshot();

		public long Revision { get; set; }
	}
	public sealed class BasicProductionLinePlan
	{
		public string PlanToken { get; set; } = string.Empty;

		public DateTimeOffset ExpiresAtUtc { get; set; }

		public string SessionId { get; set; } = string.Empty;

		public long ExpectedRevision { get; set; }

		public bool DryRun { get; set; } = true;

		public bool CommitAllowed { get; set; }

		public int RecipeId { get; set; }

		public string RecipeName { get; set; } = string.Empty;

		public int InputItemId { get; set; }

		public string InputItemName { get; set; } = string.Empty;

		public int InputItemCount { get; set; }

		public int OutputItemId { get; set; }

		public string OutputItemName { get; set; } = string.Empty;

		public List<PlannedBuildingSnapshot> Buildings { get; set; } = new List<PlannedBuildingSnapshot>();

		public List<string> Warnings { get; set; } = new List<string>();
	}
	public sealed class PlannedBuildingSnapshot
	{
		public string Role { get; set; } = string.Empty;

		public int ItemId { get; set; }

		public string ItemName { get; set; } = string.Empty;

		public Vector3Snapshot Position { get; set; } = new Vector3Snapshot();
	}
	public sealed class BasicProductionLineResult
	{
		public string ActionId { get; set; } = string.Empty;

		public bool Completed { get; set; }

		public bool Changed { get; set; }

		public bool IdempotentReplay { get; set; }

		public string SessionId { get; set; } = string.Empty;

		public long Revision { get; set; }

		public int RecipeId { get; set; }

		public int InputItemId { get; set; }

		public int InputItemCount { get; set; }

		public int OutputItemId { get; set; }

		public BasicProductionLineEntities Entities { get; set; } = new BasicProductionLineEntities();

		public bool RecipeVerified { get; set; }

		public bool ConnectionsVerified { get; set; }

		public bool InputStockVerified { get; set; }

		public bool Saved { get; set; }

		public string ProductionState { get; set; } = string.Empty;
	}
	public sealed class BasicProductionLineEntities
	{
		public int InputStorageEntityId { get; set; }

		public int AssemblerEntityId { get; set; }

		public int OutputStorageEntityId { get; set; }

		public int InputInserterEntityId { get; set; }

		public int OutputInserterEntityId { get; set; }

		public int PowerGeneratorEntityId { get; set; }
	}
	public sealed class BasicProductionLineSnapshot
	{
		public string ActionId { get; set; } = string.Empty;

		public string SessionId { get; set; } = string.Empty;

		public long Revision { get; set; }

		public bool StructureValid { get; set; }

		public bool ConnectionsValid { get; set; }

		public bool RecipeValid { get; set; }

		public bool PowerNetworkValid { get; set; }

		public bool Producing { get; set; }

		public string ProductionState { get; set; } = string.Empty;

		public int RecipeId { get; set; }

		public int InputItemId { get; set; }

		public int InputStorageCount { get; set; }

		public int OutputItemId { get; set; }

		public int OutputStorageCount { get; set; }

		public bool AssemblerWorking { get; set; }

		public BasicProductionLineEntities Entities { get; set; } = new BasicProductionLineEntities();
	}
	public sealed class BuildCatalog
	{
		public int PlanetId { get; set; }

		public long Revision { get; set; }

		public Vector3Snapshot PlayerPosition { get; set; } = new Vector3Snapshot();

		public float PlayerBuildArea { get; set; }

		public bool SandboxToolsEnabled { get; set; }

		public List<BuildCatalogItem> Buildings { get; set; } = new List<BuildCatalogItem>();

		public List<BuildCatalogRecipe> Recipes { get; set; } = new List<BuildCatalogRecipe>();

		public BasicLineRecommendation? RecommendedBasicLine { get; set; }
	}
	public sealed class BuildCatalogItem
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public string Role { get; set; } = string.Empty;

		public int ModelIndex { get; set; }

		public int Grade { get; set; }

		public int BuildMode { get; set; }

		public bool Unlocked { get; set; }

		public bool Available { get; set; }

		public string RecipeType { get; set; } = string.Empty;

		public int SlotCount { get; set; }

		public float RoughRadius { get; set; }

		public float PowerConnectDistance { get; set; }

		public float PowerCoverRadius { get; set; }
	}
	public sealed class BuildCatalogRecipe
	{
		public int RecipeId { get; set; }

		public string Name { get; set; } = string.Empty;

		public string RecipeType { get; set; } = string.Empty;

		public bool Unlocked { get; set; }

		public int TimeSpend { get; set; }

		public List<BuildCatalogIngredient> Inputs { get; set; } = new List<BuildCatalogIngredient>();

		public List<BuildCatalogIngredient> Outputs { get; set; } = new List<BuildCatalogIngredient>();
	}
	public sealed class BuildCatalogIngredient
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int Count { get; set; }

		public bool RawMaterial { get; set; }
	}
	public sealed class BasicLineRecommendation
	{
		public int StorageItemId { get; set; }

		public int AssemblerItemId { get; set; }

		public int InserterItemId { get; set; }

		public int PowerGeneratorItemId { get; set; }

		public int RecipeId { get; set; }

		public int InputItemId { get; set; }

		public int OutputItemId { get; set; }
	}
	public sealed class CommitBasicProductionLineRequest
	{
		public string PlanToken { get; set; } = string.Empty;

		public string IdempotencyKey { get; set; } = string.Empty;
	}
	public static class FactoryObjectKinds
	{
		public const string Entity = "entity";

		public const string Prebuild = "prebuild";
	}
	public sealed class ListFactoryEntitiesRequest
	{
		public int PlanetId { get; set; }

		public string? ObjectKind { get; set; }

		public string? ComponentKind { get; set; }

		public int? ItemId { get; set; }

		public int Limit { get; set; } = 50;

		public string? Cursor { get; set; }
	}
	public sealed class ListFactoryEntitiesResult
	{
		public string SessionId { get; set; } = string.Empty;

		public int PlanetId { get; set; }

		public long CapturedAtGameTick { get; set; }

		public string SnapshotId { get; set; } = string.Empty;

		public DateTimeOffset SnapshotExpiresAtUtc { get; set; }

		public List<FactoryEntitySnapshot> Entities { get; set; } = new List<FactoryEntitySnapshot>();

		public string? NextCursor { get; set; }
	}
	public sealed class InspectFactoryEntityRequest
	{
		public int PlanetId { get; set; }

		public int ObjectId { get; set; }
	}
	public sealed class FactoryEntitySnapshot
	{
		public string SessionId { get; set; } = string.Empty;

		public int PlanetId { get; set; }

		public int ObjectId { get; set; }

		public string ObjectKind { get; set; } = string.Empty;

		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public string ComponentKind { get; set; } = string.Empty;

		public Vector3Snapshot Position { get; set; } = new Vector3Snapshot();

		public QuaternionSnapshot Rotation { get; set; } = new QuaternionSnapshot();

		public int RecipeId { get; set; }

		public string? RecipeName { get; set; }

		public bool IsWorking { get; set; }

		public int Progress { get; set; }

		public int ProgressRequired { get; set; }

		public int? PowerNetworkId { get; set; }

		public long? PowerDemandPerTick { get; set; }

		public double? PowerServeRatio { get; set; }

		public List<FactoryConnectionSnapshot> Connections { get; set; } = new List<FactoryConnectionSnapshot>();

		public List<FactoryBufferSnapshot> Buffers { get; set; } = new List<FactoryBufferSnapshot>();

		public List<int> ResourceNodeIds { get; set; } = new List<int>();

		public LogisticsStationSnapshot? LogisticsStation { get; set; }

		public int? PickTargetObjectId { get; set; }

		public int? InsertTargetObjectId { get; set; }

		public int? FilterItemId { get; set; }

		public string? FilterItemName { get; set; }

		public string? InserterStage { get; set; }

		public int? InserterStackCount { get; set; }

		public int? RequiredBuildItemCount { get; set; }

		public float? ConstructionProgress { get; set; }

		public long CapturedAtGameTick { get; set; }

		public string StateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;

		public string ConfigurationStateHash { get; set; } = string.Empty;

		public int ConfigurationStateHashVersion { get; set; } = 1;

		public string EndpointStateHash { get; set; } = string.Empty;

		public int EndpointStateHashVersion { get; set; } = 1;
	}
	public sealed class QuaternionSnapshot
	{
		public float X { get; set; }

		public float Y { get; set; }

		public float Z { get; set; }

		public float W { get; set; }
	}
	public sealed class FactoryConnectionSnapshot
	{
		public int Slot { get; set; }

		public bool IsOutput { get; set; }

		public int OtherObjectId { get; set; }

		public int OtherSlot { get; set; }
	}
	public sealed class FactoryBufferSnapshot
	{
		public string Role { get; set; } = string.Empty;

		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int Count { get; set; }

		public int Inc { get; set; }
	}
	public sealed class InspectAssemblerRequest
	{
		public int EntityId { get; set; }
	}
	public sealed class InspectBasicProductionLineRequest
	{
		public string ActionId { get; set; } = string.Empty;
	}
	public sealed class ListAssemblersRequest
	{
		public int Limit { get; set; } = 50;

		public string? Cursor { get; set; }
	}
	public sealed class ListAssemblersResult
	{
		public List<AssemblerSnapshot> Assemblers { get; set; } = new List<AssemblerSnapshot>();

		public string? NextCursor { get; set; }

		public long Revision { get; set; }
	}
	public sealed class PrepareBasicProductionLineRequest
	{
		public long ExpectedRevision { get; set; }

		public int InputItemCount { get; set; } = 20;
	}
	public sealed class Vector3Snapshot
	{
		public float X { get; set; }

		public float Y { get; set; }

		public float Z { get; set; }
	}
}
namespace Spherewright.Contracts.Errors
{
	public sealed class BridgeError
	{
		public string Code { get; set; } = string.Empty;

		public string Message { get; set; } = string.Empty;

		public bool Retryable { get; set; }

		public string Recovery { get; set; } = string.Empty;

		public static BridgeError Create(string code, string message, bool retryable, string recovery)
		{
			return new BridgeError
			{
				Code = code,
				Message = message,
				Retryable = retryable,
				Recovery = recovery
			};
		}
	}
	public static class BridgeErrorCodes
	{
		public const string BridgeNotReady = "BRIDGE_NOT_READY";

		public const string AuthFailed = "AUTH_FAILED";

		public const string ServerBusy = "SERVER_BUSY";

		public const string QueueFull = "QUEUE_FULL";

		public const string GameNotLoaded = "GAME_NOT_LOADED";

		public const string NoLocalPlanet = "NO_LOCAL_PLANET";

		public const string UnsupportedGameVersion = "UNSUPPORTED_GAME_VERSION";

		public const string PeacefulModeRequired = "PEACEFUL_MODE_REQUIRED";

		public const string PeacefulModeUnknown = "PEACEFUL_MODE_UNKNOWN";

		public const string SandboxModeActive = "SANDBOX_MODE_ACTIVE";

		public const string SandboxModeUnknown = "SANDBOX_MODE_UNKNOWN";

		public const string NormalResourceMultiplierRequired = "NORMAL_RESOURCE_MULTIPLIER_REQUIRED";

		public const string WritesDisabled = "WRITES_DISABLED";

		public const string UserConfirmationRequired = "USER_CONFIRMATION_REQUIRED";

		public const string WriteSubsystemQuarantined = "WRITE_SUBSYSTEM_QUARANTINED";

		public const string InvalidRequest = "INVALID_REQUEST";

		public const string InvalidEntity = "INVALID_ENTITY";

		public const string InvalidResourceTarget = "INVALID_RESOURCE_TARGET";

		public const string TargetIdentityMismatch = "TARGET_IDENTITY_MISMATCH";

		public const string InvalidRecipe = "INVALID_RECIPE";

		public const string RecipeNotSupportedByBuilding = "RECIPE_NOT_SUPPORTED_BY_BUILDING";

		public const string RecipeLocked = "RECIPE_LOCKED";

		public const string InvalidTechnology = "INVALID_TECHNOLOGY";

		public const string TechnologyLocked = "TECHNOLOGY_LOCKED";

		public const string TechnologyPrerequisiteNotMet = "TECHNOLOGY_PREREQUISITE_NOT_MET";

		public const string TargetOutOfRange = "TARGET_OUT_OF_RANGE";

		public const string TargetUnreachable = "TARGET_UNREACHABLE";

		public const string PlayerStateUnavailable = "PLAYER_STATE_UNAVAILABLE";

		public const string PlayerBusy = "PLAYER_BUSY";

		public const string InventoryInsufficient = "INVENTORY_INSUFFICIENT";

		public const string InventoryFull = "INVENTORY_FULL";

		public const string MechaEnergyInsufficient = "MECHA_ENERGY_INSUFFICIENT";

		public const string BuildLocationInvalid = "BUILD_LOCATION_INVALID";

		public const string BuildItemMissing = "BUILD_ITEM_MISSING";

		public const string BuildConnectionInvalid = "BUILD_CONNECTION_INVALID";

		public const string PrebuildNotCompleted = "PREBUILD_NOT_COMPLETED";

		public const string NoPower = "NO_POWER";

		public const string AssemblerNotIdle = "ASSEMBLER_NOT_IDLE";

		public const string AssemblerBuffersNotEmpty = "ASSEMBLER_BUFFERS_NOT_EMPTY";

		public const string StaleSession = "STALE_SESSION";

		public const string SessionNotOwned = "SESSION_NOT_OWNED";

		public const string StaleState = "STALE_STATE";

		public const string StaleRevision = "STALE_REVISION";

		public const string StaleCursor = "STALE_CURSOR";

		public const string PlanNotFound = "PLAN_NOT_FOUND";

		public const string PlanExpired = "PLAN_EXPIRED";

		public const string PlanAlreadyBound = "PLAN_ALREADY_BOUND";

		public const string IdempotencyConflict = "IDEMPOTENCY_CONFLICT";

		public const string IdempotencyCapacityExceeded = "IDEMPOTENCY_CAPACITY_EXCEEDED";

		public const string ActionNotFound = "ACTION_NOT_FOUND";

		public const string ActionRejected = "ACTION_REJECTED";

		public const string ActionNotStarted = "ACTION_NOT_STARTED";

		public const string ActionInProgress = "ACTION_IN_PROGRESS";

		public const string ActionFailed = "ACTION_FAILED";

		public const string ActionOutcomeUnknown = "ACTION_OUTCOME_UNKNOWN";

		public const string RequestTimeout = "REQUEST_TIMEOUT";

		public const string InternalError = "INTERNAL_ERROR";
	}
}
namespace Spherewright.Contracts.Celestial
{
	public sealed class LocalStarSystemSnapshot
	{
		public string SessionId { get; set; } = string.Empty;

		public int LocalPlanetId { get; set; }

		public int StarId { get; set; }

		public string StarName { get; set; } = string.Empty;

		public long CapturedAtGameTick { get; set; }

		public string StateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;

		public List<PlanetSnapshot> Planets { get; set; } = new List<PlanetSnapshot>();
	}
	public sealed class PlanetSnapshot
	{
		public int PlanetId { get; set; }

		public string Name { get; set; } = string.Empty;

		public string PlanetType { get; set; } = string.Empty;

		public int ThemeId { get; set; }

		public string ThemeName { get; set; } = string.Empty;

		public bool IsCurrentPlanet { get; set; }

		public bool IsBirthPlanet { get; set; }

		public bool IsGasGiant { get; set; }

		public bool FactoryLoaded { get; set; }

		public float RealRadius { get; set; }

		public float OrbitRadius { get; set; }

		public double DistanceFromPlayer { get; set; }

		public UniversalPositionSnapshot UniversalPosition { get; set; } = new UniversalPositionSnapshot();

		public List<string> PotentialResourceTypes { get; set; } = new List<string>();
	}
	public sealed class UniversalPositionSnapshot
	{
		public double X { get; set; }

		public double Y { get; set; }

		public double Z { get; set; }
	}
}
namespace Spherewright.Contracts.Actions
{
	public static class MovementFailureKinds
	{
		public const string PositionStalled = "position_stalled";

		public const string RouteStalled = "route_stalled";

		public const string BoundedTimeout = "bounded_timeout";
	}
	public sealed class GetActionResultRequest
	{
		public string ActionId { get; set; } = string.Empty;
	}
	public sealed class ActionResultSnapshot
	{
		public string ActionId { get; set; } = string.Empty;

		public string ActionKind { get; set; } = string.Empty;

		public string State { get; set; } = string.Empty;

		public bool Terminal { get; set; }

		public bool Succeeded { get; set; }

		public string? SessionId { get; set; }

		public int? PlanetId { get; set; }

		public string? Message { get; set; }

		public string? IdempotencyKey { get; set; }

		public long? StartedAtGameTick { get; set; }

		public long? CompletedAtGameTick { get; set; }

		public string? BeforeStateHash { get; set; }

		public string? AfterStateHash { get; set; }

		public int? TargetObjectId { get; set; }

		public List<int> TargetObjectIds { get; set; } = new List<int>();

		public int? TargetItemId { get; set; }

		public int? RequestedCount { get; set; }

		public int? BeforeTargetAmount { get; set; }

		public int? AfterTargetAmount { get; set; }

		public List<ActionItemDelta> ItemDeltas { get; set; } = new List<ActionItemDelta>();

		public bool ReconciledFromOutcomeUnknown { get; set; }

		public long? ReconciledAtGameTick { get; set; }

		public string? FlightCheckpointId { get; set; }

		public string? FlightCheckpointReloadToken { get; set; }

		public long? FlightCheckpointGameTick { get; set; }

		public bool Stalled { get; set; }

		public bool RecoveryRequired { get; set; }

		public string? FailureKind { get; set; }

		public long? StalledGameTicks { get; set; }

		public double? RemainingDistance { get; set; }

		public bool DoNotRetrySameTarget { get; set; }

		public string? RecommendedRecovery { get; set; }

		public double? RecommendedShortMoveDistanceMeters { get; set; }

		public double? OrthogonalProbeDistanceMeters { get; set; }

		public int? MaximumOrthogonalProbeAttempts { get; set; }
	}
	public static class NormalActionKinds
	{
		public const string Move = "move";

		public const string InterplanetaryFlight = "interplanetary-flight";

		public const string Harvest = "harvest";

		public const string Handcraft = "handcraft";

		public const string SelectResearch = "select-research";

		public const string Build = "build";

		public const string Dismantle = "dismantle";

		public const string Transfer = "transfer";

		public const string LogisticsStationFleetTransfer = "logistics-station-fleet-transfer";

		public const string ConfigureBuilding = "configure-building";

		public const string Refuel = "refuel";

		public const string Save = "save";

		public const string ReconcileQuarantine = "reconcile-quarantine";

		public const string UserSaveImport = "user-save-import";
	}
	public static class NormalBuildKinds
	{
		public const string Core = "core";

		public const string Resource = "resource";

		public const string Belt = "belt";

		public const string Inserter = "inserter";
	}
	public static class TransferDirections
	{
		public const string PlayerToStorage = "player-to-storage";

		public const string StorageToPlayer = "storage-to-player";
	}
	public static class LogisticsStationFleetTransferDirections
	{
		public const string PlayerToStation = "player-to-station";

		public const string StationToPlayer = "station-to-player";
	}
	public static class LogisticsFleetItemIds
	{
		public const int Drone = 5001;

		public const int Vessel = 5002;
	}
	public static class BuildingConfigurationModes
	{
		public const string Production = "production";

		public const string Research = "research";

		public const string SorterFilter = "sorter-filter";

		public const string LogisticsStationStorage = "logistics-station-storage";

		public const string LogisticsStationBelt = "logistics-station-belt";

		public const string LogisticsStationCharge = "logistics-station-charge";
	}
	public static class LogisticsStorageLogics
	{
		public const string None = "none";

		public const string Supply = "supply";

		public const string Demand = "demand";
	}
	public static class NormalActionStates
	{
		public const string Reserved = "reserved";

		public const string Queued = "queued";

		public const string Executing = "executing";

		public const string WaitingForGame = "waiting_for_game";

		public const string Completed = "completed";

		public const string ActionFailed = "action_failed";

		public const string RecoveryRequired = "recovery_required";

		public const string OutcomeUnknown = "outcome_unknown";
	}
	public sealed class PrepareMoveRequest
	{
		public int PlanetId { get; set; }

		public Vector3Snapshot Target { get; set; } = new Vector3Snapshot();

		public float ArrivalTolerance { get; set; } = 1.5f;

		public string ExpectedPlayerStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareHarvestRequest
	{
		public int PlanetId { get; set; }

		public string ResourceKind { get; set; } = string.Empty;

		public int NodeId { get; set; }

		public int RequestedYieldCount { get; set; } = 1;

		public string ExpectedResourceStateHash { get; set; } = string.Empty;

		public string ExpectedPlayerStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareHandcraftRequest
	{
		public int PlanetId { get; set; }

		public int RecipeId { get; set; }

		public int Count { get; set; } = 1;

		public string ExpectedPlayerStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareSelectResearchRequest
	{
		public int PlanetId { get; set; }

		public int TechId { get; set; }

		public string ExpectedSelectionStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareBuildRequest
	{
		public int PlanetId { get; set; }

		public int BuildingItemId { get; set; }

		public float PreferredDistance { get; set; } = 12f;

		public Vector3Snapshot? PreferredPosition { get; set; }

		public float? PreferredYaw { get; set; }

		public int? ResourceNodeId { get; set; }

		public string? ExpectedResourceStateHash { get; set; }

		public int? SourceObjectId { get; set; }

		public string? ExpectedSourceStateHash { get; set; }

		public int? DestinationObjectId { get; set; }

		public string? ExpectedDestinationStateHash { get; set; }

		public Vector3Snapshot? PathEnd { get; set; }

		public float PathLength { get; set; } = 6f;

		public string ExpectedPlayerStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareConfigureBuildingRequest
	{
		public int PlanetId { get; set; }

		public int EntityId { get; set; }

		public int RecipeId { get; set; }

		public string Mode { get; set; } = "production";

		public int TechId { get; set; }

		public int FilterItemId { get; set; }

		public int StationStorageIndex { get; set; } = -1;

		public int StationBeltSlotIndex { get; set; } = -1;

		public int StationBeltStorageIndex { get; set; } = -1;

		public int StationItemId { get; set; }

		public int StationMaximumCount { get; set; }

		public string StationLocalLogic { get; set; } = "none";

		public string StationRemoteLogic { get; set; } = "none";

		public long StationMaximumChargePowerWatts { get; set; }

		public string ExpectedStationConfigurationStateHash { get; set; } = string.Empty;

		public string ExpectedFactoryStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareTransferRequest
	{
		public int PlanetId { get; set; }

		public string Direction { get; set; } = string.Empty;

		public int StorageEntityId { get; set; }

		public int ItemId { get; set; }

		public int Count { get; set; } = 1;

		public string ExpectedPlayerStateHash { get; set; } = string.Empty;

		public string ExpectedStorageStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareRefuelRequest
	{
		public int PlanetId { get; set; }

		public int ItemId { get; set; }

		public int Count { get; set; } = 1;

		public string ExpectedPlayerStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareSaveRequest
	{
		public int PlanetId { get; set; }

		public long ExpectedRevision { get; set; }

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareDismantleRequest
	{
		public int PlanetId { get; set; }

		public int ObjectId { get; set; }

		public string ExpectedEndpointStateHash { get; set; } = string.Empty;

		public string ExpectedPlayerStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareLogisticsStationFleetTransferRequest
	{
		public int PlanetId { get; set; }

		public int StationEntityId { get; set; }

		public string Direction { get; set; } = string.Empty;

		public int ItemId { get; set; }

		public int Count { get; set; } = 1;

		public string ExpectedPlayerStateHash { get; set; } = string.Empty;

		public string ExpectedStationFleetStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareInterplanetaryFlightRequest
	{
		public int PlanetId { get; set; }

		public int DestinationPlanetId { get; set; }

		public string ExpectedPlayerStateHash { get; set; } = string.Empty;

		public string ExpectedStarSystemStateHash { get; set; } = string.Empty;

		public double MinimumCoreEnergyRatio { get; set; } = 0.95;

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class PrepareQuarantineReconciliationRequest
	{
		public int PlanetId { get; set; }

		public string ActionId { get; set; } = string.Empty;

		public long ExpectedRevision { get; set; }

		public int StateHashVersion { get; set; } = 1;
	}
	public sealed class CommitNormalActionRequest
	{
		public string SessionId { get; set; } = string.Empty;

		public int PlanetId { get; set; }

		public string PlanToken { get; set; } = string.Empty;

		public string IdempotencyKey { get; set; } = string.Empty;
	}
	public sealed class PreparedNormalAction
	{
		public bool Prepared { get; set; }

		public string ActionKind { get; set; } = string.Empty;

		public string PlanToken { get; set; } = string.Empty;

		public DateTimeOffset ExpiresAtUtc { get; set; }

		public string ExpectedStateHash { get; set; } = string.Empty;

		public int StateHashVersion { get; set; } = 1;

		public bool CommitAllowedNow { get; set; }

		public double EstimatedDistance { get; set; }

		public long EstimatedGameTicks { get; set; }

		public List<ActionItemBudget> ItemBudget { get; set; } = new List<ActionItemBudget>();

		public List<WriteBlocker> CommitBlockers { get; set; } = new List<WriteBlocker>();

		public string CompletionCondition { get; set; } = string.Empty;

		public Vector3Snapshot? PlannedPosition { get; set; }

		public float? PlannedYaw { get; set; }

		public string? BuildKind { get; set; }

		public int? TargetObjectId { get; set; }

		public int? SourceObjectId { get; set; }

		public int? DestinationObjectId { get; set; }

		public List<Vector3Snapshot> PlannedPath { get; set; } = new List<Vector3Snapshot>();

		public List<int> PlannedResourceNodeIds { get; set; } = new List<int>();

		public string? ReconcilesActionId { get; set; }

		public List<int> ProvedObjectIds { get; set; } = new List<int>();
	}
	public sealed class ActionItemBudget
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int Count { get; set; }

		public string Direction { get; set; } = string.Empty;
	}
	public sealed class NormalActionCommitResult
	{
		public string ActionId { get; set; } = string.Empty;

		public string ActionKind { get; set; } = string.Empty;

		public string IdempotencyKey { get; set; } = string.Empty;

		public string State { get; set; } = string.Empty;

		public bool Accepted { get; set; }

		public bool IdempotentReplay { get; set; }
	}
	public sealed class ActionItemDelta
	{
		public int ItemId { get; set; }

		public string Name { get; set; } = string.Empty;

		public int BeforeCount { get; set; }

		public int AfterCount { get; set; }

		public int Delta { get; set; }
	}
}

plugins/Spherewright.Plugin.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using Microsoft.Win32.SafeHandles;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Spherewright.Bridge.Core.Abstractions;
using Spherewright.Bridge.Core.Authentication;
using Spherewright.Bridge.Core.Framing;
using Spherewright.Bridge.Core.Journals;
using Spherewright.Bridge.Core.Logistics;
using Spherewright.Bridge.Core.Progression;
using Spherewright.Bridge.Core.Routing;
using Spherewright.Bridge.Core.Safety;
using Spherewright.Bridge.Core.Snapshots;
using Spherewright.Contracts.Actions;
using Spherewright.Contracts.Celestial;
using Spherewright.Contracts.Errors;
using Spherewright.Contracts.Factory;
using Spherewright.Contracts.Journals;
using Spherewright.Contracts.Logistics;
using Spherewright.Contracts.Players;
using Spherewright.Contracts.Power;
using Spherewright.Contracts.Progression;
using Spherewright.Contracts.Protocol;
using Spherewright.Contracts.Resources;
using Spherewright.Contracts.Sessions;
using Spherewright.Contracts.Testing;
using Spherewright.Plugin.Bootstrap;
using Spherewright.Plugin.Game;
using Spherewright.Plugin.Hosting;
using Spherewright.Plugin.RuntimeDescriptor;
using Spherewright.Plugin.Security;
using Spherewright.Plugin.Transport;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Spherewright.Plugin")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.3.0")]
[assembly: AssemblyInformationalVersion("0.3.3+f0cd11105957ae63cb4b45fd5756b0a42508857f")]
[assembly: AssemblyProduct("Spherewright.Plugin")]
[assembly: AssemblyTitle("Spherewright.Plugin")]
[assembly: AssemblyVersion("0.3.3.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Spherewright.Plugin
{
	[BepInPlugin("dev.spherewright.bridge", "Spherewright", "0.3.3")]
	[BepInProcess("DSPGAME.exe")]
	public sealed class SpherewrightPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "dev.spherewright.bridge";

		public const string PluginName = "Spherewright";

		public const string PluginVersion = "0.3.3";

		private SpherewrightBridgeHost? _host;

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Spherewright plugin loaded");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Spherewright plugin version: 0.3.3");
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Spherewright protocol version: {1}");
			try
			{
				SpherewrightConfiguration spherewrightConfiguration = SpherewrightConfiguration.Load(((BaseUnityPlugin)this).Config);
				_host = SpherewrightBridgeHost.Create(spherewrightConfiguration, ((BaseUnityPlugin)this).Logger, "0.3.3");
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Spherewright writes configured: " + (spherewrightConfiguration.AllowWrites ? "enabled" : "disabled")));
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Spherewright user-save import configured: " + (spherewrightConfiguration.AllowUserSaveImport ? "enabled" : "disabled")));
				if (!spherewrightConfiguration.Enabled)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"Spherewright bridge is disabled by configuration");
					_host.Dispose();
					_host = null;
				}
				else
				{
					_host.Start();
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Spherewright bridge started");
				}
			}
			catch (Exception ex)
			{
				_host?.Dispose();
				_host = null;
				((BaseUnityPlugin)this).Logger.LogError((object)("Spherewright bridge startup failed: " + FormatExceptionChain(ex)));
				((BaseUnityPlugin)this).Logger.LogError((object)ex.ToString());
			}
		}

		private void Update()
		{
			_host?.PumpMainThread();
		}

		private void OnDestroy()
		{
			_host?.Dispose();
			_host = null;
		}

		private static string FormatExceptionChain(Exception exception)
		{
			List<string> list = new List<string>();
			for (Exception ex = exception; ex != null; ex = ex.InnerException)
			{
				list.Add(ex.GetType().Name + ": " + ex.Message);
			}
			return string.Join(" -> ", list);
		}
	}
}
namespace Spherewright.Plugin.Transport
{
	internal sealed class NamedPipeBridgeServer : IDisposable
	{
		private readonly object _gate = new object();

		private readonly string _pipeName;

		private readonly string _bridgeInstanceId;

		private readonly string _pluginVersion;

		private readonly FrameCodec _frameCodec;

		private readonly TimeSpan _readRequestTimeout;

		private readonly HandshakeAuthenticator _authenticator;

		private readonly BridgeStatusSnapshotProvider _statusProvider;

		private readonly BoundedMainThreadDispatcher _dispatcher;

		private readonly GameStateReader _gameStateReader;

		private readonly GameplayJournalManager _gameplayJournalManager;

		private readonly TestWorldCoordinator _testWorldCoordinator;

		private readonly UserSaveImportCoordinator _userSaveImportCoordinator;

		private readonly OwnedWorldResumeCoordinator _ownedWorldResumeCoordinator;

		private readonly FlightCheckpointReloadCoordinator _flightCheckpointReloadCoordinator;

		private readonly NormalGameActionCoordinator _normalActionCoordinator;

		private readonly ManualLogSource _logger;

		private readonly CancellationTokenSource _shutdown = new CancellationTokenSource();

		private Task? _serverTask;

		private NamedPipeServerStream? _activePipe;

		private int _lastAuthWarningTick;

		public NamedPipeBridgeServer(BridgeIdentity identity, string pluginVersion, int maxFrameBytes, int readRequestTimeoutSeconds, BridgeStatusSnapshotProvider statusProvider, BoundedMainThreadDispatcher dispatcher, GameStateReader gameStateReader, GameplayJournalManager gameplayJournalManager, TestWorldCoordinator testWorldCoordinator, UserSaveImportCoordinator userSaveImportCoordinator, OwnedWorldResumeCoordinator ownedWorldResumeCoordinator, FlightCheckpointReloadCoordinator flightCheckpointReloadCoordinator, NormalGameActionCoordinator normalActionCoordinator, ManualLogSource logger)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			_pipeName = identity.PipeName;
			_bridgeInstanceId = identity.BridgeInstanceId;
			_pluginVersion = pluginVersion;
			_frameCodec = new FrameCodec(maxFrameBytes);
			_readRequestTimeout = TimeSpan.FromSeconds(readRequestTimeoutSeconds);
			_authenticator = new HandshakeAuthenticator(identity.BridgeInstanceId, identity.AuthToken);
			_statusProvider = statusProvider;
			_dispatcher = dispatcher;
			_gameStateReader = gameStateReader;
			_gameplayJournalManager = gameplayJournalManager;
			_testWorldCoordinator = testWorldCoordinator;
			_userSaveImportCoordinator = userSaveImportCoordinator;
			_ownedWorldResumeCoordinator = ownedWorldResumeCoordinator;
			_flightCheckpointReloadCoordinator = flightCheckpointReloadCoordinator;
			_normalActionCoordinator = normalActionCoordinator;
			_logger = logger;
		}

		public void Start()
		{
			lock (_gate)
			{
				if (_serverTask != null)
				{
					throw new InvalidOperationException("The Named Pipe bridge is already running.");
				}
				_serverTask = Task.Run(() => RunAsync(_shutdown.Token));
			}
		}

		public void Dispose()
		{
			Task serverTask;
			lock (_gate)
			{
				_shutdown.Cancel();
				_activePipe?.Dispose();
				serverTask = _serverTask;
				_serverTask = null;
			}
			if (serverTask != null)
			{
				try
				{
					serverTask.Wait(TimeSpan.FromSeconds(2.0));
				}
				catch (AggregateException ex) when (ex.InnerExceptions.All((Exception inner) => inner is OperationCanceledException || inner is ObjectDisposedException))
				{
				}
			}
			_shutdown.Dispose();
		}

		private async Task RunAsync(CancellationToken cancellationToken)
		{
			while (!cancellationToken.IsCancellationRequested)
			{
				using NamedPipeServerStream pipe = CreateServerPipe();
				using (cancellationToken.Register(pipe.Dispose))
				{
					lock (_gate)
					{
						_activePipe = pipe;
					}
					try
					{
						await pipe.WaitForConnectionAsync().ConfigureAwait(continueOnCapturedContext: false);
						await HandleConnectionAsync(pipe, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					}
					catch (Exception ex) when (cancellationToken.IsCancellationRequested && (ex is OperationCanceledException || ex is ObjectDisposedException || ex is IOException))
					{
						break;
					}
					catch (FrameProtocolException ex2)
					{
						FrameProtocolException ex3 = ex2;
						_logger.LogWarning((object)("Spherewright rejected an invalid bridge frame: " + ((Exception)(object)ex3).Message));
					}
					catch (JsonException ex4)
					{
						JsonException ex5 = ex4;
						_logger.LogWarning((object)("Spherewright rejected malformed bridge JSON: " + ((Exception)(object)ex5).Message));
					}
					catch (IOException ex6)
					{
						_logger.LogDebug((object)("Spherewright bridge connection ended: " + ex6.Message));
					}
					catch (Exception ex7)
					{
						_logger.LogError((object)("Spherewright bridge connection failed: " + ex7.GetType().Name + ": " + ex7.Message));
					}
					finally
					{
						lock (_gate)
						{
							if (_activePipe == pipe)
							{
								_activePipe = null;
							}
						}
					}
				}
			}
		}

		private async Task HandleConnectionAsync(NamedPipeServerStream pipe, CancellationToken cancellationToken)
		{
			byte[] array = await _frameCodec.ReadFrameAsync((Stream)pipe, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (array == null)
			{
				return;
			}
			string json = FrameCodec.DecodeUtf8(array);
			BridgeError obj = ProtocolValidator.ValidateHeader(PluginJson.Deserialize<BridgeEnvelopeHeader>(json), "handshake");
			BridgeRequestEnvelope<HandshakeRequest> val = PluginJson.Deserialize<BridgeRequestEnvelope<HandshakeRequest>>(json);
			if (obj == null)
			{
				obj = _authenticator.Authenticate(val?.Payload);
			}
			if (obj != null)
			{
				LogAuthenticationFailureWithRateLimit();
				return;
			}
			BridgeResponseEnvelope<HandshakeResponse> envelope = new BridgeResponseEnvelope<HandshakeResponse>
			{
				RequestId = val.RequestId,
				Success = true,
				Result = new HandshakeResponse
				{
					Accepted = true,
					BridgeInstanceId = _bridgeInstanceId,
					PluginVersion = _pluginVersion,
					ProtocolVersion = 1
				}
			};
			await WriteEnvelopeAsync<HandshakeResponse>(pipe, envelope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			while (!cancellationToken.IsCancellationRequested && pipe.IsConnected)
			{
				byte[] array2 = await _frameCodec.ReadFrameAsync((Stream)pipe, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				if (array2 == null)
				{
					break;
				}
				string text = FrameCodec.DecodeUtf8(array2);
				BridgeEnvelopeHeader header = PluginJson.Deserialize<BridgeEnvelopeHeader>(text);
				BridgeError val2 = ProtocolValidator.ValidateHeader(header, "request");
				if (val2 != null)
				{
					NamedPipeBridgeServer namedPipeBridgeServer = this;
					BridgeEnvelopeHeader obj2 = header;
					await namedPipeBridgeServer.WriteErrorAsync(pipe, (obj2 != null) ? obj2.RequestId : null, val2, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					continue;
				}
				switch (header.Method)
				{
				case "get_bridge_status":
					await WriteResultAsync<BridgeStatus>(pipe, header.RequestId, null, _statusProvider.Capture(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "get_session_state":
					await DispatchAndWriteAsync(pipe, header.RequestId, null, _gameStateReader.GetSessionStateOnMainThread, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "get_player_state":
				{
					BridgeRequestEnvelope<LocalPlanetRequest> request27 = PluginJson.Deserialize<BridgeRequestEnvelope<LocalPlanetRequest>>(text);
					if (request27?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.GetPlayerStateOnMainThread(header.SessionId, request27.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "get_progression_state":
				{
					BridgeRequestEnvelope<LocalPlanetRequest> request17 = PluginJson.Deserialize<BridgeRequestEnvelope<LocalPlanetRequest>>(text);
					if (request17?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.GetProgressionStateOnMainThread(header.SessionId, request17.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "get_gameplay_journal":
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameplayJournalManager.CaptureOnMainThread(header.SessionId), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "get_recipe_catalog":
				{
					BridgeRequestEnvelope<LocalPlanetRequest> request3 = PluginJson.Deserialize<BridgeRequestEnvelope<LocalPlanetRequest>>(text);
					if (request3?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.GetRecipeCatalogOnMainThread(header.SessionId, request3.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "list_resource_nodes":
				{
					BridgeRequestEnvelope<ListResourceNodesRequest> request12 = PluginJson.Deserialize<BridgeRequestEnvelope<ListResourceNodesRequest>>(text);
					if (request12?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.ListResourceNodesOnMainThread(header.SessionId, request12.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "inspect_resource_node":
				{
					BridgeRequestEnvelope<InspectResourceNodeRequest> request21 = PluginJson.Deserialize<BridgeRequestEnvelope<InspectResourceNodeRequest>>(text);
					if (request21?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.InspectResourceNodeOnMainThread(header.SessionId, request21.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "list_factory_entities":
				{
					BridgeRequestEnvelope<ListFactoryEntitiesRequest> request4 = PluginJson.Deserialize<BridgeRequestEnvelope<ListFactoryEntitiesRequest>>(text);
					if (request4?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.ListFactoryEntitiesOnMainThread(header.SessionId, request4.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "inspect_factory_entity":
				{
					BridgeRequestEnvelope<InspectFactoryEntityRequest> request14 = PluginJson.Deserialize<BridgeRequestEnvelope<InspectFactoryEntityRequest>>(text);
					if (request14?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.InspectFactoryEntityOnMainThread(header.SessionId, request14.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "get_power_summary":
				{
					BridgeRequestEnvelope<LocalPlanetRequest> request24 = PluginJson.Deserialize<BridgeRequestEnvelope<LocalPlanetRequest>>(text);
					if (request24?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.GetPowerSummaryOnMainThread(header.SessionId, request24.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "get_action_result":
				{
					BridgeRequestEnvelope<GetActionResultRequest> request2 = PluginJson.Deserialize<BridgeRequestEnvelope<GetActionResultRequest>>(text);
					if (request2?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => GetActionResultOnMainThread(request2.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "prepare_move":
				{
					BridgeRequestEnvelope<PrepareMoveRequest> request25 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareMoveRequest>>(text);
					if (request25?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareMoveOnMainThread(header.SessionId, request25.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_move":
					await DispatchNormalCommitAsync(pipe, header, text, "move", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_interplanetary_flight":
				{
					BridgeRequestEnvelope<PrepareInterplanetaryFlightRequest> request16 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareInterplanetaryFlightRequest>>(text);
					if (request16?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareInterplanetaryFlightOnMainThread(header.SessionId, request16.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_interplanetary_flight":
					await DispatchNormalCommitAsync(pipe, header, text, "interplanetary-flight", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_harvest":
				{
					BridgeRequestEnvelope<PrepareHarvestRequest> request32 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareHarvestRequest>>(text);
					if (request32?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareHarvestOnMainThread(header.SessionId, request32.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_harvest":
					await DispatchNormalCommitAsync(pipe, header, text, "harvest", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_handcraft":
				{
					BridgeRequestEnvelope<PrepareHandcraftRequest> request20 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareHandcraftRequest>>(text);
					if (request20?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareHandcraftOnMainThread(header.SessionId, request20.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_handcraft":
					await DispatchNormalCommitAsync(pipe, header, text, "handcraft", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_select_research":
				{
					BridgeRequestEnvelope<PrepareSelectResearchRequest> request11 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareSelectResearchRequest>>(text);
					if (request11?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareSelectResearchOnMainThread(header.SessionId, request11.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_select_research":
					await DispatchNormalCommitAsync(pipe, header, text, "select-research", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_build":
				{
					BridgeRequestEnvelope<PrepareBuildRequest> request33 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareBuildRequest>>(text);
					if (request33?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareBuildOnMainThread(header.SessionId, request33.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_build":
					await DispatchNormalCommitAsync(pipe, header, text, "build", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_dismantle":
				{
					BridgeRequestEnvelope<PrepareDismantleRequest> request29 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareDismantleRequest>>(text);
					if (request29?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareDismantleOnMainThread(header.SessionId, request29.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_dismantle":
					await DispatchNormalCommitAsync(pipe, header, text, "dismantle", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_configure_building":
				{
					BridgeRequestEnvelope<PrepareConfigureBuildingRequest> request19 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareConfigureBuildingRequest>>(text);
					if (request19?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareConfigureBuildingOnMainThread(header.SessionId, request19.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_configure_building":
					await DispatchNormalCommitAsync(pipe, header, text, "configure-building", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_transfer":
				{
					BridgeRequestEnvelope<PrepareTransferRequest> request10 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareTransferRequest>>(text);
					if (request10?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareTransferOnMainThread(header.SessionId, request10.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_transfer":
					await DispatchNormalCommitAsync(pipe, header, text, "transfer", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_logistics_station_fleet_transfer":
				{
					BridgeRequestEnvelope<PrepareLogisticsStationFleetTransferRequest> request5 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareLogisticsStationFleetTransferRequest>>(text);
					if (request5?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareLogisticsStationFleetTransferOnMainThread(header.SessionId, request5.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_logistics_station_fleet_transfer":
					await DispatchNormalCommitAsync(pipe, header, text, "logistics-station-fleet-transfer", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_refuel":
				{
					BridgeRequestEnvelope<PrepareRefuelRequest> request31 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareRefuelRequest>>(text);
					if (request31?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareRefuelOnMainThread(header.SessionId, request31.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_refuel":
					await DispatchNormalCommitAsync(pipe, header, text, "refuel", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_save":
				{
					BridgeRequestEnvelope<PrepareSaveRequest> request28 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareSaveRequest>>(text);
					if (request28?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareSaveOnMainThread(header.SessionId, request28.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_save":
					await DispatchNormalCommitAsync(pipe, header, text, "save", cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_quarantine_reconciliation":
				{
					BridgeRequestEnvelope<PrepareQuarantineReconciliationRequest> request22 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareQuarantineReconciliationRequest>>(text);
					if (request22?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.PrepareQuarantineReconciliationOnMainThread(header.SessionId, request22.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "get_local_star_system":
				{
					BridgeRequestEnvelope<LocalPlanetRequest> request15 = PluginJson.Deserialize<BridgeRequestEnvelope<LocalPlanetRequest>>(text);
					if (request15?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.GetLocalStarSystemOnMainThread(header.SessionId, request15.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_quarantine_reconciliation":
				{
					BridgeRequestEnvelope<CommitNormalActionRequest> request9 = PluginJson.Deserialize<BridgeRequestEnvelope<CommitNormalActionRequest>>(text);
					if (request9?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.CommitQuarantineReconciliationOnMainThread(header.SessionId, request9.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "list_assemblers":
				{
					BridgeRequestEnvelope<ListAssemblersRequest> request7 = PluginJson.Deserialize<BridgeRequestEnvelope<ListAssemblersRequest>>(text);
					if (request7?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.ListAssemblersOnMainThread(header.SessionId, request7.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "inspect_assembler":
				{
					BridgeRequestEnvelope<InspectAssemblerRequest> request34 = PluginJson.Deserialize<BridgeRequestEnvelope<InspectAssemblerRequest>>(text);
					if (request34?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.InspectAssemblerOnMainThread(header.SessionId, request34.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "get_build_catalog":
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _gameStateReader.GetBuildCatalogOnMainThread(header.SessionId), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				case "prepare_new_game":
				{
					BridgeRequestEnvelope<PrepareTestWorldRequest> request30 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareTestWorldRequest>>(text);
					if (request30?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, null, () => _testWorldCoordinator.PrepareOnMainThread(request30.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_new_game":
				{
					BridgeRequestEnvelope<CommitTestWorldRequest> request26 = PluginJson.Deserialize<BridgeRequestEnvelope<CommitTestWorldRequest>>(text);
					if (request26?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, null, () => _testWorldCoordinator.CommitOnMainThread(request26.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "prepare_import_current_game":
				{
					BridgeRequestEnvelope<PrepareUserSaveImportRequest> request23 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareUserSaveImportRequest>>(text);
					if (request23?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _userSaveImportCoordinator.PrepareOnMainThread(header.SessionId, request23.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_import_current_game":
				{
					BridgeRequestEnvelope<CommitUserSaveImportRequest> request18 = PluginJson.Deserialize<BridgeRequestEnvelope<CommitUserSaveImportRequest>>(text);
					if (request18?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _userSaveImportCoordinator.CommitOnMainThread(header.SessionId, request18.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "prepare_resume_owned_game":
				{
					BridgeRequestEnvelope<PrepareOwnedWorldResumeRequest> request13 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareOwnedWorldResumeRequest>>(text);
					if (request13?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, null, () => _ownedWorldResumeCoordinator.PrepareOnMainThread(request13.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_resume_owned_game":
				{
					BridgeRequestEnvelope<CommitOwnedWorldResumeRequest> request8 = PluginJson.Deserialize<BridgeRequestEnvelope<CommitOwnedWorldResumeRequest>>(text);
					if (request8?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, null, () => _ownedWorldResumeCoordinator.CommitOnMainThread(request8.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "prepare_reload_flight_checkpoint":
				{
					BridgeRequestEnvelope<PrepareFlightCheckpointReloadRequest> request6 = PluginJson.Deserialize<BridgeRequestEnvelope<PrepareFlightCheckpointReloadRequest>>(text);
					if (request6?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, null, () => _flightCheckpointReloadCoordinator.PrepareOnMainThread(request6.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				case "commit_reload_flight_checkpoint":
				{
					BridgeRequestEnvelope<CommitFlightCheckpointReloadRequest> request = PluginJson.Deserialize<BridgeRequestEnvelope<CommitFlightCheckpointReloadRequest>>(text);
					if (request?.Payload == null)
					{
						await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						break;
					}
					await DispatchAndWriteAsync(pipe, header.RequestId, null, () => _flightCheckpointReloadCoordinator.CommitOnMainThread(request.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
				default:
					await WriteErrorAsync(pipe, header.RequestId, BridgeError.Create("INVALID_REQUEST", "The requested bridge method is not available.", false, "Call a method advertised by the current Spherewright MCP server."), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					break;
				}
			}
		}

		private GameCallResult<ActionResultSnapshot> GetActionResultOnMainThread(GetActionResultRequest request)
		{
			if (_userSaveImportCoordinator.TryGetActionResultOnMainThread(request.ActionId, out ActionResultSnapshot result) && result != null)
			{
				return GameCallResult<ActionResultSnapshot>.Succeeded(result);
			}
			if (_normalActionCoordinator.TryGetActionResultOnMainThread(request.ActionId, out ActionResultSnapshot result2) && result2 != null)
			{
				return GameCallResult<ActionResultSnapshot>.Succeeded(result2);
			}
			if (_ownedWorldResumeCoordinator.TryGetActionResultOnMainThread(request.ActionId, out ActionResultSnapshot result3) && result3 != null)
			{
				return GameCallResult<ActionResultSnapshot>.Succeeded(result3);
			}
			if (_flightCheckpointReloadCoordinator.TryGetActionResultOnMainThread(request.ActionId, out ActionResultSnapshot result4) && result4 != null)
			{
				return GameCallResult<ActionResultSnapshot>.Succeeded(result4);
			}
			return _testWorldCoordinator.GetActionResultOnMainThread(request);
		}

		private async Task DispatchNormalCommitAsync(Stream pipe, BridgeEnvelopeHeader header, string requestJson, string actionKind, CancellationToken cancellationToken)
		{
			BridgeRequestEnvelope<CommitNormalActionRequest> request = PluginJson.Deserialize<BridgeRequestEnvelope<CommitNormalActionRequest>>(requestJson);
			if (request?.Payload == null)
			{
				await WriteInvalidPayloadAsync(pipe, header.RequestId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				return;
			}
			await DispatchAndWriteAsync(pipe, header.RequestId, header.SessionId, () => _normalActionCoordinator.CommitOnMainThread(actionKind, header.SessionId, request.Payload), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		private async Task DispatchAndWriteAsync<T>(Stream pipe, string requestId, string? sessionId, Func<GameCallResult<T>> operation, CancellationToken cancellationToken)
		{
			Task<GameCallResult<T>> completion = default(Task<GameCallResult<T>>);
			if (!_dispatcher.TryEnqueue<GameCallResult<T>>(operation, ref completion))
			{
				await WriteErrorAsync(pipe, requestId, BridgeError.Create("QUEUE_FULL", "The Unity main-thread request queue is full.", true, "Retry after the game has processed pending requests."), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				return;
			}
			Task task = Task.Delay(_readRequestTimeout, cancellationToken);
			if (await Task.WhenAny(new Task[2] { completion, task }).ConfigureAwait(continueOnCapturedContext: false) != completion)
			{
				cancellationToken.ThrowIfCancellationRequested();
				await WriteErrorAsync(pipe, requestId, BridgeError.Create("REQUEST_TIMEOUT", "The Unity main-thread read request timed out.", true, "Wait for DSP to become responsive and retry."), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				return;
			}
			GameCallResult<T> result;
			try
			{
				result = await completion.ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (Exception arg)
			{
				_logger.LogError((object)$"Spherewright main-thread operation failed: {arg}");
				await WriteErrorAsync(pipe, requestId, BridgeError.Create("INTERNAL_ERROR", "A main-thread game-state read failed.", true, "Retry once. If it repeats, inspect the local Spherewright log."), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				return;
			}
			if (!result.Success || result.Value == null)
			{
				await WriteErrorAsync(pipe, requestId, result.Error ?? BridgeError.Create("INTERNAL_ERROR", "The game-state read returned an incomplete result.", true, "Retry the request."), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			else
			{
				await WriteResultAsync(pipe, requestId, sessionId, result.Value, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
		}

		private Task WriteInvalidPayloadAsync(Stream pipe, string requestId, CancellationToken cancellationToken)
		{
			return WriteErrorAsync(pipe, requestId, BridgeError.Create("INVALID_REQUEST", "The bridge request payload is missing or invalid.", false, "Correct the request payload and retry."), cancellationToken);
		}

		private Task WriteResultAsync<T>(Stream pipe, string requestId, string? sessionId, T result, CancellationToken cancellationToken)
		{
			return WriteEnvelopeAsync<T>(pipe, new BridgeResponseEnvelope<T>
			{
				RequestId = requestId,
				SessionId = sessionId,
				Success = true,
				Result = result
			}, cancellationToken);
		}

		private NamedPipeServerStream CreateServerPipe()
		{
			return WindowsCurrentUserSecurity.CreateSecurePipe(_pipeName, 4096, 4096);
		}

		private async Task WriteErrorAsync(Stream pipe, string? requestId, BridgeError error, CancellationToken cancellationToken)
		{
			BridgeResponseEnvelope<object> obj = new BridgeResponseEnvelope<object>();
			string requestId2;
			if (!string.IsNullOrWhiteSpace(requestId))
			{
				requestId2 = requestId;
			}
			else
			{
				Guid empty = Guid.Empty;
				requestId2 = empty.ToString("D");
			}
			obj.RequestId = requestId2;
			obj.Success = false;
			obj.Error = error;
			BridgeResponseEnvelope<object> envelope = obj;
			await WriteEnvelopeAsync<object>(pipe, envelope, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		private Task WriteEnvelopeAsync<T>(Stream pipe, BridgeResponseEnvelope<T> envelope, CancellationToken cancellationToken)
		{
			byte[] array = FrameCodec.EncodeUtf8(PluginJson.Serialize<BridgeResponseEnvelope<T>>(envelope));
			return _frameCodec.WriteFrameAsync(pipe, array, cancellationToken);
		}

		private void LogAuthenticationFailureWithRateLimit()
		{
			int tickCount = Environment.TickCount;
			int num = Interlocked.Exchange(ref _lastAuthWarningTick, tickCount);
			if (num == 0 || tickCount - num >= 5000)
			{
				_logger.LogWarning((object)"Spherewright rejected a bridge authentication attempt.");
			}
		}
	}
	internal static class PluginJson
	{
		private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
		{
			ContractResolver = (IContractResolver)new CamelCasePropertyNamesContractResolver(),
			DateFormatHandling = (DateFormatHandling)0,
			DateParseHandling = (DateParseHandling)2,
			MissingMemberHandling = (MissingMemberHandling)0,
			NullValueHandling = (NullValueHandling)0,
			TypeNameHandling = (TypeNameHandling)0,
			MaxDepth = 64
		};

		public static string Serialize<T>(T value)
		{
			return JsonConvert.SerializeObject((object)value, (Formatting)0, Settings);
		}

		public static T? Deserialize<T>(string json)
		{
			return JsonConvert.DeserializeObject<T>(json, Settings);
		}
	}
}
namespace Spherewright.Plugin.Security
{
	internal static class WindowsCurrentUserSecurity
	{
		private struct SecurityAttributes
		{
			public int Length;

			public IntPtr SecurityDescriptor;

			public int InheritHandle;
		}

		private sealed class NativeSecurityDescriptor : IDisposable
		{
			public IntPtr Pointer { get; private set; }

			private NativeSecurityDescriptor(IntPtr pointer)
			{
				Pointer = pointer;
			}

			public static NativeSecurityDescriptor Create(string sddl)
			{
				if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl, 1u, out var securityDescriptor, out var _))
				{
					throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not create a current-user security descriptor.");
				}
				return new NativeSecurityDescriptor(securityDescriptor);
			}

			public SecurityAttributes CreateAttributes()
			{
				return new SecurityAttributes
				{
					Length = Marshal.SizeOf(typeof(SecurityAttributes)),
					SecurityDescriptor = Pointer,
					InheritHandle = 0
				};
			}

			public void Dispose()
			{
				IntPtr pointer = Pointer;
				Pointer = IntPtr.Zero;
				if (pointer != IntPtr.Zero)
				{
					LocalFree(pointer);
				}
			}
		}

		private const uint TokenQuery = 8u;

		private const int TokenUser = 1;

		private const int ErrorInsufficientBuffer = 122;

		private const int ErrorAlreadyExists = 183;

		private const uint SecurityDescriptorRevision = 1u;

		private const uint DaclSecurityInformation = 4u;

		private const uint ProtectedDaclSecurityInformation = 2147483648u;

		private const uint GenericWrite = 1073741824u;

		private const uint CreateNew = 1u;

		private const uint FileAttributeNormal = 128u;

		private const uint PipeAccessDuplex = 3u;

		private const uint FileFlagOverlapped = 1073741824u;

		private const uint PipeRejectRemoteClients = 8u;

		private static readonly Lazy<string> CurrentUserSid = new Lazy<string>(ReadCurrentUserSid);

		public static void EnsureSecureDirectory(string path)
		{
			if (string.IsNullOrWhiteSpace(path))
			{
				throw new ArgumentException("A secure directory path is required.", "path");
			}
			using NativeSecurityDescriptor nativeSecurityDescriptor = NativeSecurityDescriptor.Create(BuildDirectorySddl(CurrentUserSid.Value));
			Stack<string> stack = new Stack<string>();
			string text = path;
			while (!Directory.Exists(text))
			{
				stack.Push(text);
				text = (Directory.GetParent(text) ?? throw new InvalidOperationException("No existing parent was found for secure directory '" + path + "'.")).FullName;
			}
			while (stack.Count > 0)
			{
				string text2 = stack.Pop();
				SecurityAttributes securityAttributes = nativeSecurityDescriptor.CreateAttributes();
				if (!CreateDirectory(text2, ref securityAttributes))
				{
					int lastWin32Error = Marshal.GetLastWin32Error();
					if (lastWin32Error != 183)
					{
						throw new Win32Exception(lastWin32Error, "Could not create secure directory '" + text2 + "'.");
					}
				}
				ApplyProtectedDacl(text2, nativeSecurityDescriptor.Pointer);
			}
			ApplyProtectedDacl(path, nativeSecurityDescriptor.Pointer);
		}

		public static void WriteSecureNewFile(string path, byte[] content)
		{
			if (string.IsNullOrWhiteSpace(path))
			{
				throw new ArgumentException("A secure file path is required.", "path");
			}
			if (content == null)
			{
				throw new ArgumentNullException("content");
			}
			using NativeSecurityDescriptor nativeSecurityDescriptor = NativeSecurityDescriptor.Create(BuildFileSddl(CurrentUserSid.Value));
			SecurityAttributes securityAttributes = nativeSecurityDescriptor.CreateAttributes();
			using SafeFileHandle safeFileHandle = CreateFile(path, 1073741824u, 0u, ref securityAttributes, 1u, 128u, IntPtr.Zero);
			if (safeFileHandle.IsInvalid)
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not create secure file '" + path + "'.");
			}
			uint numberOfBytesWritten;
			for (int i = 0; i < content.Length; i += checked((int)numberOfBytesWritten))
			{
				int num = content.Length - i;
				byte[] array = new byte[num];
				Buffer.BlockCopy(content, i, array, 0, num);
				if (!WriteFile(safeFileHandle, array, (uint)array.Length, out numberOfBytesWritten, IntPtr.Zero))
				{
					throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not write secure file '" + path + "'.");
				}
				if (numberOfBytesWritten == 0)
				{
					throw new IOException("Writing secure file '" + path + "' made no progress.");
				}
			}
			if (!FlushFileBuffers(safeFileHandle))
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not flush secure file '" + path + "'.");
			}
		}

		public static NamedPipeServerStream CreateSecurePipe(string pipeName, int inputBufferSize, int outputBufferSize)
		{
			if (string.IsNullOrWhiteSpace(pipeName))
			{
				throw new ArgumentException("A Pipe name is required.", "pipeName");
			}
			using NativeSecurityDescriptor nativeSecurityDescriptor = NativeSecurityDescriptor.Create(BuildPipeSddl(CurrentUserSid.Value));
			SecurityAttributes securityAttributes = nativeSecurityDescriptor.CreateAttributes();
			SafePipeHandle safePipeHandle = checked(CreateNamedPipe("\\\\.\\pipe\\" + pipeName, 1073741827u, 8u, 1u, (uint)outputBufferSize, (uint)inputBufferSize, 0u, ref securityAttributes));
			if (safePipeHandle.IsInvalid)
			{
				int lastWin32Error = Marshal.GetLastWin32Error();
				safePipeHandle.Dispose();
				throw new Win32Exception(lastWin32Error, "Could not create secure Named Pipe '" + pipeName + "'.");
			}
			try
			{
				return new NamedPipeServerStream(PipeDirection.InOut, isAsync: true, isConnected: false, safePipeHandle);
			}
			catch
			{
				safePipeHandle.Dispose();
				throw;
			}
		}

		private static string ReadCurrentUserSid()
		{
			if (!OpenProcessToken(GetCurrentProcess(), 8u, out var tokenHandle))
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not open the current process token.");
			}
			try
			{
				GetTokenInformation(tokenHandle, 1, IntPtr.Zero, 0, out var returnLength);
				int lastWin32Error = Marshal.GetLastWin32Error();
				if (returnLength <= 0 || lastWin32Error != 122)
				{
					throw new Win32Exception(lastWin32Error, "Could not determine the current process-token user size.");
				}
				IntPtr intPtr = Marshal.AllocHGlobal(returnLength);
				try
				{
					if (!GetTokenInformation(tokenHandle, 1, intPtr, returnLength, out var _))
					{
						throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not read the current process-token user.");
					}
					if (!ConvertSidToStringSid(Marshal.ReadIntPtr(intPtr), out var stringSid))
					{
						throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not convert the current user SID to text.");
					}
					try
					{
						return Marshal.PtrToStringUni(stringSid) ?? throw new InvalidOperationException("Windows returned an empty current-user SID.");
					}
					finally
					{
						LocalFree(stringSid);
					}
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr);
				}
			}
			finally
			{
				CloseHandle(tokenHandle);
			}
		}

		private static void ApplyProtectedDacl(string path, IntPtr securityDescriptor)
		{
			if (!SetFileSecurity(path, 2147483652u, securityDescriptor))
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not protect the ACL for '" + path + "'.");
			}
		}

		private static string BuildDirectorySddl(string sid)
		{
			return "O:" + sid + "D:P(A;OICI;FA;;;" + sid + ")";
		}

		private static string BuildFileSddl(string sid)
		{
			return "O:" + sid + "D:P(A;;FA;;;" + sid + ")";
		}

		private static string BuildPipeSddl(string sid)
		{
			return "O:" + sid + "D:P(A;;GA;;;" + sid + ")";
		}

		[DllImport("kernel32.dll")]
		private static extern IntPtr GetCurrentProcess();

		[DllImport("advapi32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle);

		[DllImport("advapi32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool GetTokenInformation(IntPtr tokenHandle, int tokenInformationClass, IntPtr tokenInformation, int tokenInformationLength, out int returnLength);

		[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool ConvertSidToStringSid(IntPtr sid, out IntPtr stringSid);

		[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string stringSecurityDescriptor, uint stringSdRevision, out IntPtr securityDescriptor, out uint securityDescriptorSize);

		[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool SetFileSecurity(string fileName, uint securityInformation, IntPtr securityDescriptor);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool CreateDirectory(string pathName, ref SecurityAttributes securityAttributes);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		private static extern SafeFileHandle CreateFile(string fileName, uint desiredAccess, uint shareMode, ref SecurityAttributes securityAttributes, uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool WriteFile(SafeFileHandle file, byte[] buffer, uint numberOfBytesToWrite, out uint numberOfBytesWritten, IntPtr overlapped);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool FlushFileBuffers(SafeFileHandle file);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		private static extern SafePipeHandle CreateNamedPipe(string name, uint openMode, uint pipeMode, uint maxInstances, uint outputBufferSize, uint inputBufferSize, uint defaultTimeout, ref SecurityAttributes securityAttributes);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool CloseHandle(IntPtr handle);

		[DllImport("kernel32.dll")]
		private static extern IntPtr LocalFree(IntPtr memory);
	}
}
namespace Spherewright.Plugin.RuntimeDescriptor
{
	internal sealed class FlightCheckpointStore
	{
		private const int TicketVersion = 1;

		private static readonly TimeSpan TicketLifetime = TimeSpan.FromHours(24.0);

		private readonly string _ticketPath;

		private readonly string _bridgeInstanceId;

		private readonly string _gameVersion;

		private readonly ManualLogSource _logger;

		private FlightCheckpointTicket? _currentTicket;

		public FlightCheckpointTicket? CurrentTicket
		{
			get
			{
				if (!IsReloadEligible(_currentTicket))
				{
					return null;
				}
				return _currentTicket;
			}
		}

		public bool HasCurrentTicket => CurrentTicket != null;

		public FlightCheckpointStore(string bridgeInstanceId, string gameVersion, ManualLogSource logger)
		{
			string text = Path.Combine(Path.GetDirectoryName(typeof(FlightCheckpointStore).Assembly.Location) ?? throw new InvalidOperationException("The Spherewright Plugin directory is unavailable."), "runtime-handoff");
			WindowsCurrentUserSecurity.EnsureSecureDirectory(text);
			_ticketPath = Path.Combine(text, "flight-checkpoint.json");
			_bridgeInstanceId = bridgeInstanceId;
			_gameVersion = gameVersion;
			_logger = logger;
			_currentTicket = ReadFromDisk();
			RetireIfCoveredByNewerPrimarySave();
			_logger.LogInfo((object)"Spherewright initialized the protected reusable flight-checkpoint store");
		}

		public FlightCheckpointTicket CreateDraft(string ownedSaveName, string sourceSessionId, long sourceRevision, int originPlanetId, int destinationPlanetId, string playerStateHash, string starSystemStateHash)
		{
			if (string.IsNullOrWhiteSpace(ownedSaveName) || string.IsNullOrWhiteSpace(sourceSessionId) || sourceRevision < 1 || originPlanetId <= 0 || destinationPlanetId <= 0 || originPlanetId == destinationPlanetId || string.IsNullOrWhiteSpace(playerStateHash) || string.IsNullOrWhiteSpace(starSystemStateHash))
			{
				throw new InvalidOperationException("A complete owned flight identity is required to create a checkpoint.");
			}
			string text = Guid.NewGuid().ToString("N");
			DateTimeOffset utcNow = DateTimeOffset.UtcNow;
			return new FlightCheckpointTicket
			{
				Version = 1,
				CheckpointId = text,
				ReloadToken = CreateToken(),
				CheckpointSaveName = "Spherewright_PreFlight_" + text,
				OwnedSaveName = ownedSaveName,
				SourceSessionId = sourceSessionId,
				SourceRevision = sourceRevision,
				SourceProcessId = Process.GetCurrentProcess().Id,
				SourceBridgeInstanceId = _bridgeInstanceId,
				GameVersion = _gameVersion,
				OriginPlanetId = originPlanetId,
				DestinationPlanetId = destinationPlanetId,
				PlayerStateHash = playerStateHash,
				StarSystemStateHash = starSystemStateHash,
				IssuedAtUtc = utcNow,
				ExpiresAtUtc = utcNow.Add(TicketLifetime),
				LifecycleState = "active"
			};
		}

		public void PersistCompletedCheckpoint(FlightCheckpointTicket ticket, long savedGameTick)
		{
			if (ticket == null || savedGameTick < 0)
			{
				throw new InvalidOperationException("A completed flight checkpoint and game tick are required.");
			}
			ticket.SavedGameTick = savedGameTick;
			if (!IsStructurallyValid(ticket))
			{
				throw new InvalidOperationException("The completed flight-checkpoint identity is invalid.");
			}
			Persist(ticket);
			_currentTicket = ticket;
			_logger.LogInfo((object)"Spherewright persisted an exact reusable pre-flight checkpoint ticket");
		}

		public bool TryMarkAttemptStarted(string checkpointId, string actionId, long gameTick, out string rejection)
		{
			rejection = string.Empty;
			FlightCheckpointTicket currentTicket = _currentTicket;
			if (!IsReloadEligible(currentTicket) || currentTicket == null || !string.Equals(currentTicket.CheckpointId, checkpointId, StringComparison.Ordinal) || string.IsNullOrWhiteSpace(actionId) || gameTick < currentTicket.SavedGameTick)
			{
				rejection = "The flight attempt does not match the current reloadable checkpoint.";
				return false;
			}
			currentTicket.LifecycleState = "active";
			currentTicket.LastAttemptActionId = actionId;
			currentTicket.LastAttemptStartedAtGameTick = gameTick;
			currentTicket.RecoveryRequiredAtGameTick = null;
			currentTicket.SuccessfulFlightAtGameTick = null;
			return TryPersistLifecycle(currentTicket, "start the bound flight attempt", out rejection);
		}

		public bool TryMarkRecoveryRequired(string checkpointId, string actionId, long gameTick, out string rejection)
		{
			rejection = string.Empty;
			FlightCheckpointTicket currentTicket = _currentTicket;
			if (!IsStructurallyValid(currentTicket) || currentTicket == null || !string.Equals(currentTicket.CheckpointId, checkpointId, StringComparison.Ordinal) || IsSuccessfulOrRetired(currentTicket) || string.IsNullOrWhiteSpace(actionId) || gameTick < currentTicket.SavedGameTick)
			{
				rejection = "The failed flight does not match the current checkpoint lifecycle.";
				return false;
			}
			currentTicket.LifecycleState = "recovery_required";
			currentTicket.LastAttemptActionId = actionId;
			currentTicket.RecoveryRequiredAtGameTick = gameTick;
			return TryPersistLifecycle(currentTicket, "mark the bound flight as recovery-required", out rejection);
		}

		public bool TryMarkFlightSucceeded(string checkpointId, string actionId, long gameTick, out string rejection)
		{
			rejection = string.Empty;
			FlightCheckpointTicket currentTicket = _currentTicket;
			if (!IsStructurallyValid(currentTicket) || currentTicket == null || !string.Equals(currentTicket.CheckpointId, checkpointId, StringComparison.Ordinal) || IsSuccessfulOrRetired(currentTicket) || string.IsNullOrWhiteSpace(actionId) || gameTick < currentTicket.SavedGameTick)
			{
				rejection = "The successful flight does not match the current checkpoint lifecycle.";
				return false;
			}
			currentTicket.LifecycleState = "flight_succeeded";
			currentTicket.LastAttemptActionId = actionId;
			currentTicket.SuccessfulFlightAtGameTick = gameTick;
			currentTicket.RecoveryRequiredAtGameTick = null;
			return TryPersistLifecycle(currentTicket, "seal the successful flight before its primary save", out rejection);
		}

		public bool TryRetireAfterPrimarySave(string ownedSaveName, long savedGameTick, out bool retired, out string rejection)
		{
			retired = false;
			rejection = string.Empty;
			FlightCheckpointTicket currentTicket = _currentTicket;
			if (!IsStructurallyValid(currentTicket) || currentTicket == null)
			{
				return true;
			}
			if (!string.Equals(EffectiveLifecycle(currentTicket), "flight_succeeded", StringComparison.Ordinal))
			{
				return true;
			}
			if (!string.Equals(currentTicket.OwnedSaveName, ownedSaveName, StringComparison.Ordinal) || !currentTicket.SuccessfulFlightAtGameTick.HasValue || savedGameTick < currentTicket.SuccessfulFlightAtGameTick.Value)
			{
				rejection = "The primary save does not cover the successful flight checkpoint timeline.";
				return false;
			}
			currentTicket.LifecycleState = "retired";
			currentTicket.RetiredAtGameTick = savedGameTick;
			currentTicket.RetiredAtUtc = DateTimeOffset.UtcNow;
			if (!TryPersistLifecycle(currentTicket, "retire the checkpoint after the covering primary save", out rejection))
			{
				return false;
			}
			retired = true;
			_logger.LogInfo((object)"Spherewright retired the successful flight checkpoint after a covering primary save");
			return true;
		}

		public bool TryGetActiveTicket(string reloadToken, out FlightCheckpointTicket? ticket, out string rejection)
		{
			ticket = null;
			rejection = string.Empty;
			if (string.IsNullOrWhiteSpace(reloadToken))
			{
				rejection = "A flight-checkpoint reload token is required.";
				return false;
			}
			FlightCheckpointTicket flightCheckpointTicket = _currentTicket ?? ReadFromDisk();
			if (!IsReloadEligible(flightCheckpointTicket) || flightCheckpointTicket == null || !FixedTimeEquals(flightCheckpointTicket.ReloadToken, reloadToken))
			{
				rejection = "The flight-checkpoint ticket is missing, expired, retired, already succeeded, or belongs to another game version.";
				return false;
			}
			_currentTicket = flightCheckpointTicket;
			ticket = flightCheckpointTicket;
			return true;
		}

		public bool TryValidateCheckpointFile(FlightCheckpointTicket ticket, out string rejection)
		{
			rejection = string.Empty;
			if (!IsStructurallyValid(ticket))
			{
				rejection = "The reusable flight-checkpoint ticket is invalid.";
				return false;
			}
			GameSaveHeader val = default(GameSaveHeader);
			GameSave.ReadHeader(ticket.CheckpointSaveName, false, ref val);
			if (val == null || val.gameTick != ticket.SavedGameTick)
			{
				rejection = "The exact pre-flight save is missing or its saved game tick no longer matches the protected ticket.";
				return false;
			}
			return true;
		}

		private bool IsStructurallyValid(FlightCheckpointTicket? ticket)
		{
			if (ticket != null && ticket.Version == 1 && string.Equals(ticket.GameVersion, _gameVersion, StringComparison.Ordinal) && !string.IsNullOrWhiteSpace(ticket.CheckpointId) && !string.IsNullOrWhiteSpace(ticket.ReloadToken) && !string.IsNullOrWhiteSpace(ticket.CheckpointSaveName) && ticket.CheckpointSaveName.StartsWith("Spherewright_PreFlight_", StringComparison.Ordinal) && ticket.CheckpointSaveName.IndexOfAny(new char[3] { '/', '\\', ':' }) < 0 && !string.IsNullOrWhiteSpace(ticket.OwnedSaveName) && !string.IsNullOrWhiteSpace(ticket.SourceSessionId) && ticket.SourceRevision >= 1 && ticket.OriginPlanetId > 0 && ticket.DestinationPlanetId > 0 && ticket.OriginPlanetId != ticket.DestinationPlanetId && ticket.SavedGameTick >= 0 && ticket.IssuedAtUtc != default(DateTimeOffset) && (ticket.ExpiresAtUtc == default(DateTimeOffset) || ticket.ExpiresAtUtc > ticket.IssuedAtUtc) && IsKnownLifecycle(ticket.LifecycleState) && !string.IsNullOrWhiteSpace(ticket.PlayerStateHash))
			{
				return !string.IsNullOrWhiteSpace(ticket.StarSystemStateHash);
			}
			return false;
		}

		private bool IsReloadEligible(FlightCheckpointTicket? ticket)
		{
			if (IsStructurallyValid(ticket) && ticket != null && EffectiveExpiresAt(ticket) > DateTimeOffset.UtcNow)
			{
				return !IsSuccessfulOrRetired(ticket);
			}
			return false;
		}

		internal static bool IsRecoveryRequired(FlightCheckpointTicket ticket)
		{
			return string.Equals(EffectiveLifecycle(ticket), "recovery_required", StringComparison.Ordinal);
		}

		internal static bool IsAttemptInFlight(FlightCheckpointTicket ticket)
		{
			return string.Equals(EffectiveLifecycle(ticket), "active", StringComparison.Ordinal);
		}

		private static bool IsSuccessfulOrRetired(FlightCheckpointTicket ticket)
		{
			string a = EffectiveLifecycle(ticket);
			if (!string.Equals(a, "flight_succeeded", StringComparison.Ordinal))
			{
				return string.Equals(a, "retired", StringComparison.Ordinal);
			}
			return true;
		}

		private static bool IsKnownLifecycle(string lifecycle)
		{
			if (!string.IsNullOrWhiteSpace(lifecycle) && !string.Equals(lifecycle, "active", StringComparison.Ordinal) && !string.Equals(lifecycle, "recovery_required", StringComparison.Ordinal) && !string.Equals(lifecycle, "flight_succeeded", StringComparison.Ordinal))
			{
				return string.Equals(lifecycle, "retired", StringComparison.Ordinal);
			}
			return true;
		}

		private static string EffectiveLifecycle(FlightCheckpointTicket ticket)
		{
			if (!string.IsNullOrWhiteSpace(ticket.LifecycleState))
			{
				return ticket.LifecycleState;
			}
			return "active";
		}

		private static DateTimeOffset EffectiveExpiresAt(FlightCheckpointTicket ticket)
		{
			if (!(ticket.ExpiresAtUtc == default(DateTimeOffset)))
			{
				return ticket.ExpiresAtUtc;
			}
			return ticket.IssuedAtUtc.Add(TicketLifetime);
		}

		private bool TryPersistLifecycle(FlightCheckpointTicket ticket, string operation, out string rejection)
		{
			_currentTicket = ticket;
			try
			{
				Persist(ticket);
				rejection = string.Empty;
				return true;
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is ArgumentException)
			{
				rejection = "Spherewright could not " + operation + " (" + ex.GetType().Name + ").";
				_logger.LogError((object)rejection);
				return false;
			}
		}

		private FlightCheckpointTicket? ReadFromDisk()
		{
			try
			{
				string json;
				using (FileStream stream = new FileStream(_ticketPath, FileMode.Open, FileAccess.Read, FileShare.Read))
				{
					using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
					json = streamReader.ReadToEnd();
				}
				FlightCheckpointTicket flightCheckpointTicket = PluginJson.Deserialize<FlightCheckpointTicket>(json);
				if (!IsStructurallyValid(flightCheckpointTicket))
				{
					_logger.LogWarning((object)"Spherewright ignored an invalid reusable flight-checkpoint ticket");
					return null;
				}
				_logger.LogInfo((object)"Spherewright loaded a reusable flight-checkpoint ticket from the protected handoff directory");
				return flightCheckpointTicket;
			}
			catch (FileNotFoundException)
			{
				return null;
			}
			catch (DirectoryNotFoundException)
			{
				return null;
			}
			catch (Exception ex3) when (ex3 is IOException || ex3 is UnauthorizedAccessException || ex3 is JsonException || ex3 is ArgumentException)
			{
				_logger.LogWarning((object)("Spherewright ignored an unreadable flight-checkpoint ticket (" + ex3.GetType().Name + ")"));
				return null;
			}
		}

		private void RetireIfCoveredByNewerPrimarySave()
		{
			FlightCheckpointTicket currentTicket = _currentTicket;
			if (!IsStructurallyValid(currentTicket) || currentTicket == null || string.Equals(EffectiveLifecycle(currentTicket), "retired", StringComparison.Ordinal))
			{
				return;
			}
			try
			{
				GameSaveHeader val = default(GameSaveHeader);
				GameSave.ReadHeader(currentTicket.OwnedSaveName, false, ref val);
				if (val != null && val.gameTick > currentTicket.SavedGameTick)
				{
					currentTicket.LifecycleState = "retired";
					currentTicket.RetiredAtGameTick = val.gameTick;
					currentTicket.RetiredAtUtc = DateTimeOffset.UtcNow;
					if (TryPersistLifecycle(currentTicket, "retire a checkpoint superseded by a newer exact primary save", out string _))
					{
						_logger.LogInfo((object)"Spherewright retired a flight checkpoint whose exact primary save already covered a newer timeline");
					}
				}
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is ArgumentException)
			{
				_logger.LogWarning((object)("Spherewright could not compare the exact primary save with its flight checkpoint (" + ex.GetType().Name + ")"));
			}
		}

		private void Persist(FlightCheckpointTicket ticket)
		{
			string? obj = Path.GetDirectoryName(_ticketPath) ?? throw new InvalidOperationException("The flight-checkpoint handoff directory is unavailable.");
			WindowsCurrentUserSecurity.EnsureSecureDirectory(obj);
			string text = Path.Combine(obj, $".flight-checkpoint-{Guid.NewGuid():N}.tmp");
			byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(PluginJson.Serialize(ticket));
			WindowsCurrentUserSecurity.WriteSecureNewFile(text, bytes);
			try
			{
				if (File.Exists(_ticketPath))
				{
					File.Replace(text, _ticketPath, null, ignoreMetadataErrors: true);
				}
				else
				{
					File.Move(text, _ticketPath);
				}
			}
			finally
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
		}

		private static string CreateToken()
		{
			byte[] array = new byte[32];
			using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create())
			{
				randomNumberGenerator.GetBytes(array);
			}
			return Convert.ToBase64String(array).TrimEnd(new char[1] { '=' }).Replace('+', '-')
				.Replace('/', '_');
		}

		private static bool FixedTimeEquals(string left, string right)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(left ?? string.Empty);
			byte[] bytes2 = Encoding.UTF8.GetBytes(right ?? string.Empty);
			int num = bytes.Length ^ bytes2.Length;
			int num2 = Math.Max(bytes.Length, bytes2.Length);
			for (int i = 0; i < num2; i++)
			{
				byte b = (byte)((i < bytes.Length) ? bytes[i] : 0);
				byte b2 = (byte)((i < bytes2.Length) ? bytes2[i] : 0);
				num |= b ^ b2;
			}
			return num == 0;
		}
	}
	internal sealed class FlightCheckpointTicket
	{
		public int Version { get; set; }

		public string CheckpointId { get; set; } = string.Empty;

		public string ReloadToken { get; set; } = string.Empty;

		public string CheckpointSaveName { get; set; } = string.Empty;

		public string OwnedSaveName { get; set; } = string.Empty;

		public string SourceSessionId { get; set; } = string.Empty;

		public long SourceRevision { get; set; }

		public int SourceProcessId { get; set; }

		public string SourceBridgeInstanceId { get; set; } = string.Empty;

		public string GameVersion { get; set; } = string.Empty;

		public int OriginPlanetId { get; set; }

		public int DestinationPlanetId { get; set; }

		public long SavedGameTick { get; set; }

		public string PlayerStateHash { get; set; } = string.Empty;

		public string StarSystemStateHash { get; set; } = string.Empty;

		public DateTimeOffset IssuedAtUtc { get; set; }

		public DateTimeOffset ExpiresAtUtc { get; set; }

		public string LifecycleState { get; set; } = string.Empty;

		public string LastAttemptActionId { get; set; } = string.Empty;

		public long? LastAttemptStartedAtGameTick { get; set; }

		public long? RecoveryRequiredAtGameTick { get; set; }

		public long? SuccessfulFlightAtGameTick { get; set; }

		public long? RetiredAtGameTick { get; set; }

		public DateTimeOffset? RetiredAtUtc { get; set; }
	}
	internal static class FlightCheckpointLifecycleStates
	{
		public const string Active = "active";

		public const string RecoveryRequired = "recovery_required";

		public const string FlightSucceeded = "flight_succeeded";

		public const string Retired = "retired";
	}
	internal sealed class OwnedWorldResumeTicketStore
	{
		private const int TicketVersion = 1;

		private readonly string _ticketPath;

		private readonly string _handoffTicketPath;

		private readonly string _runtimeDirectory;

		private readonly string _bridgeInstanceId;

		private readonly string _gameVersion;

		private readonly ManualLogSource _logger;

		private OwnedWorldResumeTicket? _currentTicket;

		private string? _currentTicketPath;

		public string? CurrentResumeToken => _currentTicket?.ResumeToken;

		public bool HasCurrentTicket => _currentTicket != null;

		public OwnedWorldResumeTicketStore(string configuredRuntimeDirectory, string bridgeInstanceId, string gameVersion, ManualLogSource logger)
		{
			_runtimeDirectory = RuntimeDescriptorPublisher.ResolveRuntimeDirectory(configuredRuntimeDirectory);
			_ticketPath = Path.Combine(_runtimeDirectory, "owned-world-resume.json");
			string text = Path.Combine(Path.GetDirectoryName(typeof(OwnedWorldResumeTicketStore).Assembly.Location) ?? throw new InvalidOperationException("The Spherewright Plugin directory is unavailable."), "runtime-handoff");
			WindowsCurrentUserSecurity.EnsureSecureDirectory(text);
			_handoffTicketPath = Path.Combine(text, "owned-world-resume.json");
			_bridgeInstanceId = bridgeInstanceId;
			_gameVersion = gameVersion;
			_logger = logger;
			_logger.LogInfo((object)"Spherewright initialized the protected owned-world resume ticket store");
			_currentTicket = ReadFromDisk();
		}

		public void ArmFromHealthySavedOwnedSession(string ownedSaveName, string sessionId, int planetId, long minimumGameTick)
		{
			Arm(ownedSaveName, sessionId, planetId, minimumGameTick, string.Empty);
			_logger.LogInfo((object)"Spherewright armed a one-time exact planned-restart ticket from a healthy owned save");
		}

		public void ArmFromQuarantinedOwnedSession(string ownedSaveName, string sessionId, int planetId, long minimumGameTick, string quarantineActionId)
		{
			if (string.IsNullOrWhiteSpace(quarantineActionId))
			{
				throw new InvalidOperationException("A quarantined owned session requires its exact action identity.");
			}
			Arm(ownedSaveName, sessionId, planetId, minimumGameTick, quarantineActionId);
			_logger.LogInfo((object)"Spherewright armed a one-time exact quarantine-recovery ticket");
		}

		private void Arm(string ownedSaveName, string sessionId, int planetId, long minimumGameTick, string quarantineActionId)
		{
			if (string.IsNullOrWhiteSpace(ownedSaveName) || string.IsNullOrWhiteSpace(sessionId) || planetId <= 0 || minimumGameTick < 0)
			{
				throw new InvalidOperationException("A complete owned-session identity is required to arm restart-resume.");
			}
			IReadOnlyList<string> source = CaptureReplicaTokens();
			DateTimeOffset utcNow = DateTimeOffset.UtcNow;
			OwnedWorldResumeTicket ticket = new OwnedWorldResumeTicket
			{
				Version = 1,
				ResumeToken = CreateToken(),
				OwnedSaveName = ownedSaveName,
				SourceSessionId = sessionId,
				SourceProcessId = Process.GetCurrentProcess().Id,
				SourceBridgeInstanceId = _bridgeInstanceId,
				GameVersion = _gameVersion,
				ExpectedPlanetId = planetId,
				MinimumGameTick = minimumGameTick,
				QuarantineActionId = quarantineActionId,
				IssuedAtUtc = utcNow,
				ExpiresAtUtc = utcNow.AddHours(24.0)
			};
			Persist(ticket);
			_currentTicket = ticket;
			_currentTicketPath = null;
			foreach (string item in source.Where((string token) => !FixedTimeEquals(token, ticket.ResumeToken)))
			{
				if (!PersistConsumptionTombstone(item))
				{
					throw new IOException("A superseded resume-ticket generation could not be durably tombstoned.");
				}
				DeleteTicketReplicaIfMatching(_ticketPath, item);
				DeleteTicketReplicaIfMatching(_handoffTicketPath, item);
			}
		}

		public bool TryGetActiveTicket(string resumeToken, out OwnedWorldResumeTicket? ticket, out string rejection)
		{
			ticket = null;
			rejection = string.Empty;
			if (string.IsNullOrWhiteSpace(resumeToken))
			{
				rejection = "A resume token is required.";
				return false;
			}
			OwnedWorldResumeTicket ownedWorldResumeTicket = _currentTicket ?? ReadFromDisk();
			if (ownedWorldResumeTicket == null)
			{
				rejection = "No one-time owned-world resume ticket exists.";
				return false;
			}
			if (IsConsumed(ownedWorldResumeTicket.ResumeToken) || ownedWorldResumeTicket.Version != 1 || !FixedTimeEquals(ownedWorldResumeTicket.ResumeToken, resumeToken) || !string.Equals(ownedWorldResumeTicket.GameVersion, _gameVersion, StringComparison.Ordinal) || ownedWorldResumeTicket.ExpiresAtUtc <= DateTimeOffset.UtcNow || string.IsNullOrWhiteSpace(ownedWorldResumeTicket.OwnedSaveName) || string.IsNullOrWhiteSpace(ownedWorldResumeTicket.SourceSessionId) || ownedWorldResumeTicket.ExpectedPlanetId <= 0 || ownedWorldResumeTicket.MinimumGameTick < 0)
			{
				rejection = "The one-time owned-world resume ticket is consumed, invalid, expired, or belongs to another game version.";
				return false;
			}
			_currentTicket = ownedWorldResumeTicket;
			ticket = ownedWorldResumeTicket;
			return true;
		}

		public void Consume(string resumeToken)
		{
			OwnedWorldResumeTicket ownedWorldResumeTicket = _currentTicket ?? ReadFromDisk();
			if (ownedWorldResumeTicket != null && FixedTimeEquals(ownedWorldResumeTicket.ResumeToken, resumeToken))
			{
				if (!PersistConsumptionTombstone(resumeToken))
				{
					_logger.LogError((object)"Spherewright did not consume the owned-world resume ticket because no durable tombstone could be written");
					return;
				}
				_currentTicket = null;
				_currentTicketPath = null;
				DeleteTicketReplicaIfMatching(_ticketPath, resumeToken);
				DeleteTicketReplicaIfMatching(_handoffTicketPath, resumeToken);
			}
		}

		private IReadOnlyList<string> CaptureReplicaTokens()
		{
			List<string> list = new List<string>();
			if (_currentTicket != null)
			{
				list.Add(_currentTicket.ResumeToken);
			}
			OwnedWorldResumeTicket ownedWorldResumeTicket = ReadFromPath(_ticketPath);
			OwnedWorldResumeTicket ownedWorldResumeTicket2 = ReadFromPath(_handoffTicketPath);
			if (ownedWorldResumeTicket != null)
			{
				list.Add(ownedWorldResumeTicket.ResumeToken);
			}
			if (ownedWorldResumeTicket2 != null)
			{
				list.Add(ownedWorldResumeTicket2.ResumeToken);
			}
			return list.Where((string token) => !string.IsNullOrWhiteSpace(token)).Distinct<string>(StringComparer.Ordinal).ToArray();
		}

		private void DeleteTicketReplicaIfMatching(string path, string resumeToken)
		{
			if (TicketPathMatchesToken(path, resumeToken))
			{
				DeleteTicketPath(path);
			}
		}

		private bool PersistConsumptionTombstone(string resumeToken)
		{
			if (string.IsNullOrWhiteSpace(resumeToken))
			{
				return false;
			}
			string text = HashToken(resumeToken);
			OwnedWorldResumeConsumptionTombstone payload = new OwnedWorldResumeConsumptionTombstone
			{
				Version = 1,
				ResumeTokenHash = text,
				GameVersion = _gameVersion,
				ConsumedAtUtc = DateTimeOffset.UtcNow
			};
			string text2 = Path.GetDirectoryName(_handoffTicketPath) ?? throw new InvalidOperationException("The owned-world handoff directory is unavailable.");
			WindowsCurrentUserSecurity.EnsureSecureDirectory(_runtimeDirectory);
			WindowsCurrentUserSecurity.EnsureSecureDirectory(text2);
			bool num = TryPersistAtPath(GetTombstonePath(_runtimeDirectory, text), _runtimeDirectory, payload, "runtime consumption tombstone");
			bool flag = TryPersistAtPath(GetTombstonePath(text2, text), text2, payload, "handoff consumption tombstone");
			return num || flag;
		}

		private void DeleteTicketPath(string path)
		{
			try
			{
				if (File.Exists(path))
				{
					File.Delete(path);
				}
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
			{
				_logger.LogWarning((object)("Spherewright could not consume its owned-world resume ticket (" + ex.GetType().Name + ")"));
			}
		}

		private static bool TicketPathMatchesToken(string path, string resumeToken)
		{
			try
			{
				if (!File.Exists(path))
				{
					return false;
				}
				OwnedWorldResumeTicket ownedWorldResumeTicket = PluginJson.Deserialize<OwnedWorldResumeTicket>(File.ReadAllText(path));
				return ownedWorldResumeTicket != null && FixedTimeEquals(ownedWorldResumeTicket.ResumeToken, resumeToken);
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is JsonException || ex is ArgumentException)
			{
				return false;
			}
		}

		private OwnedWorldResumeTicket? ReadFromDisk()
		{
			OwnedWorldResumeTicket ticket = ReadFromPath(_ticketPath);
			OwnedWorldResumeTicket ticket2 = ReadFromPath(_handoffTicketPath);
			var array = (from candidate in new[]
				{
					new
					{
						Ticket = ticket,
						Path = _ticketPath,
						Priority = 1
					},
					new
					{
						Ticket = ticket2,
						Path = _handoffTicketPath,
						Priority = 0
					}
				}
				where candidate.Ticket != null && !IsConsumed(candidate.Ticket.ResumeToken)
				orderby candidate.Ticket.IssuedAtUtc descending, candidate.Priority descending
				select candidate).ToArray();
			if (array.Length == 0)
			{
				_currentTicketPath = null;
				return null;
			}
			_currentTicketPath = array[0].Path;
			return array[0].Ticket;
		}

		private bool IsConsumed(string resumeToken)
		{
			if (string.IsNullOrWhiteSpace(resumeToken))
			{
				return false;
			}
			string tokenHash = HashToken(resumeToken);
			string directoryName = Path.GetDirectoryName(_handoffTicketPath);
			if (!TombstoneMatches(GetTombstonePath(_runtimeDirectory, tokenHash), tokenHash))
			{
				if (!string.IsNullOrWhiteSpace(directoryName))
				{
					return TombstoneMatches(GetTombstonePath(directoryName, tokenHash), tokenHash);
				}
				return false;
			}
			return true;
		}

		private bool TombstoneMatches(string path, string tokenHash)
		{
			try
			{
				if (!File.Exists(path))
				{
					return false;
				}
				OwnedWorldResumeConsumptionTombstone ownedWorldResumeConsumptionTombstone = PluginJson.Deserialize<OwnedWorldResumeConsumptionTombstone>(File.ReadAllText(path));
				return ownedWorldResumeConsumptionTombstone != null && ownedWorldResumeConsumptionTombstone.Version == 1 && string.Equals(ownedWorldResumeConsumptionTombstone.GameVersion, _gameVersion, StringComparison.Ordinal) && FixedTimeEquals(ownedWorldResumeConsumptionTombstone.ResumeTokenHash, tokenHash);
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is JsonException || ex is ArgumentException)
			{
				_logger.LogWarning((object)("Spherewright could not read an owned-world resume consumption tombstone (" + ex.GetType().Name + ")"));
				return false;
			}
		}

		private OwnedWorldResumeTicket? ReadFromPath(string path)
		{
			try
			{
				string json;
				using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
				{
					using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
					json = streamReader.ReadToEnd();
				}
				OwnedWorldResumeTicket ownedWorldResumeTicket = PluginJson.Deserialize<OwnedWorldResumeTicket>(json);
				if (ownedWorldResumeTicket == null)
				{
					_logger.LogWarning((object)"Spherewright ignored an empty owned-world resume ticket payload");
					return null;
				}
				_logger.LogInfo((object)"Spherewright loaded an owned-world restart-resume ticket from the protected runtime directory");
				return ownedWorldResumeTicket;
			}
			catch (FileNotFoundException)
			{
				_logger.LogInfo((object)"Spherewright found no owned-world resume ticket at a fixed protected path");
				return null;
			}
			catch (DirectoryNotFoundException)
			{
				_logger.LogInfo((object)"Spherewright found no owned-world resume directory at the fixed protected path");
				return null;
			}
			catch (Exception ex3) when (ex3 is IOException || ex3 is UnauthorizedAccessException || ex3 is JsonException || ex3 is ArgumentException)
			{
				_logger.LogWarning((object)("Spherewright ignored an unreadable owned-world resume ticket (" + ex3.GetType().Name + ")"));
				return null;
			}
		}

		private void Persist(OwnedWorldResumeTicket ticket)
		{
			WindowsCurrentUserSecurity.EnsureSecureDirectory(_runtimeDirectory);
			string text = Path.GetDirectoryName(_handoffTicketPath) ?? throw new InvalidOperationException("The owned-world handoff directory is unavailable.");
			WindowsCurrentUserSecurity.EnsureSecureDirectory(text);
			bool num = TryPersistAtPath(_ticketPath, _runtimeDirectory, ticket, "runtime resume-ticket replica");
			bool flag = TryPersistAtPath(_handoffTicketPath, text, ticket, "handoff resume-ticket replica");
			if (!num && !flag)
			{
				throw new IOException("No protected owned-world resume ticket replica could be persisted.");
			}
			if (!num || !flag)
			{
				_logger.LogWarning((object)"Spherewright armed the resume ticket with one durable replica; startup generation selection will prefer the newest surviving ticket");
			}
		}

		private static void PersistAtPath(string destinationPath, string directory, object payload)
		{
			string text = Path.Combine(directory, $".owned-world-resume-{Guid.NewGuid():N}.tmp");
			byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(PluginJson.Serialize(payload));
			WindowsCurrentUserSecurity.WriteSecureNewFile(text, bytes);
			try
			{
				if (File.Exists(destinationPath))
				{
					File.Replace(text, destinationPath, null, ignoreMetadataErrors: true);
				}
				else
				{
					File.Move(text, destinationPath);
				}
			}
			finally
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
		}

		private bool TryPersistAtPath(string destinationPath, string directory, object payload, string replicaName)
		{
			try
			{
				PersistAtPath(destinationPath, directory, payload);
				return true;
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is ArgumentException)
			{
				_logger.LogWarning((object)("Spherewright could not persist its " + replicaName + " (" + ex.GetType().Name + ")"));
				return false;
			}
		}

		private static string GetTombstonePath(string directory, string tokenHash)
		{
			return Path.Combine(directory, "owned-world-resume-consumed-" + tokenHash + ".json");
		}

		private static string HashToken(string token)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(token ?? string.Empty))).Replace("-", string.Empty).ToLowerInvariant();
		}

		private static string CreateToken()
		{
			byte[] array = new byte[32];
			using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create())
			{
				randomNumberGenerator.GetBytes(array);
			}
			return Convert.ToBase64String(array).TrimEnd(new char[1] { '=' }).Replace('+', '-')
				.Replace('/', '_');
		}

		private static bool FixedTimeEquals(string left, string right)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(left ?? string.Empty);
			byte[] bytes2 = Encoding.UTF8.GetBytes(right ?? string.Empty);
			int num = bytes.Length ^ bytes2.Length;
			int num2 = Math.Max(bytes.Length, bytes2.Length);
			for (int i = 0; i < num2; i++)
			{
				byte b = (byte)((i < bytes.Length) ? bytes[i] : 0);
				byte b2 = (byte)((i < bytes2.Length) ? bytes2[i] : 0);
				num |= b ^ b2;
			}
			return num == 0;
		}
	}
	internal sealed class OwnedWorldResumeTicket
	{
		public int Version { get; set; }

		public string ResumeToken { get; set; } = string.Empty;

		public string OwnedSaveName { get; set; } = string.Empty;

		public string SourceSessionId { get; set; } = string.Empty;

		public int SourceProcessId { get; set; }

		public string SourceBridgeInstanceId { get; set; } = string.Empty;

		public string GameVersion { get; set; } = string.Empty;

		public int ExpectedPlanetId { get; set; }

		public long MinimumGameTick { get; set; }

		public string QuarantineActionId { get; set; } = string.Empty;

		public DateTimeOffset IssuedAtUtc { get; set; }

		public DateTimeOffset ExpiresAtUtc { get; set; }
	}
	internal sealed class OwnedWorldResumeConsumptionTombstone
	{
		public int Version { get; set; }

		public string ResumeTokenHash { get; set; } = string.Empty;

		public string GameVersion { get; set; } = string.Empty;

		public DateTimeOffset ConsumedAtUtc { get; set; }
	}
	internal sealed class RuntimeDescriptorPublisher : IDisposable
	{
		private readonly string _runtimeDirectory;

		private readonly ManualLogSource _logger;

		private string? _descriptorPath;

		public RuntimeDescriptorPublisher(string configuredDirectory, ManualLogSource logger)
		{
			try
			{
				_runtimeDirectory = ResolveRuntimeDirectory(configuredDirectory);
			}
			catch (Exception innerException)
			{
				throw new InvalidOperationException("Runtime descriptor directory normalization failed.", innerException);
			}
			_logger = logger ?? throw new ArgumentNullException("logger");
		}

		internal static string ResolveRuntimeDirectory(string configuredDirectory)
		{
			if (configuredDirectory.StartsWith("%LOCALAPPDATA%", StringComparison.OrdinalIgnoreCase))
			{
				string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
				if (string.IsNullOrWhiteSpace(folderPath))
				{
					throw new InvalidOperationException("The local application-data directory is unavailable.");
				}
				string path = configuredDirectory.Substring("%LOCALAPPDATA%".Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
				return Path.GetFullPath(Path.Combine(folderPath, path).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar));
			}
			string path2 = Environment.ExpandEnvironmentVariables(configuredDirectory).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
			if (!Path.IsPathRooted(path2))
			{
				throw new InvalidOperationException("The runtime descriptor directory must be an absolute path.");
			}
			return Path.GetFullPath(path2);
		}

		public void Publish(BridgeRuntimeDescriptor descriptor)
		{
			if (descriptor == null)
			{
				throw new ArgumentNullException("descriptor");
			}
			EnsureSecureDirectory();
			CleanupStaleDescriptors();
			string text = Path.Combine(_runtimeDirectory, $"bridge-{descriptor.ProcessId}.json");
			string text2 = Path.Combine(_runtimeDirectory, $".bridge-{descriptor.ProcessId}-{Guid.NewGuid():N}.tmp");
			string s = PluginJson.Serialize<BridgeRuntimeDescriptor>(descriptor);
			WindowsCurrentUserSecurity.WriteSecureNewFile(text2, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(s));
			File.Move(text2, text);
			_descriptorPath = text;
		}

		public void Dispose()
		{
			string descriptorPath = _descriptorPath;
			_descriptorPath = null;
			if (descriptorPath == null)
			{
				return;
			}
			try
			{
				if (File.Exists(descriptorPath))
				{
					File.Delete(descriptorPath);
				}
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
			{
				_logger.LogWarning((object)("Spherewright could not remove its runtime descriptor (" + ex.GetType().Name + ")"));
			}
		}

		private void EnsureSecureDirectory()
		{
			WindowsCurrentUserSecurity.EnsureSecureDirectory(_runtimeDirectory);
		}

		private void CleanupStaleDescriptors()
		{
			string[] files = Directory.GetFiles(_runtimeDirectory, "bridge-*.json", SearchOption.TopDirectoryOnly);
			foreach (string path in files)
			{
				try
				{
					BridgeRuntimeDescriptor val = PluginJson.Deserialize<BridgeRuntimeDescriptor>(File.ReadAllText(path));
					if (val == null || !IsLiveDspProcess(val.ProcessId))
					{
						File.Delete(path);
					}
				}
				catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is JsonException || ex is ArgumentException)
				{
					_logger.LogWarning((object)("Spherewright ignored an unreadable stale descriptor candidate (" + ex.GetType().Name + ")"));
				}
			}
		}

		private static bool IsLiveDspProcess(int processId)
		{
			try
			{
				using Process process = Process.GetProcessById(processId);
				return !process.HasExited && string.Equals(process.ProcessName, "DSPGAME", StringComparison.OrdinalIgnoreCase);
			}
			catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException || ex is Win32Exception)
			{
				return false;
			}
		}
	}
}
namespace Spherewright.Plugin.Hosting
{
	internal sealed class BridgeIdentity
	{
		public string BridgeInstanceId { get; }

		public string PipeName { get; }

		public string AuthToken { get; }

		private BridgeIdentity(string bridgeInstanceId, string pipeName, string authToken)
		{
			BridgeInstanceId = bridgeInstanceId;
			PipeName = pipeName;
			AuthToken = authToken;
		}

		public static BridgeIdentity Create(string pipeNamePrefix)
		{
			int id = Process.GetCurrentProcess().Id;
			string arg = Base64Url(RandomBytes(12));
			string authToken = Base64Url(RandomBytes(32));
			return new BridgeIdentity(Guid.NewGuid().ToString("N"), $"{pipeNamePrefix}-{id}-{arg}", authToken);
		}

		private static byte[] RandomBytes(int count)
		{
			byte[] array = new byte[count];
			using RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create();
			randomNumberGenerator.GetBytes(array);
			return array;
		}

		private static string Base64Url(byte[] bytes)
		{
			return Convert.ToBase64String(bytes).TrimEnd(new char[1] { '=' }).Replace('+', '-')
				.Replace('/', '_');
		}
	}
	internal sealed class BridgeStatusSnapshotProvider
	{
		private readonly object _gate = new object();

		private readonly string _bridgeInstanceId;

		private readonly string _pluginVersion;

		private readonly bool _writesConfigured;

		private string _gameVersion;

		private bool _gameLoaded;

		public BridgeStatusSnapshotProvider(string bridgeInstanceId, string pluginVersion, string gameVersion, bool writesConfigured)
		{
			_bridgeInstanceId = bridgeInstanceId;
			_pluginVersion = pluginVersion;
			_gameVersion = gameVersion;
			_writesConfigured = writesConfigured;
		}

		public void UpdateGameVersionOnMainThread(string gameVersion)
		{
			lock (_gate)
			{
				_gameVersion = gameVersion;
			}
		}

		public void UpdateGameLoadedOnMainThread(bool gameLoaded)
		{
			lock (_gate)
			{
				_gameLoaded = gameLoaded;
			}
		}

		public BridgeStatus Capture()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			lock (_gate)
			{
				return new BridgeStatus
				{
					BridgeConnected = true,
					BridgeInstanceId = _bridgeInstanceId,
					PluginVersion = _pluginVersion,
					ProtocolVersion = 1,
					GameVersion = _gameVersion,
					GameLoaded = _gameLoaded,
					WritesConfigured = _writesConfigured,
					WriteHealth = "healthy"
				};
			}
		}
	}
	internal sealed class SpherewrightBridgeHost : IDisposable
	{
		private readonly SpherewrightConfiguration _configuration;

		private readonly ManualLogSource _logger;

		private readonly GameVersionSnapshotProvider _gameVersionProvider;

		private readonly GameSessionTracker _sessionTracker;

		private readonly GameplayJournalManager _gameplayJournalManager;

		private readonly NormalGameActionCoordinator _normalActionCoordinator;

		private readonly ResearchResultAutoAcknowledger _researchResultAutoAcknowledger;

		private readonly BridgeStatusSnapshotProvider _statusProvider;

		private readonly BoundedMainThreadDispatcher _dispatcher;

		private readonly RuntimeDescriptorPublisher _descriptorPublisher;

		private readonly NamedPipeBridgeServer _pipeServer;

		private readonly BridgeRuntimeDescriptor _descriptor;

		private bool _started;

		private bool _pumpLogged;

		private int _framesSinceVersionRefresh;

		private SpherewrightBridgeHost(SpherewrightConfiguration configuration, ManualLogSource logger, GameVersionSnapshotProvider gameVersionProvider, GameSessionTracker sessionTracker, GameplayJournalManager gameplayJournalManager, NormalGameActionCoordinator normalActionCoordinator, ResearchResultAutoAcknowledger researchResultAutoAcknowledger, BridgeStatusSnapshotProvider statusProvider, BoundedMainThreadDispatcher dispatcher, RuntimeDescriptorPublisher descriptorPublisher, NamedPipeBridgeServer pipeServer, BridgeRuntimeDescriptor descriptor)
		{
			_configuration = configuration;
			_logger = logger;
			_gameVersionProvider = gameVersionProvider;
			_sessionTracker = sessionTracker;
			_gameplayJournalManager = gameplayJournalManager;
			_normalActionCoordinator = normalActionCoordinator;
			_researchResultAutoAcknowledger = researchResultAutoAcknowledger;
			_statusProvider = statusProvider;
			_dispatcher = dispatcher;
			_descriptorPublisher = descriptorPublisher;
			_pipeServer = pipeServer;
			_descriptor = descriptor;
		}

		public static SpherewrightBridgeHost Create(SpherewrightConfiguration configuration, ManualLogSource logger, string pluginVersion)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Expected O, but got Unknown
			BridgeIdentity bridgeIdentity = BridgeIdentity.Create(configuration.PipeNamePrefix);
			GameVersionSnapshotProvider gameVersionSnapshotProvider = new GameVersionSnapshotProvider();
			string gameVersion = gameVersionSnapshotProvider.CaptureOnMainThread();
			BridgeStatusSnapshotProvider statusProvider = new BridgeStatusSnapshotProvider(bridgeIdentity.BridgeInstanceId, pluginVersion, gameVersion, configuration.AllowWrites);
			BoundedMainThreadDispatcher dispatcher = new BoundedMainThreadDispatcher(configuration.MaxMainThreadQueue);
			OwnedWorldResumeTicketStore ownedWorldResumeTicketStore = new OwnedWorldResumeTicketStore(configuration.RuntimeDescriptorDirectory, bridgeIdentity.BridgeInstanceId, gameVersion, logger);
			FlightCheckpointStore flightCheckpointStore = new FlightCheckpointStore(bridgeIdentity.BridgeInstanceId, gameVersion, logger);
			GameSessionTracker gameSessionTracker = new GameSessionTracker(configuration.AllowWrites, configuration.AllowUserSaveImport, gameVersion, ownedWorldResumeTicketStore, flightCheckpointStore, logger);
			UserSaveImportCoordinator userSaveImportCoordinator = new UserSaveImportCoordinator(configuration.AllowUserSaveImport, configuration.AllowWrites, configuration.PlanTokenLifetimeSeconds, configuration.IdempotencyRetentionMinutes, configuration.MaxIdempotencyEntriesPerSession, gameSessionTracker);
			GameStateReader gameStateReader = new GameStateReader(gameSessionTracker);
			GameplayJournalManager gameplayJournalManager = new GameplayJournalManager(configuration.RuntimeDescriptorDirectory, gameVersion, gameSessionTracker, logger);
			NormalGameActionCoordinator normalGameActionCoordinator = new NormalGameActionCoordinator(configuration.PlanTokenLifetimeSeconds, configuration.IdempotencyRetentionMinutes, configuration.MaxIdempotencyEntriesPerSession, gameSessionTracker, gameStateReader, flightCheckpointStore);
			ResearchResultAutoAcknowledger researchResultAutoAcknowledger = new ResearchResultAutoAcknowledger(configuration.AutoAcknowledgeResearchResults, logger);
			TestWorldCoordinator testWorldCoordinator = new TestWorldCoordinator(configuration.AllowWrites, configuration.PlanTokenLifetimeSeconds, configuration.IdempotencyRetentionMinutes, configuration.MaxIdempotencyEntriesPerSession, gameSessionTracker);
			OwnedWorldResumeCoordinator ownedWorldResumeCoordinator = new OwnedWorldResumeCoordinator(configuration.Allo