[
  {
    "path": ".github/FUNDING.yml",
    "content": "github: [muukii]\npatreon: muukii\nko_fi: muukii\n"
  },
  {
    "path": ".github/workflows/CommitChecks.yml",
    "content": "name: CommitChecks\n\non:\n  push:\n    branches:\n      - \"**\"\n\njobs:\n  test:\n    runs-on: macos-15\n\n    steps:\n      - uses: maxim-lobanov/setup-xcode@v1.1\n        with:\n          xcode-version: \"26\"\n      - uses: actions/checkout@v2\n      - name: Run Test\n        run: set -o pipefail && xcodebuild -scheme Verge-Package test -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.0' -skipMacroValidation -skipPackagePluginValidation | xcbeautify\n\n  ui-test:\n    runs-on: macos-15\n    defaults:\n      run:\n        working-directory: ./Development\n\n    steps:\n      - uses: maxim-lobanov/setup-xcode@v1.1\n        with:\n          xcode-version: \"26\"\n      - uses: actions/checkout@v2\n      - uses: jdx/mise-action@v2\n        with:\n          install: true\n          cache: true\n          experimental: true\n      - run: tuist install\n      - run: tuist generate --no-open\n      - run: tuist test\n"
  },
  {
    "path": ".gitignore",
    "content": "\n# Created by https://www.gitignore.io/api/swift\n\n### Swift ###\n# Xcode\n#\n# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore\n/worktree\n\n## Build generated\nbuild/\nDerivedData/\n\n.swiftpm\n\n## Various settings\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata/\n\n## Other\n*.moved-aside\n*.xccheckout\n*.xcscmblueprint\n\n## Obj-C/Swift specific\n*.hmap\n*.ipa\n*.dSYM.zip\n*.dSYM\n\n## Playgrounds\ntimeline.xctimeline\nplayground.xcworkspace\n\n# Swift Package Manager\n#\n# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.\n# Packages/\n# Package.pins\n.build/\n\n# CocoaPods - Refactored to standalone file\n\nPods\n\n# Carthage - Refactored to standalone file\n\nCarthage\n\n# fastlane\n#\n# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the\n# screenshots whenever they are needed.\n# For more information about the recommended setup visit:\n# https://docs.fastlane.tools/best-practices/source-control/#source-control\n\nfastlane/report.xml\nfastlane/Preview.html\nfastlane/screenshots\nfastlane/test_output\n\n.DS_Store\n\n# Tuist\nDerived\n*.xcodeproj\n\nWorkspace.xcworkspace/\n\nsettings.local.json\n\n# End of https://www.gitignore.io/api/swift\n"
  },
  {
    "path": ".spi.yml",
    "content": "version: 1\nbuilder:\n  configs:\n    - documentation_targets: [Verge, VergeNormalizationDerived]\n"
  },
  {
    "path": "Development/.gitignore",
    "content": "### macOS ###\n# General\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Icon must end with two\nIcon\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n.com.apple.timemachine.donotpresent\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n### Xcode ###\n# Xcode\n#\n# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore\n\n## User settings\nxcuserdata/\n\n## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)\n*.xcscmblueprint\n*.xccheckout\n\n## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)\nbuild/\nDerivedData/\n*.moved-aside\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\n\n### Xcode Patch ###\n*.xcodeproj/*\n!*.xcodeproj/project.pbxproj\n!*.xcodeproj/xcshareddata/\n!*.xcworkspace/contents.xcworkspacedata\n/*.gcno\n\n### Projects ###\n*.xcodeproj\n*.xcworkspace\n\n### Tuist derived files ###\ngraph.dot\nDerived/\n\n### Tuist managed dependencies ###\nTuist/.build"
  },
  {
    "path": "Development/Development/Resources/Assets.xcassets/AccentColor.colorset/Contents.json",
    "content": "{\n  \"colors\" : [\n    {\n      \"idiom\" : \"universal\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "Development/Development/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"idiom\" : \"iphone\",\n      \"scale\" : \"2x\",\n      \"size\" : \"20x20\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"scale\" : \"3x\",\n      \"size\" : \"20x20\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"scale\" : \"2x\",\n      \"size\" : \"29x29\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"scale\" : \"3x\",\n      \"size\" : \"29x29\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"scale\" : \"2x\",\n      \"size\" : \"40x40\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"scale\" : \"3x\",\n      \"size\" : \"40x40\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"scale\" : \"2x\",\n      \"size\" : \"60x60\"\n    },\n    {\n      \"idiom\" : \"iphone\",\n      \"scale\" : \"3x\",\n      \"size\" : \"60x60\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"scale\" : \"1x\",\n      \"size\" : \"20x20\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"scale\" : \"2x\",\n      \"size\" : \"20x20\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"scale\" : \"1x\",\n      \"size\" : \"29x29\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"scale\" : \"2x\",\n      \"size\" : \"29x29\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"scale\" : \"1x\",\n      \"size\" : \"40x40\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"scale\" : \"2x\",\n      \"size\" : \"40x40\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"scale\" : \"1x\",\n      \"size\" : \"76x76\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"scale\" : \"2x\",\n      \"size\" : \"76x76\"\n    },\n    {\n      \"idiom\" : \"ipad\",\n      \"scale\" : \"2x\",\n      \"size\" : \"83.5x83.5\"\n    },\n    {\n      \"idiom\" : \"ios-marketing\",\n      \"scale\" : \"1x\",\n      \"size\" : \"1024x1024\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "Development/Development/Resources/Assets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "Development/Development/Resources/Preview Content/Preview Assets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "Development/Development/Sources/BookBinding.swift",
    "content": "\nimport SwiftUI\nimport Verge\n\nstruct BookBindingUsingReading: View {\n  \n  @ReadingObject<Store<BookBindingState, Never>> var state: BookBindingState\n  \n  init() {\n    self._state = .init({\n      .init(initialState: .init())\n    })\n  }\n  \n  var body: some View {\n    Counter(value: $state.value)\n  }\n  \n  struct Counter: View {\n    \n    @Binding var value: Int\n    \n    var body: some View {\n      VStack {\n        Text(\"\\(value)\")\n        Button {\n          value += 1\n        } label: {\n          Text(\"Increment\")\n        }\n      }\n    }\n  }\n  \n}\n\nstruct BookBindingUsingStoreReader: View {\n  \n  let store: Store<BookBindingState, Never> = .init(initialState: .init())\n  \n  init() {\n  }\n  \n  var body: some View {\n    StoreReader(store) { $state in      \n      Counter(value: $state.value)\n    }\n  }\n  \n  struct Counter: View {\n    \n    @Binding var value: Int\n    \n    var body: some View {\n      VStack {\n        Text(\"\\(value)\")\n        Button {\n          value += 1\n        } label: {\n          Text(\"Increment\")\n        }\n      }\n    }\n  }\n  \n}\n\n@Tracking\nstruct BookBindingState {\n  \n  var value: Int = 0\n  \n}\n\n#Preview(\"Binding Reading\") {\n  BookBindingUsingReading()\n}\n\n#Preview(\"Binding StoreReader\") {\n  BookBindingUsingStoreReader()\n}\n"
  },
  {
    "path": "Development/Development/Sources/BookLongList.swift",
    "content": "//\n//  BookLongList.swift\n//  Development\n//\n//  Created by Muukii on 2025/03/26.\n//\n\nimport SwiftUI\nimport Verge\n\n@Tracking\nstruct BookState {\n  var items: [BookItem] = []\n  \n  init(items: [BookItem]) {\n    self.items = items\n  }\n}\n\nstruct BookItem: Identifiable {\n  var id: some Hashable {\n    cellStore\n  }\n  let cellStore: Store<BookCellState, Never>\n}\n\n@Tracking\nstruct BookCellState {\n  let id: Int\n  var title: String\n  var isSelected: Bool = false\n}\n\nstruct BookCellContent: View {\n  \n  let store: Store<BookCellState, Never>\n\n  var body: some View {\n    StoreReader(store) { $state in\n      RoundedRectangle(cornerRadius: 8)\n        .fill(state.isSelected ? Color.red : Color.blue.opacity(0.2))\n        .aspectRatio(1, contentMode: .fit)\n        .overlay(\n          Text(\"\\(state.id + 1)\")\n            .font(.system(size: 16))\n        )       \n    }\n  }\n}\n\nstruct BookCell: View {\n  \n  let store: Store<BookCellState, Never>\n\n  var body: some View {\n    Button {\n      store.commit { state in\n        state.isSelected.toggle()\n      }\n    } label: {      \n      BookCellContent(store: store)\n    }\n  }\n}\n\nstruct BookLongList: View {\n  private let columns = [\n    GridItem(.flexible()),\n    GridItem(.flexible()),\n    GridItem(.flexible()),\n    GridItem(.flexible()),\n  ]\n\n  @ReadingObject<Store<BookState, Never>>({\n    .init(initialState: .init(items: (0..<500).map { index in\n      BookItem(\n        cellStore: Store<BookCellState, Never>(\n          initialState: BookCellState(\n            id: index,\n            title: UUID().uuidString\n          )\n        )\n      )\n    }))\n  }) var state: BookState\n\n  init() {\n    \n  }\n\n  var body: some View {\n    ScrollView {\n      LazyVGrid(columns: columns, spacing: 16) {\n        ForEach(state.items) { item in\n          BookCell(store: item.cellStore)\n        }\n      }\n      .padding()\n    }\n  }\n}\n\n#Preview {\n  BookLongList()\n}\n"
  },
  {
    "path": "Development/Development/Sources/BookReadingPropertyWrapper.swift",
    "content": "import Verge\nimport SwiftUI\n\nstruct BookReading: View {\n  \n  var body: some View {\n    ReadingSolution()\n  }\n  \n}\n\n@Tracking\nstruct MyState {\n  \n  var value: Int = 0\n  \n  var a: Int = 0\n  var b: Int = 0\n  var c: Int = 0\n}\n\nextension Store where State == MyState {\n  \n  func backgroundUpdate() {\n    Task {\n      await self.backgroundCommit { \n        $0.value += 1\n        $0.a += 1\n        $0.b += 1\n        $0.c += 1      \n      }\n    }\n  }\n  \n}\n\nenum ItemKind: Identifiable {\n  case first\n  case second\n  case third\n  var id: String {\n    switch self {\n    case .first: return \"1\"\n    case .second: return \"2\"\n    case .third: return \"3\"\n    }\n  }\n}\n\nstruct ItemDetail<Item: Identifiable, Content: View>: View {\n  \n  let items: [Item]\n  let content: (Item) -> Content\n  \n  @State var selectedItem: Item?\n  private let name: String\n  \n  init(\n    name: String,\n    items: [Item],\n    @ViewBuilder content: @escaping (Item) -> Content\n  ) {\n    self.name = name\n    self.items = items\n    self.content = content    \n  }\n  \n  var body: some View {\n    VStack {\n      ForEach(items) { item in\n        Button(\"\\(name).\\(item.id)\") {\n          selectedItem = item\n        }          \n      }\n            \n      if let item = selectedItem {\n        content(item)\n          .padding()\n          .background(Color.orange)\n      }\n    }\n  }\n  \n}\n\nprivate struct ReadingSolution: View {\n  \n  @State var id: Int = 0\n  @State var outerValue: Int = 0\n  \n  init() {\n    print(\"init\")\n  }\n  \n  var body: some View {\n    VStack {   \n      \n      Button(\"New\") {\n        id += 1\n      }\n      Button(\"Up Outer\") {\n        outerValue += 1\n      }\n      Solution(outerValue: outerValue)\n        .id(id)\n        .padding()\n        .background(Color.green)\n\n    }\n  }\n  \n  struct Solution: View {\n    \n    let items: [ItemKind] = [\n      .first,\n      .second,\n      .third,\n    ]\n    \n    @ReadingObject<Store<MyState, Never>> var state: MyState\n    \n    private let outerValue: Int\n    \n    init(outerValue: Int) {\n      self._state = .init(\n        label: \"A\", { \n          Store<_, Never>.init(initialState: MyState())\n        }\n      )\n      self.outerValue = outerValue\n    }\n    \n    var body: some View {\n      HStack {\n        VStack {\n          Text(\"Using Store holding\")\n          Button(\"async up\") {\n            $state.driver.backgroundUpdate()\n          }\n          Button(\"A Up\") {\n            $state.driver.commit {\n              $0.value += 1\n            }\n          }\n          Text(\"A Value: \\(state.value)\")\n          Text(\"Outer: \\(outerValue)\")\n          ItemDetail(name: \"A\", items: items) { item in\n            switch item {\n            case .first:\n              Button.init(\"A.1.a: \\(state.a)\") {             \n                $state.driver.commit {\n                  $0.a += 1\n                }\n              }\n            case .second:\n              Button.init(\"A.1.b: \\(state.b)\") {             \n                $state.driver.commit {\n                  $0.b += 1\n                }\n              }        \n            case .third:\n              Button.init(\"A.1.c: \\(state.c)\") {             \n                $state.driver.commit {\n                  $0.c += 1\n                }\n              }              \n            }\n            \n          }\n          .padding()\n          .background(Color.yellow)\n        }\n        Passed(store: $state.driver)\n      }\n    }\n  }\n  \n  struct Passed: View {\n    \n    let items: [ItemKind] = [\n      .first,\n      .second,\n      .third,\n    ]\n    \n    @Reading<Store<MyState, Never>> var state: MyState\n    \n    init(\n      store: Store<MyState, Never>\n    ) {\n      self._state = .init(label: \"B\", store)\n    }\n    \n    var body: some View {\n      VStack {\n        Text(\"Using Store passed\")\n        Button(\"B Up\") {\n          $state.driver.commit {\n            $0.value += 1\n          }\n        }\n        Text(\"B Value: \\(state.value)\")\n        ItemDetail(name: \"B\",items: items) { item in\n          switch item {\n          case .first:\n            Button.init(\"B.1.a: \\(state.a)\") {             \n              $state.driver.commit {\n                $0.a += 1\n              }\n            }\n          case .second:\n            Button.init(\"B.1.b: \\(state.b)\") {             \n              $state.driver.commit {\n                $0.b += 1\n              }\n            }        \n          case .third:\n            Button.init(\"B.1.c: \\(state.c)\") {             \n              $state.driver.commit {\n                $0.c += 1\n              }\n            }              \n          }\n          \n        }\n        .padding()\n        .background(Color.yellow)\n      }\n    }\n    \n  }\n}\n\nstruct PassedContainer: View {\n  \n  private let store: Store<MyState, Never> = .init(initialState: MyState())\n  @State var count: Int = 0\n  \n  var body: some View {\n    VStack {\n      Button(\"Outer Up \\(count)\") {\n        count += 1\n      }\n      ReadingSolution.Passed(store: store)\n    }\n  }\n  \n}\n\n#Preview(\"Reading solution\") {\n  ReadingSolution()\n}\n\n#Preview(\"Passed solution\") {\n  PassedContainer()\n}\n"
  },
  {
    "path": "Development/Development/Sources/BookStoreReader.swift",
    "content": "import SwiftUI\nimport Verge\n\nstruct StoreReaderSolution: View {\n  @State var id: Int = 0\n  @State var outerValue: Int = 0\n  \n  init() {\n    print(\"init\")\n  }\n  \n  var body: some View {\n    VStack {   \n      Button(\"New\") {\n        id += 1\n      }\n      Button(\"Up Outer\") {\n        outerValue += 1\n      }\n      Solution(outerValue: outerValue)\n        .id(id)\n        .padding()\n        .background(Color.green)\n    }\n  }\n  \n  struct Solution: View {\n    let items: [ItemKind] = [\n      .first,\n      .second,\n      .third,\n    ]\n    \n    @StoreObject var store = Store<MyState, Never>(initialState: .init())\n    private let outerValue: Int\n    \n    init(outerValue: Int) {\n      self.outerValue = outerValue\n    }\n    \n    var body: some View {\n      HStack {\n        VStack {\n          Text(\"Using Store holding\")\n          StoreReader(store) { $state in\n            VStack {\n              Button(\"A Up\") {\n                store.commit {\n                  $0.value += 1\n                }\n              }\n              Text(\"A Value: \\(state.value)\")\n              Text(\"Outer: \\(outerValue)\")\n              ItemDetail(name: \"A\", items: items) { item in\n                switch item {\n                case .first:\n                  Button(\"A.1.a: \\(state.a)\") {\n                    store.commit {\n                      $0.a += 1\n                    }\n                  }\n                case .second:\n                  Button(\"A.1.b: \\(state.b)\") {\n                    store.commit {\n                      $0.b += 1\n                    }\n                  }\n                case .third:\n                  Button(\"A.1.c: \\(state.c)\") {\n                    store.commit {\n                      $0.c += 1\n                    }\n                  }\n                }\n              }\n              .padding()\n              .background(Color.yellow)\n            }\n          }\n        }\n        Passed(store: store)\n      }\n    }\n  }\n  \n  struct Passed: View {\n    let items: [ItemKind] = [\n      .first,\n      .second,\n      .third,\n    ]\n    \n    private let store: Store<MyState, Never>\n    \n    init(store: Store<MyState, Never>) {\n      self.store = store\n    }\n    \n    var body: some View {\n      VStack {\n        Text(\"Using Store passed\")\n        StoreReader(store) { $state in\n          VStack {\n            Button(\"B Up\") {\n              store.commit {\n                $0.value += 1\n              }\n            }\n            Text(\"B Value: \\(state.value)\")\n            ItemDetail(name: \"B\", items: items) { item in\n              switch item {\n              case .first:\n                Button(\"B.1.a: \\(state.a)\") {\n                  store.commit {\n                    $0.a += 1\n                  }\n                }\n              case .second:\n                Button(\"B.1.b: \\(state.b)\") {\n                  store.commit {\n                    $0.b += 1\n                  }\n                }\n              case .third:\n                Button(\"B.1.c: \\(state.c)\") {\n                  store.commit {\n                    $0.c += 1\n                  }\n                }\n              }\n            }\n            .padding()\n            .background(Color.yellow)\n          }\n        }\n      }\n    }\n  }\n}\n\n\n#Preview(\"Reading solution\") {\n  StoreReaderSolution()\n}\n"
  },
  {
    "path": "Development/Development/Sources/ContentView.swift",
    "content": "import SwiftUI\n\npublic struct ContentView: View {\n  public init() {}\n\n  public var body: some View {\n    NavigationStack {\n\n      List {\n\n        NavigationLink {\n          BookReading()\n        } label: {\n          Text(\"@Reading\")\n        }\n\n        NavigationLink {\n          PassedContainer()\n        } label: {\n          Text(\"@Reading - passed\")\n        }\n        \n        NavigationLink {\n          StoreReaderSolution()\n        } label: {\n          Text(\"StoreReader\")\n        }\n        \n        NavigationLink {\n          BookLongList()\n        } label: {\n          Text(\"Long List\")\n        }\n        \n        NavigationLink {\n          BookBindingUsingReading()\n        } label: {\n          Text(\"Binding @Reading\")\n        }\n        \n        NavigationLink {\n          BookBindingUsingStoreReader()\n        } label: {\n          Text(\"Binding StoreReader\")\n        }\n      }\n\n    }\n  }\n}\n\nstruct ContentView_Previews: PreviewProvider {\n  static var previews: some View {\n    ContentView()\n  }\n}\n"
  },
  {
    "path": "Development/Development/Sources/DevelopmentApp.swift",
    "content": "import SwiftUI\n\n@main\nstruct DevelopmentApp: App {\n    var body: some Scene {\n        WindowGroup {\n            ContentView()\n        }\n    }\n}\n"
  },
  {
    "path": "Development/Development/Tests/DevelopmentTests.swift",
    "content": "import Foundation\nimport XCTest\n\nfinal class DevelopmentTests: XCTestCase {\n    func test_twoPlusTwo_isFour() {\n        XCTAssertEqual(2+2, 4)\n    }\n}"
  },
  {
    "path": "Development/Development/UITests/ReadingTests.swift",
    "content": "import XCTest\n\nfinal class ReadingTests: XCTestCase {\n\n  var app: XCUIApplication!\n\n  override func setUpWithError() throws {\n    continueAfterFailure = false\n    app = XCUIApplication()\n    app.launch()\n  }\n\n  override func tearDownWithError() throws {\n    app = nil\n  }\n\n  func testA_up() {\n\n    let app = XCUIApplication()\n    app.collectionViews.buttons[\n      \"@Reading\"\n    ]\n    .tap()\n\n    app.buttons[\"A Up\"].tap()\n\n    XCTAssertTrue(app.staticTexts[\"A Value: 1\"].exists)\n    XCTAssertTrue(app.staticTexts[\"B Value: 1\"].exists)\n\n  }\n\n  func test_sync() {\n\n    let app = XCUIApplication()\n    app.collectionViews.buttons[\n      \"@Reading\"\n    ]\n    .tap()\n    app.buttons[\"A.1\"].tap()\n\n    app.buttons[\"A.1.a: 0\"].tap()\n\n    XCTAssertTrue(app.buttons[\"A.1.a: 1\"].exists)\n\n    app.buttons[\"B.1\"].tap()\n\n    XCTAssertTrue(app.buttons[\"B.1.a: 1\"].exists)\n    \n    app.buttons[\"B.1.a: 1\"].tap()\n    \n    XCTAssertTrue(app.buttons[\"A.1.a: 2\"].exists)\n    XCTAssertTrue(app.buttons[\"B.1.a: 2\"].exists)\n\n  }\n  \n  func test_binding_reading() {\n        \n    let app = XCUIApplication()\n    app.collectionViews/*@START_MENU_TOKEN@*/.buttons[\"Binding @Reading\"]/*[[\".cells.buttons[\\\"Binding @Reading\\\"]\",\".buttons[\\\"Binding @Reading\\\"]\"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()\n    app.buttons[\"Increment\"].tap()\n    \n    XCTAssertTrue(app.staticTexts[\"1\"].exists)\n    \n  }\n  \n  func test_binding_storeReader() {\n    \n    let app = XCUIApplication()\n    app.collectionViews.buttons[\"Binding StoreReader\"].tap()\n    app.buttons[\"Increment\"].tap()\n    \n    XCTAssertTrue(app.staticTexts[\"1\"].exists)\n    \n  }\n}\n"
  },
  {
    "path": "Development/Development/UITests/StoreReaderTests.swift",
    "content": "import XCTest\n\nfinal class StoreReaderTests: XCTestCase {\n  \n  var app: XCUIApplication!\n  \n  override func setUpWithError() throws {\n    continueAfterFailure = false\n    app = XCUIApplication()\n    app.launch()\n  }\n  \n  override func tearDownWithError() throws {\n    app = nil\n  }\n  \n  func testA_up() {\n    \n    let app = XCUIApplication()\n    app.collectionViews.buttons[\n      \"StoreReader\"\n    ]\n      .tap()\n    \n    app.buttons[\"A Up\"].tap()\n    \n    XCTAssertTrue(app.staticTexts[\"A Value: 1\"].exists)\n    XCTAssertTrue(app.staticTexts[\"B Value: 1\"].exists)\n    \n  }\n  \n  func test_sync() {\n    \n    let app = XCUIApplication()\n    app.collectionViews.buttons[\n      \"StoreReader\"\n    ]\n      .tap()\n    app.buttons[\"A.1\"].tap()\n    \n    app.buttons[\"A.1.a: 0\"].tap()\n    \n    XCTAssertTrue(app.buttons[\"A.1.a: 1\"].exists)\n    \n    app.buttons[\"B.1\"].tap()\n    \n    XCTAssertTrue(app.buttons[\"B.1.a: 1\"].exists)\n    \n    app.buttons[\"B.1.a: 1\"].tap()\n    \n    XCTAssertTrue(app.buttons[\"A.1.a: 2\"].exists)\n    XCTAssertTrue(app.buttons[\"B.1.a: 2\"].exists)\n    \n    \n  }\n}\n"
  },
  {
    "path": "Development/DevelopmentUITests/DevelopmentUITests.swift",
    "content": "//\n//  DevelopmentUITests.swift\n//  DevelopmentUITests\n//\n//  Created by Muukii on 2025/03/22.\n//\n\nimport XCTest\n\nfinal class DevelopmentUITests: XCTestCase {\n\n    override func setUpWithError() throws {\n        // Put setup code here. This method is called before the invocation of each test method in the class.\n\n        // In UI tests it is usually best to stop immediately when a failure occurs.\n        continueAfterFailure = false\n\n        // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.\n    }\n\n    override func tearDownWithError() throws {\n        // Put teardown code here. This method is called after the invocation of each test method in the class.\n    }\n\n    @MainActor\n    func testExample() throws {\n        // UI tests must launch the application that they test.\n        let app = XCUIApplication()\n        app.launch()\n\n        // Use XCTAssert and related functions to verify your tests produce the correct results.\n    }\n\n    @MainActor\n    func testLaunchPerformance() throws {\n        if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {\n            // This measures how long it takes to launch your application.\n            measure(metrics: [XCTApplicationLaunchMetric()]) {\n                XCUIApplication().launch()\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Development/DevelopmentUITests/DevelopmentUITestsLaunchTests.swift",
    "content": "//\n//  DevelopmentUITestsLaunchTests.swift\n//  DevelopmentUITests\n//\n//  Created by Muukii on 2025/03/22.\n//\n\nimport XCTest\n\nfinal class DevelopmentUITestsLaunchTests: XCTestCase {\n\n    override class var runsForEachTargetApplicationUIConfiguration: Bool {\n        true\n    }\n\n    override func setUpWithError() throws {\n        continueAfterFailure = false\n    }\n\n    @MainActor\n    func testLaunch() throws {\n        let app = XCUIApplication()\n        app.launch()\n\n        // Insert steps here to perform after app launch but before taking a screenshot,\n        // such as logging into a test account or navigating somewhere in the app\n\n        let attachment = XCTAttachment(screenshot: app.screenshot())\n        attachment.name = \"Launch Screen\"\n        attachment.lifetime = .keepAlways\n        add(attachment)\n    }\n}\n"
  },
  {
    "path": "Development/Project.swift",
    "content": "import ProjectDescription\n\nlet project = Project(\n  name: \"Development\",\n  targets: [\n    .target(\n      name: \"Development\",\n      destinations: .iOS,\n      product: .app,\n      bundleId: \"io.tuist.Development\",\n      infoPlist: .extendingDefault(\n        with: [\n          \"UILaunchScreen\": [\n            \"UIColorName\": \"\",\n            \"UIImageName\": \"\",\n          ]\n        ]\n      ),\n      sources: [\"Development/Sources/**\"],\n      resources: [\"Development/Resources/**\"],\n      dependencies: [\n        .external(name: \"Verge\")\n      ]\n    ),\n    .target(\n      name: \"DevelopmentUITests\",\n      destinations: .iOS,\n      product: .uiTests,\n      bundleId: \"io.tuist.DevelopmentUITests\",\n      infoPlist: .default,\n      sources: [\"Development/UITests/**\"],\n      resources: [],\n      dependencies: [.target(name: \"Development\")]\n    ),\n    .target(\n      name: \"DevelopmentTests\",\n      destinations: .iOS,\n      product: .unitTests,\n      bundleId: \"io.tuist.DevelopmentTests\",\n      infoPlist: .default,\n      sources: [\"Development/Tests/**\"],\n      resources: [],\n      dependencies: [.target(name: \"Development\")]\n    ),\n  ]\n)\n"
  },
  {
    "path": "Development/Tuist/Package.resolved",
    "content": "{\n  \"originHash\" : \"fb710b9bf77d01a2d48fc3e3b210bfb0e949769f26d1ca1c351ac86995dca6fb\",\n  \"pins\" : [\n    {\n      \"identity\" : \"normalization\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/Normalization\",\n      \"state\" : {\n        \"revision\" : \"6e7cb1ddeda4d0f1d2fbf8ca6d25ecd8ed6ba917\",\n        \"version\" : \"1.1.0\"\n      }\n    },\n    {\n      \"identity\" : \"rxswift\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/ReactiveX/RxSwift.git\",\n      \"state\" : {\n        \"revision\" : \"5dd1907d64f0d36f158f61a466bab75067224893\",\n        \"version\" : \"6.9.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-atomics\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/apple/swift-atomics.git\",\n      \"state\" : {\n        \"revision\" : \"cd142fd2f64be2100422d658e7411e39489da985\",\n        \"version\" : \"1.2.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-collections\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/apple/swift-collections\",\n      \"state\" : {\n        \"revision\" : \"671108c96644956dddcd89dd59c203dcdb36cec7\",\n        \"version\" : \"1.1.4\"\n      }\n    },\n    {\n      \"identity\" : \"swift-concurrency-task-manager\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/swift-concurrency-task-manager\",\n      \"state\" : {\n        \"revision\" : \"340cf14e0282977deeeb436605d1810ce4f4fbc9\",\n        \"version\" : \"1.4.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-macro-state-struct\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/swift-macro-state-struct\",\n      \"state\" : {\n        \"revision\" : \"b6ade33024ae04699fa6a4885be70c0299eb3cec\",\n        \"version\" : \"2.0.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-syntax\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/apple/swift-syntax.git\",\n      \"state\" : {\n        \"revision\" : \"0687f71944021d616d34d922343dcef086855920\",\n        \"version\" : \"600.0.1\"\n      }\n    },\n    {\n      \"identity\" : \"typedcomparator\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/TypedComparator\",\n      \"state\" : {\n        \"revision\" : \"337ce0e573e7637ddd29392cb88c3b852f042c8e\",\n        \"version\" : \"1.0.0\"\n      }\n    },\n    {\n      \"identity\" : \"typedidentifier\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/TypedIdentifier\",\n      \"state\" : {\n        \"revision\" : \"284340409ba47858a1b3c353dcef9c21303953db\",\n        \"version\" : \"2.0.3\"\n      }\n    }\n  ],\n  \"version\" : 3\n}\n"
  },
  {
    "path": "Development/Tuist/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\n#if TUIST\n  import struct ProjectDescription.PackageSettings\n\n  let packageSettings = PackageSettings(\n    // Customize the product types for specific package product\n    // Default is .staticFramework\n    // productTypes: [\"Alamofire\": .framework,]\n    productTypes: [:]\n  )\n#endif\n\nlet package = Package(\n  name: \"Development\",\n  dependencies: [\n    // Add your own dependencies here:\n    // .package(url: \"https://github.com/Alamofire/Alamofire\", from: \"5.0.0\"),\n    // You can read more about dependencies here: https://docs.tuist.io/documentation/tuist/dependencies\n    .package(path: \"../../\")\n  ]  \n)\n"
  },
  {
    "path": "Development/Tuist.swift",
    "content": "import ProjectDescription\n\nlet tuist = Tuist(project: .tuist())"
  },
  {
    "path": "Development/mise.toml",
    "content": "[tools]\ntuist = \"4.44.3\"\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017 muukii\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "Package.resolved",
    "content": "{\n  \"originHash\" : \"e0239f7d7b3b817d553cd88ff38b3bf2eaf6a4d2aa61a19fb57aed0c303e01eb\",\n  \"pins\" : [\n    {\n      \"identity\" : \"normalization\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/Normalization\",\n      \"state\" : {\n        \"revision\" : \"0d6adaadd3dcf2aa4c65db8edcf1ea94c73d4a10\",\n        \"version\" : \"2.0.0\"\n      }\n    },\n    {\n      \"identity\" : \"rxswift\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/ReactiveX/RxSwift.git\",\n      \"state\" : {\n        \"revision\" : \"5949cbd3d4f3f97968bb40b6cd232f8315c6341c\",\n        \"version\" : \"6.7.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-atomics\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/apple/swift-atomics.git\",\n      \"state\" : {\n        \"revision\" : \"cd142fd2f64be2100422d658e7411e39489da985\",\n        \"version\" : \"1.2.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-collections\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/apple/swift-collections\",\n      \"state\" : {\n        \"revision\" : \"94cf62b3ba8d4bed62680a282d4c25f9c63c2efb\",\n        \"version\" : \"1.1.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-concurrency-task-manager\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/swift-concurrency-task-manager\",\n      \"state\" : {\n        \"revision\" : \"87605b623fa1a02c657534251ae238a56bc0d15c\",\n        \"version\" : \"3.0.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-custom-dump\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/pointfreeco/swift-custom-dump\",\n      \"state\" : {\n        \"revision\" : \"82645ec760917961cfa08c9c0c7104a57a0fa4b1\",\n        \"version\" : \"1.3.3\"\n      }\n    },\n    {\n      \"identity\" : \"swift-macro-state-struct\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/swift-macro-state-struct\",\n      \"state\" : {\n        \"revision\" : \"aabd53cd8be48f71bb33e5fe66e38accc0438660\",\n        \"version\" : \"3.0.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-macro-testing\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/pointfreeco/swift-macro-testing.git\",\n      \"state\" : {\n        \"revision\" : \"9ab11325daa51c7c5c10fcf16c92bac906717c7e\",\n        \"version\" : \"0.6.4\"\n      }\n    },\n    {\n      \"identity\" : \"swift-snapshot-testing\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/pointfreeco/swift-snapshot-testing\",\n      \"state\" : {\n        \"revision\" : \"a8b7c5e0ed33d8ab8887d1654d9b59f2cbad529b\",\n        \"version\" : \"1.18.7\"\n      }\n    },\n    {\n      \"identity\" : \"swift-syntax\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"state\" : {\n        \"revision\" : \"4799286537280063c85a32f09884cfbca301b1a1\",\n        \"version\" : \"602.0.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-typed-identifier\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/swift-typed-identifier\",\n      \"state\" : {\n        \"revision\" : \"ea7afa2ce943c6bf3ef87d385c8a6e9f67fea4f3\",\n        \"version\" : \"2.0.4\"\n      }\n    },\n    {\n      \"identity\" : \"typedcomparator\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/TypedComparator\",\n      \"state\" : {\n        \"revision\" : \"337ce0e573e7637ddd29392cb88c3b852f042c8e\",\n        \"version\" : \"1.0.0\"\n      }\n    },\n    {\n      \"identity\" : \"viewinspector\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/nalexn/ViewInspector.git\",\n      \"state\" : {\n        \"revision\" : \"5acfa0a3c095ac9ad050abe51c60d1831e8321da\",\n        \"version\" : \"0.10.0\"\n      }\n    },\n    {\n      \"identity\" : \"xctest-dynamic-overlay\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/pointfreeco/xctest-dynamic-overlay\",\n      \"state\" : {\n        \"revision\" : \"b2ed9eabefe56202ee4939dd9fc46b6241c88317\",\n        \"version\" : \"1.6.1\"\n      }\n    }\n  ],\n  \"version\" : 3\n}\n"
  },
  {
    "path": "Package.swift",
    "content": "// swift-tools-version: 6.0\nimport CompilerPluginSupport\nimport PackageDescription\n\nlet package = Package(\n  name: \"Verge\",\n  platforms: [\n    .macOS(.v13),\n    .iOS(.v16),\n    .tvOS(.v13),\n    .watchOS(.v6),\n  ],\n  products: [\n    .library(name: \"Verge\", targets: [\"Verge\"]),\n    .library(name: \"VergeTiny\", targets: [\"VergeTiny\"]),\n    .library(name: \"VergeNormalizationDerived\", targets: [\"VergeNormalizationDerived\"]),\n    .library(name: \"VergeRx\", targets: [\"VergeRx\"]),\n    .library(name: \"VergeClassic\", targets: [\"VergeClassic\"]),\n    .library(name: \"VergeMacros\", targets: [\"VergeMacros\"]),\n  ],\n  dependencies: [\n    .package(url: \"https://github.com/ReactiveX/RxSwift.git\", from: \"6.0.0\"),\n    .package(url: \"https://github.com/apple/swift-atomics.git\", from: \"1.0.2\"),\n    .package(url: \"https://github.com/apple/swift-collections\", from: \"1.1.0\"),\n    .package(url: \"https://github.com/VergeGroup/swift-concurrency-task-manager\", from: \"3.0.0\"),\n    .package(url: \"https://github.com/VergeGroup/TypedComparator\", from: \"1.0.0\"),\n    .package(url: \"https://github.com/VergeGroup/Normalization\", from: \"2.0.0\"),\n    .package(url: \"https://github.com/VergeGroup/swift-macro-state-struct\", from: \"3.0.0\"),\n\n    /// for testing\n    .package(url: \"https://github.com/nalexn/ViewInspector.git\", from: \"0.10.0\"),\n    .package(url: \"https://github.com/swiftlang/swift-syntax.git\", \"600.0.0\"..<\"603.0.0\"),\n    .package(url: \"https://github.com/pointfreeco/swift-macro-testing.git\", from: \"0.2.1\")\n  ],\n  targets: [\n\n    // compiler plugin\n    .macro(\n      name: \"VergeMacrosPlugin\",\n      dependencies: [\n        .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n        .product(name: \"SwiftCompilerPlugin\", package: \"swift-syntax\"),\n      ]\n    ),\n\n    // macro exports\n    .target(name: \"VergeMacros\", dependencies: [\"VergeMacrosPlugin\"]),\n\n    .target(name: \"VergeTiny\", dependencies: []),\n    .target(\n      name: \"Verge\",\n      dependencies: [\n        \"VergeMacros\",\n        .product(name: \"StateStruct\", package: \"swift-macro-state-struct\"),\n        .product(name: \"TypedComparator\", package: \"TypedComparator\"),\n        .product(name: \"Atomics\", package: \"swift-atomics\"),\n        .product(name: \"DequeModule\", package: \"swift-collections\"),\n        .product(name: \"ConcurrencyTaskManager\", package: \"swift-concurrency-task-manager\"),\n      ]\n    ),\n    .target(\n      name: \"VergeClassic\",\n      dependencies: [\n        \"VergeRx\"\n      ]\n    ),\n    .target(\n      name: \"VergeNormalizationDerived\",\n      dependencies: [\n        \"Verge\",\n        .product(name: \"Normalization\", package: \"Normalization\"),\n        .product(name: \"HashTreeCollections\", package: \"swift-collections\"),\n      ]\n    ),\n    .target(\n      name: \"VergeRx\",\n      dependencies: [\n        \"Verge\",\n        .product(name: \"RxSwift\", package: \"RxSwift\"),\n        .product(name: \"RxCocoa\", package: \"RxSwift\"),\n      ]\n    ),\n    .testTarget(\n      name: \"VergeNormalizationDerivedTests\",\n      dependencies: [\"VergeNormalizationDerived\"]\n    ),\n    .testTarget(\n      name: \"VergeRxTests\",\n      dependencies: [\"VergeRx\", \"VergeClassic\"]\n    ),\n    .testTarget(\n      name: \"VergeTests\",\n      dependencies: [\"Verge\", \"ViewInspector\"],\n      swiftSettings: [\n        .enableExperimentalFeature(\"StrictConcurrency\")\n      ]\n    ),\n    .testTarget(\n      name: \"VergeTinyTests\",\n      dependencies: [\"VergeTiny\"]\n    ),\n    .testTarget(\n      name: \"VergeMacrosTests\",\n      dependencies: [\n        \"VergeMacrosPlugin\",\n        .product(name: \"SwiftSyntaxMacrosTestSupport\", package: \"swift-syntax\"),\n        .product(name: \"MacroTesting\", package: \"swift-macro-testing\"),\n      ]),\n  ],\n  swiftLanguageModes: [.v6]\n)\n"
  },
  {
    "path": "README.md",
    "content": "> [!WARNING]\n> Verge is stabilizing and transitioning to [swift-state-graph](https://github.com/VergeGroup/swift-state-graph) as its next-generation foundation.\n> Please check this out\n> https://medium.com/p/8c7423692992\n\n\n\n\n\n<p align=\"center\">\n  <a href=\"https://vergegroup.org\">\n<img width=\"128\" alt=\"VergeIcon\" src=\"https://user-images.githubusercontent.com/1888355/85241314-5ac19c80-b476-11ea-9be6-e04ed3bc6994.png\">\n    </a>\n</p>\n\n<h1 align=\"center\">Verge.swift</h1>\n<p align=\"center\">\n  <b>📍An effective state management architecture for iOS - UIKit, SwiftUI📍</b><br/>\n<sub>_ An easier way to get unidirectional data flow _</sub><br/>\n<sub>_ Supports concurrent processing _</sub><br/>\n</p>\n\n[My development note](https://www.notion.so/muukii/Verge-93813aec77d44bef802a2d92f565c7bb?pvs=4)\n\n## Using StoreReader or @Reading in SwiftUI\n\nIn SwiftUI, there are two ways to observe a Store: using the `StoreReader` view or the `@Reading` property wrapper. Both efficiently track state changes and only re-render the view when tracked values change.\n\nFirst, define your state with `@Tracking` macro:\n\n```swift\n@Tracking\nstruct State {\n  var count: Int = 0\n\n  @Tracking\n  struct NestedState {\n    var isActive: Bool = false\n    var message: String = \"Hello, Verge!\"\n  }\n\n  var nestedState: NestedState = NestedState()\n}\n```\n\n### StoreReader Example\n\n```swift\nstruct MyView: View {\n  let store = Store<State, Never>(initialState: .init())\n  \n  var body: some View {\n    StoreReader(store) { $state in\n      VStack {\n        Text(\"Count: \\(state.count)\")\n        Button(\"Increment\") {\n          store.commit {\n            $0.count += 1\n          }\n        }\n        Text(\"Is Active: \\(state.nestedState.isActive)\")\n        Text(\"Message: \\(state.nestedState.message)\")\n        Button(\"Toggle Active\") {\n          store.commit {\n            $0.nestedState.isActive.toggle()\n          }\n        }\n      }\n    }\n  }\n}\n```\n\n### @Reading Example\n\n```swift\nstruct MyView: View {\n  @Reading<Store<State, Never>> var state: State\n  \n  init() {\n    self._state = .init(\n      label: \"MyView\",\n      { Store<State, Never>(initialState: .init()) }\n    )\n  }\n  \n  var body: some View {\n    VStack {\n      Text(\"Count: \\(state.count)\")\n      Button(\"Increment\") {\n        $state.driver.commit {\n          $0.count += 1\n        }\n      }\n      Text(\"Is Active: \\(state.nestedState.isActive)\")\n      Text(\"Message: \\(state.nestedState.message)\")\n      Button(\"Toggle Active\") {\n        $state.driver.commit {\n          $0.nestedState.isActive.toggle()\n        }\n      }\n    }\n  }\n}\n```\n\n---\n\n- Dependencies\n  - [TypedIdentifier](https://github.com/VergeGroup/TypedIdentifier)\n  - [TypedComparator](https://github.com/VergeGroup/TypedComparator)\n  - [Normalization](https://github.com/VergeGroup/Normalization)\n\n- Docs\n  - [Verge](https://swiftpackageindex.com/VergeGroup/swift-Verge/main/documentation/verge)\n  - [VergeNormalizationDerived](https://swiftpackageindex.com/VergeGroup/swift-Verge/main/documentation/vergenormalizationderived)\n\n## Support this projects\n<a href=\"https://www.buymeacoffee.com/muukii\">\n<img width=\"160\" alt=\"yellow-button\" src=\"https://user-images.githubusercontent.com/1888355/146226808-eb2e9ee0-c6bd-44a2-a330-3bbc8a6244cf.png\">\n</a>\n\n# Verge: A High-Performance, Scalable State Management Library for SwiftUI and UIKit\n\nVerge is a high-performance, scalable state management library for Swift, designed with real-world use cases in mind. It offers a lightweight and easy-to-use approach to managing your application state without the need for complex actions and reducers. This guide will walk you through the basics of using Verge in your Swift projects.\n\n## Key Concepts and Motivations\n\nVerge was designed with the following concepts in mind:\n\n- Inspired by the Flux library, but with a focus on providing a store-pattern as the core concept.\n- The store-pattern is a primitive concept found in Flux and Redux, focusing on sharing state between components using a single source of truth.\n- Verge does not dictate how to manage actions to modify the state. Instead, it provides a simple `commit` function that accepts a closure describing how to change the state.\n- Users can build additional layers on top of Verge, such as implementing enum-based actions for more structured state management.\n- Verge supports multi-threading, ensuring fast, safe, and efficient operation.\n- Compatible with both UIKit and SwiftUI.\n- Includes APIs for handling real-world application development use cases, such as managing asynchronous operations.\n- Addresses the complexity of updating state in large and complex applications.\n- Provides an ORM for efficient management of a large number of entities.\n- Designed for use in business-focused applications.\n\n## Getting Started\n\nTo use Verge, follow these steps:\n\n1. Define a state struct with `@Tracking` macro\n2. Instantiate a `Store` with your initial state\n3. Update the state using the `commit` method on the store instance\n4. Subscribe to state updates using the `sinkState` method\n\n\n## Defining Your State\n\nCreate a state struct that represents the state of your application. Use the `@Tracking` macro to make your state trackable by Verge. This allows Verge to detect changes in your state and trigger updates as necessary.\n\n```swift\n@Tracking\nstruct MyState {\n  var count: Int = 0 \n}\n```\n\n## Instantiating a Store\n\nCreate a `Store` instance with the initial state of your application. The `Store` class takes two type parameters:\n\n- The first type parameter represents the state of your application.\n- The second type parameter represents any activity you want to use with your store. If you don't need any activity, use `Never`.\n\n```swift\nlet store = Store<_, Never>(initialState: MyState())\n```\n\n## Updating the State\n\nTo update your application state, use the `commit` method on your `Store` instance. The `commit` method takes a closure with a single parameter, which is a mutable reference to your state. Inside the closure, modify the state as needed.\n\n```swift\nstore.commit {   \n  $0.count += 1 \n}\n```\n\n## Subscribing to State Updates\n\nTo receive updates when the state changes, use the `sinkState` method on your `Store` instance. This method takes a closure that receives the updated state as its parameter. The closure will be called whenever the state changes.\n\n```swift\nstore.sinkState { state in\n  // Receives updates of the state\n}\n.storeWhileSourceActive()\n```\n\nThe `storeWhileSourceActive()` call at the end is a method provided by Verge to automatically manage the lifetime of the subscription. It retains the subscription as long as the source (in this case, the `store` instance) is alive.\n\n## Using Activity of Store for Event-Driven Programming\n\nIn certain scenarios, event-driven programming is essential for creating responsive and efficient applications. The Verge library's Activity of Store feature is designed to cater to this need, allowing developers to handle events seamlessly within their projects.\n\nThe Activity of Store comes into play when your application requires event-driven programming. It enables you to manage events and associated logic independently from the main store management, promoting a clean and organized code structure. This separation of concerns simplifies the overall development process and makes it easier to maintain and extend your application over time.\n\nBy leveraging the Activity of Store functionality, you can efficiently handle events within your application while keeping the store management intact. This ensures that your application remains performant and scalable, enabling you to build robust and reliable Swift applications using the Verge library.\n\nHere's an example of using Activity of Store:\n\n```swift\nlet store: Store<MyState, MyActivity>\n\nstore.send(MyActivity.somethingHappened)\n```\n\n```swift\nstore.sinkActivity { (activity: MyActivity) in\n  // handle activities.\n}\n.storeWhileSourceActive()\n```\n\n## Using Verge with SwiftUI\n\nTo use Verge in SwiftUI, you can utilize the `StoreReader` to subscribe to state updates within your SwiftUI views. Here's an example of how to do this:\n\n```swift\nimport SwiftUI\nimport Verge\n\nstruct ContentView: View {\n  @StoreObject private var viewModel = CounterViewModel()\n\n  var body: some View {\n    VStack {\n      StoreReader(viewModel) { state in\n        Text(\"Count: \\(state.count)\")\n          .font(.largeTitle)\n      }\n\n      Button(action: {\n        viewModel.increment()\n      }) {\n        Text(\"Increment\")\n      }\n    }\n  }\n}\n\nfinal class CounterViewModel: StoreComponentType {\n  @Tracking\n  struct State {\n    var count: Int = 0\n  }\n\n  let store: Store<State, Never> = .init(initialState: .init())\n\n  func increment() {\n    commit {\n      $0.count += 1\n    }\n  }\n}\n```\n\nIn this example, `StoreReader` is used to read the state from the `MyViewModel` store. This allows you to access and display the state within your SwiftUI view. Additionally, you can perform actions by calling methods on the store directly, as demonstrated with the button in the example.\n\nThis new section will help users understand how to use Verge with SwiftUI, allowing them to manage state effectively within their SwiftUI views. Let me know if you have any further suggestions or changes!\n\n**StoreObject** property wrapper:\n\nSwiftUI provides the `@StateObject` property wrapper to create and manage a persistent instance of a given object that adheres to the ObservableObject protocol. However, StateObject will cause the view to be refreshed whenever the ObservableObject is updated.\n\nIn Verge, we introduce the StoreObject property wrapper, which instantiates a Store object for the duration of the view's lifecycle but does not cause the view to refresh when the Store updates.\n\nThis is beneficial when you want to manage the Store in a more granular way, without causing the entire view to refresh when the Store changes. Instead, Store updates can be handled through the StoreReader.\n\n## Using Verge with UIKit\n\nHere's a simple usage example of Verge with a UIViewController:\n\n```swift\nclass MyViewController: UIViewController {\n  \n  @Tracking\n  private struct State {\n    var count: Int = 0\n  }\n  \n  private let store: Store<State, Never> = .init(initialState: .init())\n  \n  private let label: UILabel = .init()\n  \n  override func viewDidLoad() {\n    super.viewDidLoad()\n    \n    setupUI()\n    \n    // Subscribe to the store's state updates\n    store.sinkState { [weak self] state in\n      guard let self = self else { return }\n      \n      // Check if the value has been updated using ifChanged\n      state.ifChanged(\\.count) { count in\n        self.label.text = \"Count: \\(count)\"\n      }\n    }\n    .storeWhileSourceActive()\n  }\n  \n  private func setupUI() {\n    // Omitted for brevity\n  }\n  \n  private func incrementCount() {\n    store.commit {\n      $0.count += 1\n    }\n  }\n}\n```\n\n## Efficient State Updates in UIKit using `sinkState`, `Changed<State>`, and `ifChanged`\n\nIn UIKit, which is event-driven, it's crucial to update components efficiently by only updating them as needed. The Verge library provides a way to achieve this using the `sinkState` method, the `Changed<State>` type, and the `ifChanged` method.\n\nWhen you use the `sinkState` method, the closure you provide receives the latest state wrapped in a `Changed<State>` type. This wrapper also includes the previous state, allowing you to determine which properties have been updated using the `ifChanged` method.\n\nHere's an example of using `sinkState` and `ifChanged` in UIKit to efficiently update components:\n\n```swift\nstore.sinkState {\n  $0.ifChanged(\\.myProperty) { newValue in\n    // Update the component only when myProperty has changed\n  }\n}\n```\n\nIn this example, the component is updated only when `myProperty` has changed, ensuring efficient updates in the UIKit-based application.\n\nCompared to UIKit, SwiftUI works with a declarative view structure, which means that there is less need to check for state changes to update the view. However, when working with UIKit, using `sinkState`, `Changed<State>`, and `ifChanged` helps maintain a performant and responsive application.\n\n## Using TaskManager for Asynchronous Operations\n\nVerge's Store includes a TaskManager that allows you to dispatch and manage asynchronous operations. This feature simplifies handling async tasks while keeping them associated with your Store.\n\n### Basic usage\n\nTo use TaskManager, simply call the `task` method on your Store instance, and provide a closure that contains the asynchronous operation:\n\n```swift\nstore.task {\n  await runMyOperation()\n}\n```\n\n### Task management with keys and modes\n\nTaskManager also enables you to manage tasks based on keys and modes. You can assign a unique key to each task and specify a mode for its execution. This allows you to control the execution behavior of tasks based on their keys.\n\nFor example, you can use the `.dropCurrent` mode to drop any currently running tasks with the same key and run the new task immediately:\n\n```swift\nstore.task(key: .init(\"MyOperation\"), mode: .dropCurrent) {\n  //\n}\n```\n\nThis functionality provides you with fine-grained control over how tasks are executed, ensuring that your application remains responsive and efficient, even when handling multiple asynchronous operations.\n\n## Advanced Usage: Managing Multiple Stores for Complex Applications\n\nIn theory, managing your entire application state in a single store is ideal. However, in large and complex applications, the computational complexity can become significant, leading to performance issues and slow application responsiveness. In such cases, it's recommended to separate your state into multiple stores and integrate them as needed.\n\nBy dividing your state into multiple stores, you can reduce the complexity and overhead associated with state updates. Each store can manage a specific part of your application state, ensuring that updates are performed efficiently and quickly. This approach also promotes better organization and separation of concerns in your code, making it easier to maintain and extend your application over time.\n\nTo use multiple stores, create separate Store instances for different parts of your application state, and then connect them as needed. This may involve passing store instances to child components or sharing stores between sibling components. By structuring your application this way, you can ensure that each part of your application state is managed efficiently and effectively.\n\n### Copying State Between Stores\n\nTo copy state between stores, you can use the `sinkState` method along with the `ifChanged` function to only trigger updates when the state has changed. Here's an example:\n\n```swift\nstore.sinkState {\n  $0.ifChanged(\\.myState) { value in\n    otherStore.commit {\n      $0.myState = value\n    }\n  }\n}\n```\n\nIn this example, when the state of `myState` changes in `store`, the new value is committed to `otherStore`. This approach allows you to synchronize state between multiple stores efficiently.\n\n## Using Derived for Efficient Computed Properties\n\nVerge's `Derived` feature allows you to create computed properties based on your store's state and efficiently subscribe to updates. This feature can help you optimize your application by reducing unnecessary computations and updates. Derived is inspired by the [reselect](https://github.com/reduxjs/reselect) library and provides similar functionality.\n\n### Creating a Derived Property\n\nTo create a derived property, you'll use the `store.derived` method. This method takes a `Pipeline` object that describes how the derived data is generated:\n\n```swift\nlet derived: Derived<Int> = store.derived(.select(\\\\.count))\n```\n\nYou can use `select` or `map` to generate derived data. `select` is used to take a value directly from the state, while `map` can be used to generate new values based on the state, similar to a map function:\n\n```swift\nlet derived: Derived<Int> = store.derived(.map { $0.count * 2 })\n```\n\nThe `Pipeline` checks if the derived data has been updated from the previous value. If it hasn't changed, `Derived` won't publish any changes.\n\n### Chaining Derived Instances\n\nYou can create another Derived instance from an existing Derived instance, effectively chaining them together:\n\n```swift\nlet anotherDerived: Derived<String> = derived.derived(.map { $0.description })\n```\n\n### Subscribing to Derived Property Updates\n\nTo subscribe to updates of a derived property, you can use the `sinkState` method, just like with a store:\n\n```swift\nderived.sinkState { value in \n  // Handle updates of the derived property \n} \n.storeWhileSourceActive()\n```\n\nBy using `Derived` for computed properties and subscribing to updates, you can ensure that your application remains efficient and performant, avoiding unnecessary computations and state updates.\n\n# Normalization\n\nVergeGroup and Verge package provide a library for normalization techniques to handle entities in an efficient way.  \n[Normalization](https://github.com/VergeGroup/Normalization) is a library that makes tables in a struct and manages value-type entities in copy-efficient tables.  \nIt can be used in the same way as handling value types. Which means we can use it with Verge bringing them into store-pattern.  \n`VergeNormalizationDerived` target provides functionalities for subscribing entity updates when it's using with Verge.\n\n# Installation\n\n## SwiftPM\n\nVerge supports SwiftPM.\n\n## Thanks\n\n- [Redux](https://redux.js.org/)\n- [Vuex](https://vuex.vuejs.org/)\n- [ReSwift](https://github.com/ReSwift/ReSwift)\n- [swift-composable-architecture](https://github.com/pointfreeco/swift-composable-architecture)\n\n## Author\n\n[🇯🇵 Muukii (Hiroshi Kimura)](https://github.com/muukii)\n\n## License\n\nVerge is released under the MIT license.\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Activity.md",
    "content": "# Activity\n\n## What Activity brings to us\n\nActivity enables Event-driven partially.\n\nVerge supports to send any events that won’t be stored persistently. Even if an application runs with State-Driven, it might have some issues that not easy to something with State-Driven.\n\nFor example, something that would happen with the timer’s trigger. It’s probably not easy to expressing that as a state.\nIn this case, Activity helps that can do easily.\n\nThis means Verge can use Event-Driven from Data-Driven partially.\nWe think it’s not so special concept. SwiftUI supports these use cases as well that using Combine’s Publisher.\n\n```swift\nfunc onReceive<P>(_ publisher: P, perform action: @escaping (P.Output) -> Void) -> some View where P : Publisher, P.Failure == Never\n```\n\n[Apple’s SwiftUI Ref](https://developer.apple.com/documentation/swiftui/view/3365935-onreceive)\n\n## Add Activity to the Store\n\nIn sample code following this:\n\n```swift\nfinal class MyStore: StoreComponentType {\n\n  struct State {\n    ...\n  }\n\n}\n```\n\nTo enable using Activity, we add new decralation just like this:\n\n```swift\nfinal class MyStore: StoreComponentType {\n\n  struct State {\n    ...\n  }\n\n  /// 👇\n  enum Activity {\n    case didSendMessage\n  }\n\n}\n```\n\n## Send an Activity\n\nAnd finally, that Store now can emit an activity that we created.\n\n```swift\nextension MyStore {\n  func sendMessage() {\n    send(.didSendMessage)\n  }\n}\n```\n\n---\n\n## Subscribe the Activity\n\n**Normal**\n\n```swift\nstore.sinkActivity { activity in\n  ...\n}\n.store(in: &subscriptions)\n```\n\n**Using Combine**\n\n```swift\nstore\n  .activityPublisher\n  .sink { event in\n    // do something\n  }\n  .store(in: &subscriptions)\n```\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Changes.md",
    "content": "# ``Verge/Changes``\n\n`Changes<State>` wraps primitive value inside and previous one.\nThis data structure enables to get differences between now one and previous one.\nIt helps us to prevent duplicated operation with the same value from the state.\n\n![Changes structure](changes)\n\n## How we update UI with the state uniquely in UIKit\n\nIn subscribing the state and binding UI, it’s most important to reduce the meaningless time to update UI.\nWhat things are the meaningless? that is the update UI operations which contains no updates.\nBasically, we can prevent this with like followings:\n\n```swift\nfunc updateUI(newState: State) {\n  if self.label.text != newState.name {\n    self.label.text = newState.name\n  }\n}\n```\n\nAlthough, this approach make the code a little bit complicated by increasing the code that updates UI.\nEspecially, same words come up a lot.\n\n## Changes simplify the code\n\nActually, state property of Store returns `Changes<State>` implicitly.\nFrom the power of `dynamicMemberLookup`, we can use the property of the State with we don’t know that is actually Changes object.\n\nHow to know there is differences is using `ifChanged`.\n\n```swift\nlet store: MyStore\nlet state: Changes<MyState> = store.state\n\nstate.ifChanged(\\.name) { name in\n  // called when `name` changed only\n}\n```\n\n## Patterns of `ifChanged`\n\n`ifChanged` has a bunch of overloads.\nLet’s take a look of patterns.\n\n```swift\nstate.ifChanged(\\.aaa, \\.bbb) { aaa, bbb in\n  // Executes every two properties change.\n}\n```\n\n```swift\nstate.ifChanged({ \"Mr.\" + $0.name }) { composedName in\n\n}\n```\n\n```swift\nstate.ifChanged({ \"Mr.\" + $0.name }, { $0 == $1 }) { aaa, bbb in\n\n}\n```\n\n```swift\nstate.ifChanged({ ($0.aaa, $0.bbb, \"Mr\" + $0.name)}, ==) { composedName in\n  // Returning tuple that contains composed value enables to do anything with the value you want.\n  // It releases us from complicated streaming mixing.\n  // Current Swift version does not support tuple conforming with Equatable,\n  // You need passing `==` function in the second argument.\n}\n```\n\n## Subscribing the state\n\n```swift\nclass ViewController: UIViewController {\n\n  var subscriptions = Set<UntilDeinitCancellable>()\n\n  let store: MyStore\n\n  override func viewDidLoad() {\n\n    super.viewDidLoad()\n\n    store.sinkChanges { [weak self] (changes) in\n      // it will be called on the thread which committed\n      self?.update(changes: changes)\n    }\n    .store(in: &subscriptions)\n  }\n\n  private func update(changes: Changes<MyState> {\n    changes.ifChanged(\\.name) { name in\n      // called only name changed\n    }\n    ...\n  }\n\n}\n```\n\n## Make Changes object the first-time value\n\nIf you have a `Changes` from anywhere, it might have previous value,\nUsing `ifChanged` might return false because compared with the previous one.\nYou can create the Changed object that always returns true from `ifChanged` with followings:\n\n```swift\nlet changes: Changes<State>\n\nlet firstTimeChanges: Changes<State> = changes.droppedPrevious()\n```#  <#Title#>\n\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/ComputedProperty.md",
    "content": "# Computed Property\n\n## Overview\n\nA declaration to add a computed-property into the state. It helps to add a property that does not need to be stored-property. It’s like Swift’s computed property like following:\n\n```swift\nstruct State {\n var items: [Item] = [] {\n\n var itemsCount: Int {\n   items.count\n }\n}\n```\n\nHowever, this Swift’s computed-property will compute the value every state changed. It might become a serious issue on performance.\n\nCompared with Swift’s computed property and this, this does not compute the value every state changes, It does compute depend on specified rules. That rules mainly come from the concept of Memoization.\n\nExample code:\n\n```swift\nstruct State: ExtendedStateType {\n\n var name: String = ...\n var items: [Int] = []\n\n struct Extended: ExtendedType {\n\n   static let instance = Extended()\n\n   let filteredArray = Field.Computed<[Int]> {\n     $0.items.filter { $0 > 300 }\n   }\n   .dropsInput {\n     $0.noChanges(\\.items)\n   }\n }\n}\n```\n\n```swift\nlet store: MyStore<State, Never> = ...\n\nlet state = store.state\n\nlet result: [Int] = state.computed.filteredArray\n```\n\n## Instructions\n\n### Computed Property on State\n\nStates may have a property that actually does not need to be stored property. In that case, we can use computed property.\n\nAlthough, we should take care of the cost of the computing to return value in that. What is that case? Followings explains that.\n\n<aside>\n💡 Computed concept is inspired from Vuex Getters. [https://vuex.vuejs.org/guide/getters.html](https://vuex.vuejs.org/guide/getters.html)\n\n</aside>\n\nFor example, there is itemsCount.\n\n```swift\nstruct State {\n  var items: [Item] = []\n\n  var itemsCount: Int = 0\n}\n```\n\nIn order to become itemsCount dynamic value, it needs to be updated with updating items like this.\n\n```swift\nstruct State {\n  var items: [Item] = [] {\n    didSet {\n      itemsCount = items.count\n    }\n  }\n\n  var itemsCount: Int = 0\n}\n```\n\nWe got it, but we don’t think it’s pretty simple. Actually we can do this like this.\n\n```swift\nstruct State {\n  var items: [Item] = [] {\n\n  var itemsCount: Int {\n    items.count\n  }\n}\n```\n\nWith this, it did get to be more simple.\n\n```swift\nstruct State {\n  var items: [Item] = []\n\n  var processedItems: [ProcessedItem] {\n    items.map { $0.doSomeExpensiveProcessing() }\n  }\n}\n```\n\nAs an example, Item can be processed with the something operation that takes expensive cost. We can replace this example with filter function.\n\nThis code looks is very simple and it has got data from source of truth. Every time we can get correct data. However we can look this takes a lot of the computing resources. In this case, it would be better to use didSet and update data.\n\n```swift\nstruct State {\n  var items: [Item] = [] {\n    didSet {\n      processedItems = items.map { $0.doSomeExpensiveProcessing() }\n    }\n  }\n\n  var processedItems: [ProcessedItem] = []\n}\n```\n\nHowever, as we said, this approach is not simple. And this can not handle easily a case that combining from multiple stored property. Next introduces one of the solutions.\n\n## Extended Computed Properties\n\nVergeStore has a way of providing computed property with caching to reduce taking computing resource.\n\nKeywords are:\n\n- `ExtendedStateType`\n- `ExtendedType`\n- `Field.Computed<T>`\n\nAbove State code can be improved like following.\n\n```swift\nstruct State: ExtendedStateType {\n\n  var name: String = ...\n  var items: [Int] = []\n\n  struct Extended: ExtendedType {\n\n    static let instance = Extended()\n\n    let filteredArray = Field.Computed<[Int]> {\n      $0.items.filter { $0 > 300 }\n    }\n    .dropsInput {\n      $0.noChanges(\\.items)\n    }\n  }\n}\n```\n\nTo access that computed property, we can do the followings:\n\n```swift\nlet store: MyStore<State, Never> = ...\n\nlet state = store.state\n\nlet result: [Int] = state.computed.filteredArray\n```\n\n`store.computed.filteredArray` will be updated only when items updated. Since the results are stored as a cache, we can take value without computing.\n\nFollowings are the steps describes when it computes while paying the cost.\n\n```swift\nlet store: MyStore<State, Never> = ...\n\n// It computes\nstore.state.computed.filteredArray\n\n// no computes because results cached with first-time access\nstore.state.computed.filteredArray\n\n// State will change but no affects items\nstore.commit {\n  $0.name = \"Muukii\"\n}\n\n// no computes because results cached with first-time access\nstore.state.computed.filteredArray\n\n// State will change with it affects items\nstore.commit {\n  $0.items.append(...)\n}\n\n// It computes new value\nstore.state.computed.filteredArray\n```#  <#Title#>\n\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Derived.md",
    "content": "#  ``Verge/Derived``\n\nDerived’s functions are:\n\n- Computes the derived data from the state tree\n- Emit the updated data with updating Store\n- Supports subscribe the data\n- Supports Memoization\n- Compatible with SwiftUI’s observableObject and `StateReader`\n\n## Overview\n\n### Create a Derived object from the Store\n\n**Select a tree from the state**\n\n```swift\nlet derived: Derived<Int> = store.derived(.map(\\.count))\n```\n\n```swift\n// we can write also this.\n// However, we recommend do above way as possible\n// because it enables cache.\nlet derived: Derived<Int> = store.derived(.map { $0.count })\n```\n\n**Technically, above method callings are produced from below declaration.**\n\n```swift\nextension StoreType {\n\n  public func derived<NewState>(\n    _ memoizeMap: MemoizeMap<Changes<State>, NewState>, \n    dropsOutput: ((Changes<NewState>) -> Bool)? = nil,\n    queue: TargetQueue? = nil\n  ) -> Derived<NewState>\n\n}\n```\n\n`MemoizeMap` manages to transform value from the state and keep performance that way of drops transform operations if the input value no changes.\n\n**Compute a value from the state**\n\nDerived can create any type of value what we need. MemoizeMap\n\n```swift\nlet derived = store.derived(\n  .map(derive: { ($0.name, $0.age) },\n  dropsDerived: ==\n) { args in\n\n  let (name, age) = args\n  ...\n  return ...\n\n})\n```\n\n<aside>\n💡 This method is quite optimized the performance If you create a Derived object that computes a new shape value that using multiple values from the state.\nBecause Derived object uses the specified derived value to create a new shape value, It can detect no need to compute that value if the input derived value not changed.\n\n</aside>\n\n**Most manually way of creating a Derived object**\n\nWe can create fully tuned up Derived object with using custom initialized `MemoizedMap`. Most of the cases, we don’t need to do this. Because several overloaded methods enable optimizations automatically that depending on doing things. Verge shows current optimization status from the Complexity column of Xcode documentation.\n\n![https://user-images.githubusercontent.com/1888355/83332811-41df2480-a2d8-11ea-8da0-d86c127fc926.png](https://user-images.githubusercontent.com/1888355/83332811-41df2480-a2d8-11ea-8da0-d86c127fc926.png)\n\n## Take a value\n\nDerived is an object (reference type). It provides a latest value from a store. This supports getting the value ad-hoc or subscribing the value updating.\n\nDerived allows us to take the latest value at the time.\n\n```\nlet value: Changes<Int> = derived.value\n```\n\n## Subscribe the latest value Derived provides\n\nDerived allows us to subscribe to the updated value.\n\n```swift\nlet cancellable = derived.sinkValue { (changes: Changes<Int>) in\n}\n```\n\nPlease, carefully handle a cancellable object.\nA concealable object that returns that subscribe method is similar to AnyCancellable of Combine.framework.\nWe need to retain that until we don’t need to get the update event.\n\n## Supports other Reactive Frameworks\n\nWe might need to use some Reactive framework to integrate other sequence. Derived allows us to make to a sequence from itself. Currently, it supports Combine.framework and RxSwift.framework.\n\n### + Combine\n\n```swift\nderived\n  .valuePublisher()\n  .sink { (changes: Changes<Int>) in\n\n  }\n```\n\n### + RxSwift\n\n💡You need to install VergeRx module to use this.\n\n```swift\nderived.rx\n  .changesObservable()\n  .subscribe(onNext: { (changes: Changes<Int>) in\n\n  })\n```\n\n## Memoization to keep good performance\n\nMostly Derived is used for projecting the specified shape from the source object. And some cases may contain an expensive operation. In that case, we can consider to tune Memoization up. We can see the detail of Memoization from below link.\n\n[Wiki - Memoization](https://en.wikipedia.org/wiki/Memoization)\n\n## Skips the map operation if the source state has no changes\n\nIn create Derived method, we can get the detail that how we suppress the no need updating and updated event.\n\n```swift\nextension StoreType {\n\n  public func derived<NewState>(\n    _ memoizeMap: MemoizeMap<Changes<State>, NewState>,\n    dropsOutput: @escaping (Changes<NewState>) -> Bool = { _ in false }\n  ) -> Derived<NewState>\n\n}\n```\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Dispatcher.md",
    "content": "# ``Verge/DispatcherType``\n\nDispatcher allows us to update the state of the Store from away the store and to manage dependencies to create Mutation.\n\n- Dispatcher is\n    - it is an object.\n    - it does not have its own state.\n    - it can run commit with specified store’s state.\n    - it can have a temporary dependency to commit the mutation.\n    - it can focus on specified tree of the state.\n\nHere is an example store, in this section we create a dispatcher to commit the mutation into this Store:\n\n```swift\nstruct State: StateType {\n  var count: Int = 0\n}\n\nenum Activity {\n  case happen\n}\n\nfinal class MyStore: Store<State, Activity> {\n  ...\n}\n```\n\nMyStore has a typealias to define a dispatcher:\n\n```swift\nMyStore.Dispatcher\n```\n\n<aside>\n💡 Actual type of `MyStore.Dispatcher` is `DispatcherBase<State, Never>` It is a typealias to write shortly.\n\n</aside>\n\n## Define a dispatcher\n\nLet’s take a look how we create a dispatcher with using the typealias:\n\n```swift\nfinal class MyDispatcher: MyStore.Dispatcher {\n\n}\n```\n\nNow we can create an instance of `MyDispatcher`:\n\n```swift\nlet store = MyStore()\nlet dispatcher = MyDispatcher(targetStore: store)\n```\n\n## Add an action to the dispatcher\n\nNext, we add an action that commits a mutation:\n\n```swift\nfinal class MyDispatcher: MyStore.Dispatcher {\n  func doSomething() {\n    commit {\n      $0.count = 100\n    }\n  }\n}\n```\n\n```swift\nlet store: MyStore\nlet dispatcher: MyDispatcher\n\ndispatcher.doSomething()\n\nstore.state.count == 100 // true\n```\n\n## Add a dependency to dispatch an action\n\nIn the case of large applications, we need to handle many dependencies to run the application.\nFor example, if we use multiple HTTP clients.\n\n```swift\nfinal class MyDispatcher: MyStore.Dispatcher {\n\n  let apiClient: APIClient\n\n  init(apiClient: APIClient, targetStore: Store<RootState>) {\n    self.apiClient = apiClient\n    super.init(targetStore: targetStore)\n  }\n\n  // an example of fetching data and commit\n  func fetchData() {\n    apiClient.fetchData { [weak self] result in\n      switch result {\n      case .success(let data):\n        let items = data.encode(...)\n        self?.commit {\n          $0.fetchedItems = items\n        }\n      case .failure(let error):\n      // handles error\n      }\n    }\n  }\n}\n```\n\nTo use this:\n\n```swift\nlet store = MyStore()\nlet apiClient = APIClient()\nlet dispatcher = MyDispatcher(apiClient: apiClient, target: store)\n\ndispatcher.fetchData()\n```\n\nNow we can handle multiple kinds of dependencies each it fits itself life-time.\nFor example, if you have a restriction that some dependencies can be created only the user’s logging-in, you can create a dispatcher what is for.\n\nNext section explains the detail.\n\n## Create multiple Dispatcher\n\n![https://user-images.githubusercontent.com/1888355/82821486-28586a00-9edf-11ea-8c98-062eafcc4f16.png](https://user-images.githubusercontent.com/1888355/82821486-28586a00-9edf-11ea-8c98-062eafcc4f16.png)\n\nCreating a dispatcher does not have the restriction of the number of instances or types.\nThis means that it allows us to define a dispatcher and instantiate an instance of the dispatcher to fill the use-case.\n\nFor example, In case the timing of getting dependencies that to be needed by run Action or Mutation is different, it’s not easy to have them in the one dispatcher with type-safety. they must be optional types.\n\nUsing creating multiple dispatchers techniques solves this case by defines the dispatcher each the timing of getting dependencies.\n\n```swift\nclass LoggedInDispatcher: MyStore.Dispatcher {\n\n  let apiClientNeedsAuthToken: APIClient = ...\n  ...\n}\n\nclass LoggedOutDispatcher: MyStore.Dispatcher {\n\n  let apiClientWithoutAuthToken: APIClient = ...\n  ...\n}\n```\n\n```swift\nlet store = MyStore()\nlet loggedInDispatcher = LoggedInDispatcher(...)\nlet loggedOutDispatcher = LoggedOutDispatcher(...)\n```\n\nThe application will create `LoggedInDispatcher` when the user is logged-in and deinitialize `LoggedOutDispatcher`.\n\n## Create scoped dispatcher\n\nAs another feature what Dispatcher provides, It supports to commit specified scope of the state which helps to mutate with focus on a part of the large state tree.\n\nHere is a sample state that assuming a large app.\n\n- AppState (MyStore)\n    - db: Database\n    - loggedIn: LoggedInState\n        - myInfo: MyInfoState\n    - loggedOut: LoggedOutState\n\nWe have `database`, `logged-in` and `logged-out state`. `database` means normalized state shape to manage many entities.\n\nIn previous section, that explained we can multiple dispatchers each the user’s state.\nHowever, it needs to the full path to mutate where we need to mutate.\n\n```swift\nclass LoggedInDispatcher: MyStore.Dispatcher {\n\n  func performA() {\n    commit {\n      $0.loggedIn.xxx\n    }\n  }\n\n  func performB() {\n    commit {\n      $0.loggedIn.xxx\n    }\n  }\n\n  func performC() {\n    commit {\n      $0.loggedIn.xxx\n    }\n  }\n}\n```\n\nLoggedInDispatcher will often dispatch some action for logged-in-state.\nBut it calls everytime `$0.loggedIn`, it seems a little bit verbosity.\n\nThat will be solved by `ScopedDispatcher`. It will move on target tree of the state when it dispatch the action.\n\nThe following code shows how we could create a `ScopedDispatcher`:\n\n```swift\nfinal class LoggedInService: MyStore.ScopedDispatcher<LoggedInState> {\n\n  init(store: Store) {\n    super.init(targetStore: store, scope: \\.loggedIn)\n  }\n\n  func someOperation() {\n    commit { (state: LoggedInState) in\n      ...\n    }\n  }\n}\n```\n\nIn LoggedInService, commit mutates `LoggedInState` directly. Like this, we can create a dispatcher each use-cases.\n\n### Detaching to other tree\n\nJust in case, `ScopedDispatcher` supports also mutating on other state tree.\n\n**Moving on more deeper**\n\n```swift\nfinal class LoggedInService: MyStore.ScopedDispatcher<LoggedInState> {\n\n  func detachingOperation() {\n    let myInfo = detached(by: \\.myInfo)\n    myInfo.commit { (state: MyInfo) in\n\n    }\n  }\n}\n```\n\n**Detaches from root**\n\n```swift\nfinal class LoggedInService: MyStore.ScopedDispatcher<LoggedInState> {\n\n  func detachingOperation() {\n    let db = detached(from: \\.db)\n    db.commit { (state: Database) in\n\n    }\n  }\n}\n```\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Essentials/Motivation.md",
    "content": "# Motivation\n\n## Verge focuses use-cases in the real-world\n\nRecently, we could say the unidirectional data flow is a popular architecture such as flux.\n\n## Does flux architecture have a good performance?\n\nIt depends. The performance will be the worst depends on how it is used.\n\nHowever, most of the cases, we don't know the app we're creating how it will grow and scales.While the application is scaling up, the performance might decrease by getting complexity.To keep performance, we need to tune it up with several approaches.Considering the performance takes time from the beginning.it will make us be annoying to use flux architecture.\n\n## Verge is designed for use from small and supports to scale.\n\nSetting Verge up quickly, and tune-up when we need it.\n\nVerge automatically tune-up and shows us what makes performance badly while development from Xcode's documentation.\n\nFor example, Verge provides these stuff to tune performance up.\n\n- Derived (Similar to [facebookexperimental/Recoil](https://github.com/facebookexperimental/Recoil)'s Selector)\n- ORM\n\n## Supports volatile events - Activity\n\nWe use an event as `Activity` that won't be stored in the state.This concept would help us to describe something that is not easy to describe as a state in the client application.\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Guides/Advanced Usage.md",
    "content": "# Advanced Usage\n\n## To keep performance and scalability\n\n## Adding a cachable computed property in a State\n\nWe can add a computed property in a state to get a derived value with stored property,\nand that computed property works fine as well other stored property.\n\n```swift\nstruct MyState {\n  var items: [Item] = [] {\n\n  var itemsCount: Int {\n    items.count\n  }\n}\n```\n\nHowever, this patterns might cause an expensive cost of operation depends on how they computes.\nTo solve it, Verge arrows us to define the computed property with another approach.\n\n```swift\nstruct MyState: ExtendedStateType {\n\n  var name: String = ...\n  var items: [Int] = []\n\n  struct Extended: ExtendedType {\n    let filteredArray = Field.Computed<[Int]> {\n      $0.items.filter { $0 > 300 }\n    }\n    .ifChanged(selector: \\.largeArray)\n  }\n}\n```\n\n```swift\nlet store: MyStore\n\nstore.changes.computed.filteredArray\n```\n\nThis defined computed array calculates only if changed specified value.\nThat condition to re-calculate is defined with `.ifChanged` method in the example code.\n\nAnd finally, it caches the result by first-time access and it returns cached value until if the source value changed.\n\n## Making a slice of the state (Selector)\n\nWe can create a slice object that derives a data from the state.\n\n```swift\nlet derived: Derived<Int> = store.derived(.map(\\.count))\n\n// take a value\nderived.value\n\n// subscribe a value changes\nderived.sinkChanges { (changes: Changes<Int>) in\n}\n```\n\n## Creating a Dispatcher\n\nStore arrows us to define an action in itself, that might cause gain complexity in supporting a large application.\nTo solve this, Verge offers us to create an object that dispatches an action to the store.\nWe can separate the code of actions to keep maintainability.\nthat also help us to manage a different type of dependencies.\n\nFor example, the case of those dependencies different between logged-in and logged-out.\n\n```swift\nclass MyDispatcher: MyStore.Dispatcher {\n  func moreOperation() {\n    commit {\n      ...\n    }\n  }\n}\n```\n\n```swift\nlet store: MyStore\nlet dispatcher = MyDispatcher(target: store)\n\ndispatcher.moreOperation()\n```\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Guides/Basic Usage.md",
    "content": "# Basic Usage\n\nThis section shows you how we start to use Verge.\nIt’s very basic usage. You need to read Advanced Usage section if you’re considering to use in production.\n\nTo understand smoothly about Verge, we need to figure the following domains out.\n\n## Domains\n\n### Store\n\n- A storage object to manage a state and emit activities by the action.\n- Store can dispatch actions to itself.\n\n### State\n\n- A type of state-tree that describes the data our feature needs.\n\n### Activity (Optional)\n\n- A type that describes an activity that happens during performs the action.\n- This instance won’t be stored in anywhere. It would help us to perform something by event-driven.\n- Consider to use this depends on that if can be represented as a state.\n- For example, to present alert or notifcitaions by the action.\n\n### Action\n\n- Action runs any operations (sync / async) and commits any mutations to the state of the store.\n- Action is described by Swift’s method in Store or Dispatcher.\n\n### Dispatcher (Optional)\n\n- A type to dispatch an action to specific store.\n- For a large application, to separate the logics each domain.\n\n## Setup a Store\n\n### Define a state\n\n```swift\nstruct MyState {\n  var count = 0\n}\n```\n\n### Define an activity\n\n```swift\nenum MyActivity {\n  case countWasIncremented\n}\n```\n\n`Activity` is not required type.\nIf you don’t need to use `Activity`, you can set`Never` in Store’s type parameter.\n\n### Define a store\n\n```swift\nclass MyStore: Store<MyState, MyActivity> {\n\n  init(dependency: Dependency) {\n    super.init(initialState: .init(), logger: nil)\n  }\n\n}\n```\n\nIn example, it created a subclass of `Store`. Of course, we can also create an instance from `Store` without subclassing.\nBut we can put some dependencies (e.g. API client) with creating a sub-class of `Store`.\n\n<aside>\n💡 When don’t use Activity\n`class MyStore: Store<MyState, Never>`\n\n</aside>\n\n## Add an action\n\nNext, add an action to mutate the state. Essentially, Verge uses Swift’s method to describe an action against enum or struct based action descriptor other Flux library has. This approach has advantages that adding an action faster and call it naturally and dispatches with a faster way by Swift’s native method dispatching system.\n\n- **Better Performance**\n    - Swift can perform this action with Swift’s method dispatching instead switch-case computing.\n- **Returns anything we need**\n    - the action can return anything from that action (e.g. state or result)\n    - If that action dispatch async operation, it can return `Future` object. (such as Vuex action)\n\nAs a future direction, Verge might get a dispatching action system with describing with enum or struct based to run action.\nHowever, the current approach would be the base system for it.\n\nWe’re currently researching that needs.\n\n```swift\nclass MyStore: Store<MyState, MyActivity> {\n\tfunc incrementCount() { \n    commit { \n      $0.count += 1 \n    } \n}\n```\n\nYes, this point is most different with Redux. we could say it close to Vuex. Store knows what the application’s needs.\n\nTo mutate the state, we use `commit` method.\nthe argument inside commit’s closure is `inout State`, you can modify it anything but you can’t put the asynchronous operations.\nIf you need to do this, call `commit` from the asynchronous operation. like this:\n\n```swift\nfunc incrementCount() {\n  DispatchQueue.main.async {\n    commit {\n      $0.count += 1\n    }\n  }\n}\n```\n\n<aside>\n💡 You can define actions aware from the Store Using `Dispatcher`, you can manage the set of actions aware from the store.\n\n</aside>\n\n### Run the action\n\nFor example, call that action.\n\n```swift\nlet store = MyStore(...)\nstore.incrementCount()\n```\n\n## Send an activity from the action\n\n```swift\nfunc incrementCount() {\n  ...\n  send(.countWasIncremented)\n}\n```\n\n## Binding the state with UI\n\n### Use the store in SwiftUI\n\nTo bind the state with `View`, it uses `StateReader`.\nSince `Store` is also compatible with `ObservableObject`, we can declare `@ObservedObject` or `@EnviromentObject`.\n\n`StateReader` provides several options to reduce no changes updates.\nPlease check it out from Xcode.\n\n```swift\nstruct MyView: View {\n\n  let store: MyStore\n\n  var body: some View {\n    StateReader(store).content { state in\n      Text(state.name)\n    }\n    .onReceive(session.store.activityPublisher) { (activity) in\n      ...\n    }\n  }\n}\n```\n\n### Use the store in UIKit\n\nIn UIKit, UIKit doesn’t work with differentiating.\nTo keep better performance, we need to set a value if it’s changed.\n\nVerge publishes an object that contains previous state and latest state, `Changes` object would be so helpful to check if a value changed.\n\n```swift\nclass ViewController: UIViewController {\n\n  let store: MyStore\n\n  var cancellable: VergeAnyCancellable?\n\n  init(store: MyStore) {\n    ...\n\n    self.cancellable = store.sinkState { [weak self] state in\n      self?.update(state: state)\n    }\n\n  }\n\n  private func update(state: Changes<MyStore.State>) {\n\n    state.ifChanged(\\.name) { (name) in\n      nameLabel.text = name\n    }\n\n    state.ifChanged(\\.age) { (age) in\n      ageLabel.text = age.description\n    }\n\n  }\n}\n```\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Guides/Migration Guide v9.md",
    "content": "# Changes in v9\n\n## Store requires Equatable State\n\nFrom v8 complex implementations, v9 becomes it requires Equatable to State associated with Store, Changes, Derived and what else related.\n\nThen Verge v9 now dropped lots of implementations and overloads covering cases if the state don’t have Equatable.\n\n## Store can have multiple databases\n\nNow, Store has `databases` accessor that allows us to read database.\n`databases` is `DatabaseDynamicMembers` which provides property following to State shape.\nThis looks up member only type of `DatabaseType`\n\n```swift\n@dynamicMemberLookup\npublic struct DatabaseDynamicMembers<Store: StoreType> {\n  \n  unowned let store: Store\n  \n  init(store: Store) {\n    self.store = store\n  }\n\n  public subscript<Database: DatabaseType>(dynamicMember keyPath: KeyPath<Store.State, Database>) -> DatabaseContext<Store, Database> {\n    .init(keyPath: keyPath, store: store)\n  }\n  \n}\n```\n\n## Use new syntax for creating Field.Computed\n\nAs you know, Changes supports memoized-computed-property.\nThat can be done writing `Field.Computed`\n\nNow its writing syntax will change.\n\n```swift\nlet filteredArray = Field.Computed(\n  .map(\n    using: { $0.largeArray },\n    transform: { $0.filter { $0 > 300 } }\n  )\n)\n```\n\n`using` specifies the dependencies which used from `transform` function.\n`transform` function will create a new value from given dependencies provided from `using` function.\n\n## Detail changes\n\n- Dropped complex implementations related to performance tunings\n- Stopped using cache to return Derived internally.\n- Deleted `batchCommit`\n\nFrom v8 complex implementations, v9 becomes it requires Equatable to State associated with Store, Changes, Derived and what else related.\n\nThen Verge v9 now dropped lots of implementations and overloads covering cases if the state don’t have Equatable.\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Mutation.md",
    "content": "#  Mutation\n\n## What Mutation is\n\nThe only way to actually change state in a Store is by committing a mutation. Define a function that returns Mutation object. That expresses that function is Mutation\n\n<aside>\n⚠️ Mutation does NOT allow to run asynchronous operation.\n\n</aside>\n\nMutation does **NOT** allow to run asynchronous operation.\n\n### Define mutations in the Store\n\n```swift\nstruct MyState {\n  var todos: [TODO] = []\n}\n\nclass MyStore: Store<MyState, Never> {\n\n  func addNewTodo(title: String) {\n    commit { (state: inout InoutRef<MyState>) in\n      state.todos.append(Todo(title: title, hasCompleted: false))\n    }\n  }\n\n}\n```\n\n<aside>\n💡 If the commit has no modifications, Store skips the mutation.\n\n</aside>\n\n### Run Mutation\n\n```swift\nlet store = MyStore()\nstore.addNewTodo(title: \"Create SwiftUI App\")\n\nprint(store.state.todos)\n// store.state.todos => [Todo(title: \"Create SwiftUI App\", hasCompleted: false)]\n```\n\n## Batches multiple commtis\n\nCommitting multiple mutations in a short time might decrease performance.\nBecause the subscribers around the store derive a state many times.\n\nLike this,\n\n```swift\nclass MyStore: Store<MyState, Never> {\n\n  func myMutation() {\n    if ... {\n      commit {\n        ...\n      }\n      // emits updated event\n    }\n\n    if ... {\n      commit {\n        ...\n      }\n      // emits updated event\n    }\n\n    if ... {\n      commit {\n        ...\n      }\n      // emits updated event\n    }\n  }\n\n}\n```\n\nTo keep better performance, we need to keep using fewer commits in a short time.\n\nWe have 2 ways.\n\n### Using `commit`\n\n``DispatcherType/commit(_:_:_:_:mutation:)`` provides ``InoutRef``, that can detect how the wrapped state will change.\nIf there is no change, `commit` does nothing and no emitting the events from the Store.\n\nHowever, you should attention `commit` is atomically operation which means, the Store getting lock while committing.\n\n```swift\nfunc myMutation() {\n  commit { (state: inout InoutRef<State>) in\n    if ... {\n      state.aaa = ...\n    }\n\n    if ... {\n      state.bbb = ...\n    }\n\n    if ... {\n      state.ccc = ...\n    }\n  }\n}\n```\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Resources/Tiny.md",
    "content": "# Yet another super tiny store pattern with Verge/Tiny\n\nIn fact, `store-pattern` doesn't need something library to run.\nThe actually necessary thing is **the changing detection in UIKit.**\n\nWithout the changing detection, the code is here.\nThere is no dependencies.\n\n```swift\nclass MyView: UIView {\n  private struct State {\n    var count: Int = 0\n  }\n  \n  private var state: State {\n    didSet {\n      update(with: state)\n    }\n  }\n\n  private func update(with state: State) {\n    ...\n  }\n}\n```\n\nNext, we focus on `update(with:)` method.\nTry to simulate updating the label's value.\n\n```swift\nprivate func update(with state: State) {\n  myLabel.text = \"\\(state.count)\"\n}\n```\n\nAs you can see, you will think you want to prevent updating the value until the value changed.\n\n## Use Verge.Tiny module to prevent the duplicated updating.\n\nWith installing `Verge/Tiny` module, we can write up like followings.\n\n```swift\nprivate func update(with state: State) {\n  associatedProperties.doIfChanged(state.count) { count in \n    myLabel.text = \"\\(count)\"\n  }\n}\n```\n\n`associatedProperties` is a storage of the values that associated with its owner object(NSObject).\n\n`doIfChanged` gets the location of the code that would be a unique key by composition in the storage.\n\nWith this functions, we can get a filter anywhere in the object.\nHowever, this function might affect code readabilities in Swift. \nPlease carefully using this.\n\nWe recommend you gather those operations into one place.\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/State.md",
    "content": "# Thinking in single state tree (Not enforced)\n\nVergeStore uses a **single state-tree. (Recommended)** That means an object contains all of the application’s state. With this, we can get to achieve **“single source of truth”**\n\nThat state is managed by ``Store``. It process updating the state and notify updated events to the subscribers.\n\n> Tip: Store DOES support multiple state-tree as well. Depending on the case, we can create another Store instance.\n\n## Add a computed property\n\n```\nstruct State: Equatable {\n\n  var count: Int = 0\n\n  var countText: String {\n    return count.description\n  }\n\n}\n```\n\nExtending properties that computes a value from stored property.\n\nAlthough in some of cases, the cost of computing might be higher which depends on how it create the value from stored properties.\n\nThere is ``ExtendedStateType``.\nThis provies us to get more stuff that **increases performance** and productivity.\n\n## Attention to Normalization\n\n**If you put the data that has relation-ship or complicated structure into state tree, it would be needed normalization to keep performance. Please check VergeORM module**\n\n[About more Normalization and why we need to do this](https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape/)\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Verge.Store.md",
    "content": "# ``Verge/Store``\n\n- Store:\n    - Should be a reference type object,\n    - To share the state they manage to multiple subscribers.\n    - Receives **Mutation** to update the state with thread-safety\n    - Compatible with SwiftUI’s observableObject and we can use `StateReader` to read the state partially.\n\n## Ways to creating a store\n\nVerge provides 2 ways to create a store.\n\n1. Declare a class that conforms with `StoreComponentType` - It’s a protocol that indicates the class wraps a store inside and behaves like a store.\n2. Subclassing from `Store` - a most basic way, but we need to define State and Activity outside\n\nNow, we recommend using No.1 in order to manage the source code with better portability.\n\n## Declare a class that conforms with `StoreComponentType`\n\n```swift\nfinal class MyStore: StoreComponentType {\n\n  struct State: StateType {\n    var count: Int = 0\n  }\n\n  /// This means wrapping store inside. (Probably it should be renamed as like `innerStore` or `wrappedStore`)\n  /// `DefaultStore` is a typealias that declared by `StoreComponentType`.\n  /// You can use any class that inherited from `Store` for your use-cases.\n  let store: DefaultStore\n\n  init() {\n\n    self.store = .init(initialState: .init())\n\n  }\n\n}\n```\n\n### Add a Mutation\n\n```swift\nextension MyStore {\n\n  func increment() {\n    commit {\n      $0.count += 0\n    }\n  }\n\n}\n```\n\n### Commit the mutation\n\n```swift\nlet store = MyStore()\nstore.increment()\n```\n\n## Subclassing from `Store`\n\n```swift\nstruct State: StateType {\n  var count: Int = 0\n}\n\nenum Activity {\n  case happen\n}\n\nfinal class MyStore: Store<State, Never> {\n\n  init() {\n    super.init(\n      initialState: .init(),\n      logger: DefaultStoreLogger.shared\n    )\n  }\n\n}\n```\n\n### Add a Mutation\n\n```swift\nextension MyStore {\n\n  func increment() {\n    commit {\n      $0.count += 0\n    }\n  }\n\n}\n```\n\n### Commit the mutation\n\n```swift\nlet store = MyStore()\nstore.increment()\n```\n"
  },
  {
    "path": "Sources/Verge/Documentation.docc/Verge.md",
    "content": "# ``Verge``\n\n\n## 🛹 Small start unidirectional data flow\n\nVerge is designed for use from small and supports to scale. Setting Verge up quickly, and tune-up when we need it.\n\n## 🏎 Focus on performance\n\nDoes flux have a good performance?The performance will be the worst depends on how it is used.Verge automatically tune-up and shows us how we could gain a performant.\n\n## ⛱ Available in **UIKit** and **SwiftUI**\n\nVerge supports both of UI framework. Especially, it highly supports to update partially UI on UIKit.\n\n## Verge supports small start and scaling up\n\nVerge is a state management library for iOS (UIKit / SwiftUI).Mostly it's based on Flux architecture.Flux architecture is so beautiful and simplified thinking.Although, we need to do several tuning to bring it into a real product.In fact, Flux needs to consider about computing resources.\n\nVerge contains several ideas to do this from Web technologies such as Redux, Vuex, and Recoil.They have very useful techniques to be successful in real-world productions based on the core-concept of Flux.\n\nVerge can be setting it up quickly, and tune performance up when we need it.Verge automatically tune-up as possible and shows us what makes performance badly while development from Xcode's documentation.\n\n## At a glance\n\nA way to create a ViewModel\n\n```swift\nfinal class MyViewModel: StoreComponentType {\n\n  struct State: Equatable {\n    var name: String = \"\"\n    var count: Int = 0\n  }\n\n  let store: DefaultStore = .init(initialState: .init())\n\n  func myAction() {\n    commit {\n      $0.name = \"Hello, Verge\"\n    }\n  }\n\n  func increment() {\n    commit {\n      $0.count += 1\n    }\n  }\n}\n```\n\nA way to create a customized store\n\n```swift\nstruct MyState: Equatable {\n  var name: String = \"\"\n  var count: Int = 0\n}\n\nfinal class MyStore: Store<MyState, Never> {\n\n  func myAction() {\n    commit {\n      $0.name = \"Hello, Verge\"\n    }\n  }\n\n  func increment() {\n    commit {\n      $0.count += 1\n    }\n  }\n}\n```\n\n### SwiftUI\n\n```swift\nstruct MyView: View {\n\n  let store: MyViewModel\n\n  var body: some View {\n    StateReader(store) { state in\n      Text(state.name)\n      Button(action: {\n        self.store.myAction()\n      }) {\n        Text(\"Action\")\n      }\n    }\n  }\n}\n```\n\n### UIKit\n\n```swift\nfinal class MyViewController: UIViewController {\n\n  let viewModel: MyViewModel\n\n  ...\n\n  var cancellable: VergeAnyCancellable?\n\n  init(viewModel: MyViewModel) {\n\n    self.viewModel = viewModel\n\n    self.cancellable = viewModel.sinkState { [weak self] state in\n      self?.update(state: state)\n    }\n\n  }\n\n  private func update(state: Changes<MyStore.State>) {\n\n    state.ifChanged(\\.name) { (name) in\n      nameLabel.text = name\n    }\n\n    state.ifChanged(\\.count) { (age) in\n      countLabel.text = age.description\n    }\n\n    ...\n  }\n\n}\n```\n\n## Prepare moving to SwiftUI from now with Verge\n\nSwiftUI's concept is similar to the concept of React, Vue, and Elm.Therefore, the concept of state management will become to be similar as well.\n\nThat is Redux or Vuex and more.\n\nNow, almost of iOS Applications are developed on top of UIKit.And We can't say SwiftUI is ready for top production.However, it would change.\n\nIt's better to use the state management that fits SwiftUI from now. It's not only for that, current UIKit based applications can get more productivity as well.\n\n## Questions?\n\nWe accept your questions about usage of Verge and something else in GitHub Issues.\n\n日本語での質問も大丈夫です\n\n\n\n## Topics\n\n### Guides\n\n- <doc:Motivation>\n- <doc:Basic-Usage>\n- <doc:Advanced-Usage>\n\n### Extras\n\n- <doc:Tiny>\n\n### Migrations\n\n- <doc:Migration-Guide-v9>\n\n### Essentials\n\n- ``Verge/Store``\n- ``Verge/Changes``\n- ``Verge/Derived``\n- ``Verge/DispatcherType``\n"
  },
  {
    "path": "Sources/Verge/Library/BackgroundDeallocationQueue.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\nimport DequeModule\n\nactor BackgroundDeallocationQueue {\n\n  private var buffer: Deque<Unmanaged<AnyObject>> = .init()\n\n  func releaseObjectInBackground(object: AnyObject) {\n\n    let innerCurrentRef = Unmanaged.passRetained(object)\n\n    let isFirstEntry = buffer.isEmpty\n    buffer.append(innerCurrentRef)\n\n    if isFirstEntry {\n      Task {\n        // accumulate objects to dealloc for batching\n        try? await Task.sleep(nanoseconds: 1_000_000)\n        await self.drain()\n      }\n    }\n  }\n\n  func drain() async {\n\n    guard buffer.isEmpty == false else {\n      return\n    }\n\n    while let pointer = buffer.popFirst() {\n      pointer.release()\n      await Task.yield()\n    }\n\n    await drain()\n\n  }\n}\n"
  },
  {
    "path": "Sources/Verge/Library/CachedMap.swift",
    "content": "//\n// Copyright (c) 2020 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\n@available(*, deprecated, renamed: \"InstancePool\")\npublic typealias CachedMapStorage<Source, Target> = InstancePool<Source, Target>\n\n/// A storage object that retains projected instance from source by identified key.\npublic final class InstancePool<Source, Target>: @unchecked Sendable {\n\n  struct Artifact {\n    let source: Source\n    var value: Target\n  }\n\n  private let generateKey: @Sendable (Source) -> AnyHashable\n  private let updateCondition: @Sendable (Source, Source) -> Bool\n\n  private var innerStorage: [AnyHashable: Artifact] = [:]\n\n  private let outerLock = NSLock()\n\n  /// Creates an instance\n  ///\n  /// - Parameters:\n  ///   - keySelector: A closure that gives key to identify the mapped instance.\n  ///   - shouldUpdate: A closure that indicates whether cached one replace with new mapped instance.\n  public init<Key: Hashable>(\n    keySelector: @escaping @Sendable (Source) -> Key,\n    shouldUpdate: @escaping @Sendable (_ cached: Source, _ new: Source) -> Bool = { _, _ in false }\n  ) {\n    self.updateCondition = shouldUpdate\n    self.generateKey = {\n      AnyHashable(keySelector($0))\n    }\n  }\n\n  public func purgeCache() {\n    outerLock.lock()\n    defer {\n      outerLock.unlock()\n    }\n    innerStorage = [:]\n  }\n\n  public func map<C: Collection>(\n    from collection: C,\n    sweepsUnused: Bool,\n    makeNew: (C.Element) throws -> Target,\n    update: (C.Element, inout Target) -> Void\n  ) rethrows -> [Target] where C.Element == Source {\n\n    outerLock.lock()\n    defer {\n      outerLock.unlock()\n    }\n\n    let keys = collection.map(generateKey)\n\n    let result = try zip(collection, keys).map { (element, key) -> Target in\n      if let cached = innerStorage[key], !updateCondition(cached.source, element) {\n        update(element, &innerStorage[key]!.value)\n        return innerStorage[key]!.value\n      }\n      let newObject = try makeNew(element)\n      innerStorage[key] = Artifact(source: element, value: newObject)\n      return newObject\n    }\n\n    if sweepsUnused {\n      let unusedKeys = Set(innerStorage.keys).subtracting(keys)\n      \n      for key in unusedKeys {\n        innerStorage.removeValue(forKey: key)\n      }\n    }\n\n    return result\n  }\n\n  public func compactMap<C: Collection>(\n    from collection: C,\n    sweepsUnused: Bool,\n    makeNew: (C.Element) throws -> Target?,\n    update: (C.Element, inout Target) -> Void\n  )\n    rethrows -> [Target] where C.Element == Source\n  {\n\n    outerLock.lock()\n    defer {\n      outerLock.unlock()\n    }\n\n    let keys = collection.map(generateKey)\n\n    let result = try zip(collection, keys).compactMap { (element, key) -> Target? in\n      if let cached = innerStorage[key], !updateCondition(cached.source, element) {\n        update(element, &innerStorage[key]!.value)\n        return innerStorage[key]!.value\n      }\n      guard let newObject = try makeNew(element) else { return nil }\n      innerStorage[key] = Artifact(source: element, value: newObject)\n      return newObject\n    }\n\n    if sweepsUnused {\n      let unusedKeys = Set(innerStorage.keys).subtracting(keys)\n      \n      for key in unusedKeys {\n        innerStorage.removeValue(forKey: key)\n      }\n    }\n\n    return result\n  }\n}\n\nextension Collection {\n\n  /**\n   Returns an array containing the results of mapping the given closure over the sequence’s elements.\n   Especially, it uses a cached instance to return.\n   You can set your expectation on how it caches from creating `CachedMapStorage`.\n\n   It helps to create a store object or view model from immutable data.\n\n   - Author: Verge\n   */\n  public func cachedMap<U>(\n    using pool: InstancePool<Self.Element, U>,\n    sweepsUnused: Bool = false,\n    makeNew: (Self.Element) throws -> U,\n    update: (Self.Element, inout U) -> Void = { _, _ in }\n  ) rethrows -> [U] {\n    return try pool.map(from: self, sweepsUnused: sweepsUnused, makeNew: makeNew, update: update)\n  }\n\n  /**\n   Returns an array containing the results of mapping the given closure over the sequence’s elements.\n   Especially, it uses a cached instance to return.\n   You can set your expectation on how it caches from creating `CachedMapStorage`.\n\n   It helps to create a store object or view model from immutable data.\n\n   - Author: Verge\n   */\n  public func cachedCompactMap<U>(\n    using pool: InstancePool<Self.Element, U>,\n    sweepsUnused: Bool = false,\n    makeNew: (Self.Element) throws -> U?,\n    update: (Self.Element, inout U) -> Void = { _, _ in }\n  ) rethrows -> [U] {\n    return try pool.compactMap(from: self, sweepsUnused: sweepsUnused, makeNew: makeNew, update: update)\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Library/EventEmitter.swift",
    "content": "//\n// Copyright (c) 2019 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Atomics\nimport Combine\nimport DequeModule\nimport Foundation\nimport os\n\npublic final class EventEmitterCancellable: Hashable, Cancellable, @unchecked Sendable {\n\n  public static func == (lhs: EventEmitterCancellable, rhs: EventEmitterCancellable) -> Bool {\n    lhs === rhs\n  }\n\n  private struct State {\n    weak var owner: EventEmitterType?\n    var wasCancelled: Bool = false\n  }\n\n  private let state: VergeConcurrency.ManagedCriticalState<State>\n\n  fileprivate init(owner: EventEmitterType) {\n    self.state = VergeConcurrency.ManagedCriticalState(State(owner: owner))\n  }\n\n  public func hash(into hasher: inout Hasher) {\n    ObjectIdentifier(self).hash(into: &hasher)\n  }\n\n  public func cancel() {\n    \n    let continues: EventEmitterType? = state.withCriticalRegion { \n      guard $0.wasCancelled == false else {\n        return nil\n      }\n      $0.wasCancelled = true\n      return $0.owner\n    }      \n    \n    continues?.removeEventHandler(self)\n  }\n}\n\nprotocol EventEmitterType: AnyObject, Sendable {\n  func removeEventHandler(_ token: EventEmitterCancellable)\n}\n\npublic protocol EventEmitterEventType {\n  func onComsume()\n}\n\n/// Instead of Combine\nopen class EventEmitter<Event: EventEmitterEventType>: EventEmitterType, @unchecked Sendable {\n\n  public var publisher: Publisher {\n    return .init(eventEmitter: self)\n  }\n\n  private var subscribers:\n    VergeConcurrency.UnfairLockAtomic<[EventEmitterCancellable: (Event) -> Void]> = .init([:])\n\n  private let queue: VergeConcurrency.UnfairLockAtomic<Deque<Event>> = .init(.init())\n\n  private let flag = ManagedAtomic<Bool>.init(false)\n\n  private var deinitHandlers: VergeConcurrency.UnfairLockAtomic<[() -> Void]> = .init([])\n\n  public init() {\n  }\n\n  deinit {\n    deinitHandlers.value.forEach {\n      $0()\n    }\n  }\n\n  @_spi(EventEmitter)\n  public func accept(_ event: consuming Event) {\n\n    /**\n     https://github.com/VergeGroup/Verge/pull/220\n     https://github.com/VergeGroup/Verge/issues/221\n     https://github.com/VergeGroup/Verge/pull/222\n     */\n\n    // delivers a given event for subscribers at this point.\n    let capturedSubscribers = subscribers.value\n\n    queue.modify {\n      $0.append(event)\n    }\n\n    if flag.compareExchange(expected: false, desired: true, ordering: .sequentiallyConsistent)\n      .exchanged\n    {\n\n      while let event: Event = queue.modify({\n        if $0.isEmpty == false {\n          return $0.removeFirst()\n        } else {\n          return nil\n        }\n      }) {\n\n        // Emits\n        receiveEvent(event)\n\n        for subscriber in capturedSubscribers {\n          vergeSignpostEvent(\"EventEmitter.emitForSubscriber\")\n          subscriber.1(event)\n        }\n        event.onComsume()\n      }\n\n      /**\n       might contain a bug in here?\n       a conjunction of enqueue and dequeue\n       */\n\n      _ = flag.compareExchange(expected: true, desired: false, ordering: .sequentiallyConsistent)\n    } else {\n      // enqueue only\n    }\n\n  }\n\n  open func receiveEvent(_ event: consuming Event) {\n\n  }\n\n  @_spi(EventEmitter)\n  @discardableResult\n  public func addEventHandler(_ eventReceiver: @escaping (Event) -> Void) -> EventEmitterCancellable\n  {\n    let token = EventEmitterCancellable(owner: self)\n    subscribers.modify {\n      $0[token] = eventReceiver\n    }\n    return token\n  }\n\n  func removeEventHandler(_ token: EventEmitterCancellable) {\n    var itemToRemove: ((Event) -> Void)? = nil\n    subscribers.modify {\n      itemToRemove = $0[token]\n      $0.removeValue(forKey: token)\n    }\n\n    // To avoid triggering deinit inside removing operation\n    // At this point, deallocation will happen, then ``EventEmitterCancellable` runs operations.\n    // subscribers is using unfair-lock means it's not recursive lock.\n    // if removes the item then deallocated inside locking, onDeinit handler runs then entering this method recursively potentially by some others.\n    // then unfair-lock raises runtime error.\n    withExtendedLifetime(itemToRemove, {})\n  }\n\n  public func onDeinit(_ onDeinit: @escaping () -> Void) {\n    deinitHandlers.modify {\n      $0.append(onDeinit)\n    }\n  }\n\n}\n\nextension EventEmitter {\n\n  @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)\n  public struct Publisher: Combine.Publisher {\n\n    public typealias Output = Event\n\n    public typealias Failure = Never\n\n    private weak var eventEmitter: EventEmitter<Event>?\n\n    public init(eventEmitter: EventEmitter<Event>) {\n      self.eventEmitter = eventEmitter\n    }\n\n    public func receive<S>(subscriber: S)\n    where S: Subscriber, Failure == S.Failure, Output == S.Input {\n\n      let subscription = Subscription<S>(subscriber: subscriber, eventEmitter: eventEmitter)\n      subscriber.receive(subscription: subscription)\n    }\n\n  }\n\n  @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)\n  public struct Subscription<S: Subscriber>: Combine.Subscription where S.Input == Event {\n\n    public let combineIdentifier: CombineIdentifier = .init()\n\n    private let subscriber: S\n    private let eventEmitterSubscription: EventEmitterCancellable?\n    private weak var eventEmitter: EventEmitter<Event>?\n\n    init(subscriber: S, eventEmitter: EventEmitter<Event>?) {\n\n      self.subscriber = subscriber\n      self.eventEmitter = eventEmitter\n\n      self.eventEmitterSubscription = eventEmitter?\n        .addEventHandler { (event) in\n          _ = subscriber.receive(event)\n        }\n    }\n\n    public func request(_ demand: Subscribers.Demand) {\n      // TODO: implement\n    }\n\n    public func cancel() {\n      guard let eventEmitterSubscription else { return }\n      eventEmitter?.removeEventHandler(eventEmitterSubscription)\n    }\n\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Library/InoutRef.swift",
    "content": "//\n// Copyright (c) 2020 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\nimport StateStruct\n\npublic enum Modification {\n  case graph(PropertyNode)\n  case indeterminate\n}\n\npublic struct InoutRef<Wrapped>: ~Copyable {\n    \n  // MARK: - Properties\n\n  nonisolated(unsafe) private let pointer: UnsafeMutablePointer<Wrapped>\n\n  /// A wrapped value\n  /// You may use this property to call the mutating method which `Wrapped` has.\n  public var wrapped: Wrapped {\n    _read {\n      yield pointer.pointee\n    }\n    _modify {\n      yield &pointer.pointee\n    }\n  }\n  \n  private(set) var modification: Modification?\n\n  public var hasModified: Bool {\n    guard let modification else {\n      return false\n    }    \n    switch modification {\n    case .graph(let graph):\n      return !graph.isEmpty\n    case .indeterminate:\n      return true\n    }      \n  }\n\n  // MARK: - Initializers\n\n  /**\n   Creates an instance\n\n   You should take care of using the pointer of value.\n   Using always `withUnsafeMutablePointer` to pass it, otherwise Swift might crash with Memory error.\n   */\n  init(_ pointer: UnsafeMutablePointer<Wrapped>) {\n    self.pointer = pointer\n  }\n  \n  deinit {\n    (pointer.pointee as? TrackingObject)?.endTracking()\n  }\n\n  // MARK: - Functions\n  \n  public mutating func modify<T>(_ perform: (inout Wrapped) throws -> T) rethrows -> T {\n    \n    if pointer.pointee is TrackingObject {\n      \n      let identifier = Token()\n      \n      (pointer.pointee as! TrackingObject)._tracking_context.identifier = identifier\n      \n      let result = try perform(&pointer.pointee)\n                  \n      let resultIdentifier = (pointer.pointee as! TrackingObject)._tracking_context.identifier\n      \n      (pointer.pointee as! TrackingObject)._tracking_context.identifier = nil\n      \n      guard Optional(identifier) == resultIdentifier else {\n        // replacing instance itself happened.\n        modification = .indeterminate\n        return result\n      }\n      \n      if var modifyingResult = (pointer.pointee as! TrackingObject).trackingResult {\n        \n        modifyingResult.graph.shakeAsWrite()\n        \n        let graph = modifyingResult.graph\n        \n        self.modification = .graph(graph)\n//#if DEBUG\n//        Log.writeGraph.debug(\"Modified: \\(graph.prettyPrint())\")\n//#endif\n      } else {\n        modification = .indeterminate\n      }\n      \n      \n      return result\n      \n    } else {\n      let r = try perform(&pointer.pointee)\n      \n      modification = .indeterminate\n      \n      return r \n    }\n   \n  }\n\n}\n\n\nprivate final class Token: Hashable {\n  \n  static func == (lhs: Token, rhs: Token) -> Bool {\n    lhs === rhs\n  }\n  \n  func hash(into hasher: inout Hasher) {\n    ObjectIdentifier(self).hash(into: &hasher)\n  }\n  \n}\n\n/// Do not retain on anywhere.\n@dynamicMemberLookup\npublic final class ReadRef<Wrapped> {\n\n  private let pointer: UnsafePointer<Wrapped>\n\n  /// A wrapped value\n  /// You may use this property to call the mutating method which `Wrapped` has.\n  public var wrapped: Wrapped {\n    _read {\n      yield pointer.pointee\n    }\n  }\n\n  // MARK: - Initializers\n\n  /**\n   Creates an instance\n\n   You should take care of using the pointer of value.\n   Using always `withUnsafeMutablePointer` to pass it, otherwise Swift might crash with Memory error.\n   */\n  public init(_ pointer: UnsafePointer<Wrapped>) {\n    self.pointer = pointer\n  }\n\n  // MARK: - Functions\n\n  public subscript<T>(dynamicMember keyPath: KeyPath<Wrapped, T>) -> T {\n    _read {\n      yield pointer.pointee[keyPath: keyPath]\n    }\n  }\n\n  public subscript<T>(dynamicMember keyPath: KeyPath<Wrapped, T?>) -> T? {\n    _read {\n      yield pointer.pointee[keyPath: keyPath]\n    }\n  }\n\n  public subscript<T>(keyPath keyPath: KeyPath<Wrapped, T>) -> T {\n    _read {\n      yield pointer.pointee[keyPath: keyPath]\n    }\n  }\n\n  public subscript<T>(keyPath keyPath: KeyPath<Wrapped, T?>) -> T? {\n    _read {\n      yield pointer.pointee[keyPath: keyPath]\n    }\n  }\n\n  func map<U, Result>(keyPath: KeyPath<Wrapped, U>, perform: (inout ReadRef<U>) throws -> Result)\n    rethrows -> Result\n  {\n\n    try withUnsafePointer(to: pointer.pointee[keyPath: keyPath]) { (pointer) in\n      var ref = ReadRef<U>.init(pointer)\n      return try perform(&ref)\n    }\n  }\n\n  func map<U, Result>(keyPath: KeyPath<Wrapped, U?>, perform: (inout ReadRef<U>?) throws -> Result)\n    rethrows -> Result\n  {\n\n    guard pointer.pointee[keyPath: keyPath] != nil else {\n      var _nil: ReadRef<U>! = .none\n      return try perform(&_nil)\n    }\n\n    return try withUnsafePointer(to: pointer.pointee[keyPath: keyPath]!) { (pointer) in\n      var ref: ReadRef<U>! = ReadRef<U>.init(pointer)\n      return try perform(&ref)\n    }\n\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Library/Log.swift",
    "content": "//\n//  Log.swift\n//  VergeCore\n//\n//  Created by muukii on 2020/02/24.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\n\nimport os.log\n\nenum Log {\n    \n  static let store = Logger(OSLog.makeOSLogInDebug { OSLog.init(subsystem: \"Verge\", category: \"store\") })\n  \n  static let storeCommit = Logger(OSLog.makeOSLogInDebug { OSLog.init(subsystem: \"Verge\", category: \"store.commit\") })\n  \n  static let storeReader = Logger(OSLog.makeOSLogInDebug { OSLog.init(subsystem: \"Verge\", category: \"storeReader\") })\n  \n  static let reading = Logger(OSLog.makeOSLogInDebug { OSLog.init(subsystem: \"Verge\", category: \"reading\") })\n  \n  static let writeGraph = Logger(OSLog.makeOSLogInDebug { OSLog.init(subsystem: \"Verge\", category: \"writeGraph\") })\n  \n}\n\nextension OSLog {\n  \n  @inline(__always)\n  fileprivate static func makeOSLogInDebug(isEnabled: Bool = true, _ factory: () -> OSLog) -> OSLog {\n#if DEBUG\n    return factory()\n#else\n    return .disabled\n#endif\n  }\n  \n}\n"
  },
  {
    "path": "Sources/Verge/Library/Signpost.swift",
    "content": "import os\nimport Foundation\n\nnonisolated(unsafe)\npublic var _verge_signpost_enabled = ProcessInfo.processInfo.environment[\"VERGE_SIGNPOST_ENABLED\"] != nil\n\n@usableFromInline\nenum SignpostConstants {\n  @usableFromInline\n  static let performanceLog = { () -> OSLog in\n    if #available(iOSApplicationExtension 13.0, *) {\n      return OSLog(subsystem: \"lib.verge\", category: \"performance\")\n    } else {\n      return OSLog(subsystem: \"lib.verge\", category: \"performance\")\n    }\n  }()\n  @usableFromInline\n  static let pointOfInterestLog = OSLog(subsystem: \"lib.verge\", category: .pointsOfInterest)\n}\n\n@inlinable\npublic func vergeSignpostEvent(_ event: StaticString) {\n  #if DEBUG\n  if _verge_signpost_enabled {\n    let id = OSSignpostID(log: SignpostConstants.pointOfInterestLog)\n    os_signpost(.event, log: SignpostConstants.pointOfInterestLog, name: event, signpostID: id)\n  }\n  #endif\n}\n\n@inlinable\npublic func vergeSignpostEvent(_ event: StaticString, label: @autoclosure () -> String) {\n  #if DEBUG\n  if _verge_signpost_enabled {\n    let id = OSSignpostID(log: SignpostConstants.pointOfInterestLog)\n    os_signpost(.event, log: SignpostConstants.pointOfInterestLog, name: event, signpostID: id, \"%@\", label())\n  }\n  #endif\n}\n\n\npublic struct VergeSignpostTransaction {\n  \n  #if DEBUG\n  @usableFromInline\n  let _end: () -> Void\n  public let rawID: os_signpost_id_t\n  #endif\n  \n  public init(_ name: StaticString) {\n    #if DEBUG\n    if _verge_signpost_enabled {\n      let id = OSSignpostID(log: SignpostConstants.performanceLog)\n      self.rawID = id.rawValue\n      os_signpost(.begin, log: SignpostConstants.performanceLog, name: name, signpostID: id)\n      _end = {\n        os_signpost(.end, log: SignpostConstants.performanceLog, name: name, signpostID: id)\n      }\n    } else {\n      rawID = 0\n      _end = {}\n    }\n    #else\n    #endif\n  }\n  \n  public init(_ name: StaticString, label: @autoclosure () -> String) {\n    #if DEBUG\n    if _verge_signpost_enabled {\n      let id = OSSignpostID(log: SignpostConstants.performanceLog)\n      self.rawID = id.rawValue\n      let _label = label()\n      os_signpost(.begin, log: SignpostConstants.performanceLog, name: name, signpostID: id, \"Begin: %@\", _label)\n      _end = {\n        os_signpost(.end, log: SignpostConstants.performanceLog, name: name, signpostID: id, \"End: %@\", _label)\n      }\n    } else {\n      rawID = 0\n      _end = {}\n    }\n    #else\n    #endif\n  }\n  \n  public func event(name: StaticString, label: @autoclosure () -> String) {\n    #if DEBUG\n    if _verge_signpost_enabled {\n      let id = OSSignpostID(rawID)\n      os_signpost(.event, log: SignpostConstants.pointOfInterestLog, name: name, signpostID: id, \"%@\", label())\n    }\n    #endif\n  }\n  \n  @inlinable\n  @inline(__always)\n  public func event(name: StaticString) {\n    #if DEBUG\n    if _verge_signpost_enabled {\n      let id = OSSignpostID(rawID)\n      os_signpost(.event, log: SignpostConstants.pointOfInterestLog, name: name, signpostID: id)\n    }\n    #endif\n  }\n  \n  @inlinable\n  @inline(__always)\n  public func end() {\n    #if DEBUG\n    _end()\n    #endif\n  }\n}\n"
  },
  {
    "path": "Sources/Verge/Library/StoreActivitySubscription.swift",
    "content": "import Combine\nimport Atomics\n\n/**\n A subscription that is compatible with Combine’s Cancellable.\n You can manage asynchronous tasks either call the ``cancel()`` to halt the subscription, or allow it to terminate upon instance deallocation, and by implementing the ``storeWhileSourceActive()`` technique, the subscription’s active status is maintained until the source store is released.\n */\npublic final class StoreActivitySubscription: StoreSubscriptionBase, @unchecked Sendable {\n \n}\n\n"
  },
  {
    "path": "Sources/Verge/Library/StoreStateSubscription.swift",
    "content": "import Combine\nimport Atomics\n\n/**\n A subscription that is compatible with Combine's Cancellable.\n You can manage asynchronous tasks either call the ``cancel()`` to halt the subscription, or allow it to terminate upon instance deallocation, and by implementing the ``storeWhileSourceActive()`` technique, the subscription's active status is maintained until the source store is released.\n */\npublic final class StoreStateSubscription: StoreSubscriptionBase, @unchecked Sendable {\n  \n}\n"
  },
  {
    "path": "Sources/Verge/Library/StoreSubscriptionBase.swift",
    "content": "\npublic class StoreSubscriptionBase: Hashable, Cancellable {\n\n  public static func == (lhs: StoreSubscriptionBase, rhs: StoreSubscriptionBase) -> Bool {\n    lhs === rhs\n  }\n  \n  private struct State {\n    var wasCancelled: Bool = false\n    weak var storeCancellable: VergeAnyCancellable?\n    var associatedStore: (any StoreType)?\n  }\n  \n  private let state: VergeConcurrency.ManagedCriticalState<State>\n  \n  public func hash(into hasher: inout Hasher) {\n    ObjectIdentifier(self).hash(into: &hasher)\n  }    \n  \n  private let source: EventEmitterCancellable\n  \n  init(\n    _ eventEmitterCancellable: EventEmitterCancellable,\n    storeCancellable: VergeAnyCancellable\n  ) {\n    self.source = eventEmitterCancellable\n    self.state = .init(State(storeCancellable: storeCancellable))\n  }\n  \n  public func cancel() {\n    \n    let continues = state.withCriticalRegion { state -> Bool in\n      guard state.wasCancelled == false else {\n        return false\n      }\n      state.wasCancelled = true  \n      // if it's associated as storeWhileSourceActive.\n      state.storeCancellable?.dissociate(self)\n      state.associatedStore = nil\n      return true\n    }\n    \n    guard continues else {\n      return\n    }\n    \n    source.cancel()\n  }\n  \n  /**\n   Make this subscription alive while the source is active.\n   the source means a root data store which is Store.\n   \n   In case of Derived, the source will be Derived's upstream.\n   If the upstream invalidated, this subscription will stop.\n   */\n  @discardableResult\n  public func storeWhileSourceActive() -> Self {\n    state.withCriticalRegion { state in   \n      assert(state.wasCancelled == false)\n      assert(state.storeCancellable != nil)\n      state.storeCancellable?.associate(self)\n    }\n    return self\n  }\n       \n  func associate(store: any StoreType) -> Self {\n    state.withCriticalRegion { state in\n      assert(state.wasCancelled == false)\n      assert(state.storeCancellable != nil)\n      state.associatedStore = store\n    }\n    return self\n  }\n  \n  /**\n   Converts to Combine.AnyCancellable to make it auto cancellable.\n   */\n  public func asAny() -> AnyCancellable {\n    return .init { [self] in\n      self.cancel()\n    }\n  }\n  \n  deinit {\n    cancel()\n  }\n}\n"
  },
  {
    "path": "Sources/Verge/Library/VergeAnyCancellable.swift",
    "content": "import Combine\nimport Atomics\n\n/// A typealias to `Set<AnyCancellable>`.\npublic typealias VergeAnyCancellables = Set<AnyCancellable>\n\n/// A type-erasing cancellable object that executes a provided closure when canceled.\n/// An AnyCancellable instance automatically calls cancel() when deinitialized.\n/// To cancel depending owner, can be written following\n///\n/// ```\n/// class ViewController {\n///\n///   var subscriptions = VergeAnyCancellables()\n///\n///   func something() {\n///\n///   let derived = store.derived(...)\n///\n///   derived\n///     .subscribeStateChanges { ... }\n///     .store(in: &subscriptions)\n///   }\n///\n/// }\n/// ```\npublic final class VergeAnyCancellable: Hashable, Cancellable, Sendable {\n\n  private struct State {\n    var wasCancelled: Bool = false\n    var actions: ContiguousArray<() -> Void>? = .init()\n    var retainObjects: [AnyObject] = []\n  }\n  \n  private let state: VergeConcurrency.ManagedCriticalState<State> = .init(State())\n\n  public static func == (lhs: VergeAnyCancellable, rhs: VergeAnyCancellable) -> Bool {\n    lhs === rhs\n  }\n\n  public func hash(into hasher: inout Hasher) {\n    ObjectIdentifier(self).hash(into: &hasher)\n  }\n\n  public init() {\n  }\n\n  public convenience init(onDeinit: @escaping () -> Void) {\n    self.init()\n    state.withCriticalRegion { $0.actions = [onDeinit] }\n  }\n\n  public convenience init<C>(_ cancellable: C) where C : Cancellable {\n    self.init {\n      cancellable.cancel()\n    }\n  }\n\n  @discardableResult\n  public func associate(_ object: AnyObject) -> VergeAnyCancellable {\n    state.withCriticalRegion { state in\n      assert(!state.wasCancelled)\n      state.retainObjects.append(object)\n    }\n    return self\n  }\n\n  public func dissociate(_ object: AnyObject) {\n    let targets = state.withCriticalRegion { state -> [AnyObject] in\n      var targets: [AnyObject] = .init()\n      targets.reserveCapacity(state.retainObjects.count)\n      state.retainObjects.removeAll {\n        let remove = $0 === object\n        if remove {\n          targets.append($0)\n        }\n        return remove          \n      }\n      return targets\n    }\n    \n    guard targets.isEmpty == false else {\n      return\n    }\n\n    withExtendedLifetime(targets, {})\n  }\n\n  public func insert(_ cancellable: Cancellable) {\n    state.withCriticalRegion { state in\n      assert(!state.wasCancelled)\n      state.actions?.append {\n        cancellable.cancel()\n      }\n    }\n  }\n\n  public func insert(onDeinit: @escaping () -> Void) {\n    state.withCriticalRegion { state in\n      assert(!state.wasCancelled)\n      state.actions?.append(onDeinit)\n    }\n  }\n\n  deinit {\n    cancel()\n  }\n\n  public func cancel() {\n    let result = state.withCriticalRegion { state -> (\n      retainObjects: [AnyObject],\n      actions: ContiguousArray<() -> Void>?\n    )? in\n      guard !state.wasCancelled else {\n        return nil\n      }\n      \n      state.wasCancelled = true\n      \n      let retainObjects = state.retainObjects\n      state.retainObjects.removeAll()\n      \n      let actions = state.actions\n      state.actions = nil\n      \n      return (retainObjects, actions)\n    }\n    \n    guard let result else {\n      return\n    }\n    \n    withExtendedLifetime(result.retainObjects, {})\n    \n    result.actions?.forEach {\n      $0()\n    }\n  }\n}\n\n"
  },
  {
    "path": "Sources/Verge/Library/VergeConcurrency+SynchronizationTracker.swift",
    "content": "//\n// Copyright (c) 2020 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\nextension VergeConcurrency {\n  ///\n  ///\n  /// Modified based on RxSwift's original implementations.\n  public final class SynchronizationTracker: @unchecked Sendable {\n    \n    public enum Warning: Hashable {\n      case reentrancyAnomaly\n      case synchronizationAnomaly\n    }\n    \n    private let _lock = VergeConcurrency.RecursiveLock()\n    \n    private var _threads = [UnsafeMutableRawPointer: Int]()\n    \n    private let _isEnabled: Bool\n         \n    public init(debugOnly: Bool = false) {\n      if debugOnly {\n        #if DEBUG\n        self._isEnabled = true\n        #else\n        self._isEnabled = false\n        #endif\n      } else {\n        self._isEnabled = true\n      }\n    }\n    \n    /**\n     Marks as entering a synchronized operation.\n     */\n    @discardableResult\n    public func register(\n      _ file: StaticString = #file,\n      _ function: StaticString = #function,\n      _ line: UInt = #line,\n      printsConsole: Bool = false\n    ) -> Set<Warning> {\n      \n      guard _isEnabled else { return .init() }\n            \n      self._lock.lock(); defer { self._lock.unlock() }\n      \n      var flags = Set<Warning>()\n      \n      let pointer = Unmanaged.passUnretained(Thread.current).toOpaque()\n      let count = (self._threads[pointer] ?? 0) + 1\n      \n      if count > 1 {\n        flags.insert(.reentrancyAnomaly)\n      }\n      \n      self._threads[pointer] = count\n      \n      if self._threads.count > 1 {\n        flags.insert(.synchronizationAnomaly)\n      }\n      \n      if printsConsole, flags.isEmpty == false {\n        print(\"⚠️[SynchronizationTracker] Found issues \\(flags) in \\(file):\\(function):\\(line)\")\n      }\n      \n      return flags\n    }\n    \n    /**\n     Marks as exited a synchronized operation.\n     */\n    public func unregister() {\n      \n      guard _isEnabled else { return }\n      \n      self._lock.lock(); defer { self._lock.unlock() }\n      let pointer = Unmanaged.passUnretained(Thread.current).toOpaque()\n      self._threads[pointer] = (self._threads[pointer] ?? 1) - 1\n      if self._threads[pointer] == 0 {\n        self._threads[pointer] = nil\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "Sources/Verge/Library/VergeConcurrency.swift",
    "content": "//\n// Copyright (c) 2020 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\npublic enum VergeConcurrency {\n  \n  public final class RecursiveLock: NSRecursiveLock, @unchecked Sendable {\n    \n  }\n  \n  public struct UnfairLock: ~Copyable, @unchecked Sendable {\n    private let _lock: os_unfair_lock_t\n   \n    public init() {\n      _lock = .allocate(capacity: 1)\n      _lock.initialize(to: os_unfair_lock())\n    }\n\n    public func lock() {\n      os_unfair_lock_lock(_lock)\n    }\n\n    public func unlock() {\n      os_unfair_lock_unlock(_lock)\n    }\n\n    public func `try`() -> Bool {\n      return os_unfair_lock_trylock(_lock)\n    }\n\n    deinit {\n      _lock.deinitialize(count: 1)\n      _lock.deallocate()\n    }\n  }\n  \n  /// An atomic variable.\n  public final class RecursiveLockAtomic<Value>: @unchecked Sendable {\n    \n    public var unsafelyWrappedValue: Value {\n      _read { yield _value }\n    }\n    \n    private let lock: RecursiveLock\n    private var _value: Value\n    \n    /// Atomically get or set the value of the variable.\n    public var value: Value {\n      get {\n        return withValue { $0 }\n      }\n      \n      set(newValue) {\n        swap(newValue)\n      }\n    }\n    \n    /// Initialize the variable with the given initial value.\n    ///\n    /// - parameters:\n    ///   - value: Initial value for `self`.\n    public init(_ value: Value) {\n      _value = value\n      lock = .init()\n    }\n    \n    /// Atomically modifies the variable.\n    ///\n    /// - parameters:\n    ///   - action: A closure that takes the current value.\n    ///\n    /// - returns: The result of the action.\n    @discardableResult\n    public func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {\n      lock.lock()\n      defer { lock.unlock() }\n      \n      return try action(&_value)\n    }\n    \n    /// Atomically perform an arbitrary action using the current value of the\n    /// variable.\n    ///\n    /// - parameters:\n    ///   - action: A closure that takes the current value.\n    ///\n    /// - returns: The result of the action.\n    @discardableResult\n    public func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {\n      lock.lock()\n      defer { lock.unlock() }\n      \n      return try action(_value)\n    }\n    \n    /// Atomically replace the contents of the variable.\n    ///\n    /// - parameters:\n    ///   - newValue: A new value for the variable.\n    ///\n    /// - returns: The old value.\n    @discardableResult\n    public func swap(_ newValue: Value) -> Value {\n      return modify { (value: inout Value) in\n        let oldValue = value\n        value = newValue\n        return oldValue\n      }\n    }\n  }\n    \n  /// An atomic variable.\n  @propertyWrapper\n  public final class UnfairLockAtomic<Value>: @unchecked Sendable {\n    \n    public var unsafelyWrappedValue: Value {\n      _read { yield _value }\n    }\n    \n    private let lock: UnfairLock\n    private var _value: Value\n    \n    /// Atomically get or set the value of the variable.\n    public var value: Value {\n      get {\n        return withValue { $0 }\n      }\n      set(newValue) {\n        swap(newValue)\n      }\n    }\n\n    public var wrappedValue: Value {\n      get {\n        return withValue { $0 }\n      }\n      set(newValue) {\n        swap(newValue)\n      }\n    }\n\n    /// Initialize the variable with the given initial value.\n    ///\n    /// - parameters:\n    ///   - value: Initial value for `self`.\n    public init(_ wrappedValue: Value) {\n      _value = wrappedValue\n      lock = .init()\n    }\n\n    public init(wrappedValue: Value) {\n      _value = wrappedValue\n      lock = .init()\n    }\n\n    public var projectedValue: UnfairLockAtomic<Value> { self }\n\n    /// Atomically modifies the variable.\n    ///\n    /// - parameters:\n    ///   - action: A closure that takes the current value.\n    ///\n    /// - returns: The result of the action.\n    @discardableResult\n    public func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {\n      lock.lock()\n      defer { lock.unlock() }\n      \n      return try action(&_value)\n    }\n    \n    /// Atomically perform an arbitrary action using the current value of the\n    /// variable.\n    ///\n    /// - parameters:\n    ///   - action: A closure that takes the current value.\n    ///\n    /// - returns: The result of the action.\n    @discardableResult\n    public func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {\n      lock.lock()\n      defer { lock.unlock() }\n      \n      return try action(_value)\n    }\n    \n    /// Atomically replace the contents of the variable.\n    ///\n    /// - parameters:\n    ///   - newValue: A new value for the variable.\n    ///\n    /// - returns: The old value.\n    @discardableResult\n    public func swap(_ newValue: Value) -> Value {\n      return modify { (value: inout Value) in\n        let oldValue = value\n        value = newValue\n        return oldValue\n      }\n    }\n  }\n\n  /// A container that initializes value when it needs.\n  ///\n  /// Supports multi-threading.\n  @propertyWrapper\n  public final class AtomicLazy<T>: @unchecked Sendable {\n\n    private enum State {\n      case initialized(T)\n      case notInitialized\n    }\n\n    public typealias Initializer = () -> T\n\n    private var _onInitialized: (T) -> Void = { _ in }\n\n    private let lock: UnfairLock = .init()\n\n    public var wrappedValue: T {\n\n      lock.lock()\n      defer {\n        lock.unlock()\n      }\n\n      return unsafeValue\n    }\n\n    public var projectedValue: AtomicLazy<T> {\n      self\n    }\n\n    @discardableResult\n    public func modify<Result>(_ action: (inout T) throws -> Result) rethrows -> Result {\n      lock.lock()\n      defer { lock.unlock() }\n\n      var new = unsafeValue\n      let result = try action(&new)\n      self._synchronized_state = .initialized(new)\n      return consume result\n    }\n\n    private var _synchronized_state: State = .notInitialized\n\n    private var unsafeValue: T {\n      get {\n        switch _synchronized_state {\n        case .notInitialized:\n          let value = initializer()\n          _onInitialized(value)\n          self._synchronized_state = .initialized(value)\n          self.initializer = nil\n          return value\n        case .initialized(let value):\n          return value\n        }\n      }\n    }\n\n    private var initializer: Initializer!\n\n    public init(_ initializer: @escaping Initializer) {\n      self.initializer = initializer\n    }\n\n    public init(wrappedValue initializer: @autoclosure @escaping Initializer) {\n      self.initializer = initializer\n    }\n\n    /// Set closure on value initialized.\n    /// the closure would be called on thread which value initialized.\n    @discardableResult\n    public func onInitialized(_ perform: @escaping (T) -> Void) -> Self {\n      _onInitialized = perform\n      return self\n    }\n  }\n  \n  // From: https://github.com/apple/swift-async-algorithms/blob/4c3ea81f81f0a25d0470188459c6d4bf20cf2f97/Sources/AsyncAlgorithms/Locking.swift#L131 \n  struct ManagedCriticalState<State>: @unchecked Sendable {\n    \n    private final class LockedBuffer: ManagedBuffer<State, Lock.Primitive> {\n      deinit {\n        withUnsafeMutablePointerToElements { Lock.deinitialize($0) }\n      }\n    }\n    \n    private let buffer: ManagedBuffer<State, Lock.Primitive>\n    \n    init(_ initial: State) {\n      buffer = LockedBuffer.create(minimumCapacity: 1) { buffer in\n        buffer.withUnsafeMutablePointerToElements { Lock.initialize($0) }\n        return initial\n      }\n    }\n    \n    func withCriticalRegion<R>(_ critical: (inout State) throws -> R) rethrows -> R {\n      try buffer.withUnsafeMutablePointers { header, lock in\n        Lock.lock(lock)\n        defer { Lock.unlock(lock) }\n        return try critical(&header.pointee)\n      }\n    }\n  }\n  \n  internal struct Lock {\n#if canImport(Darwin)\n    typealias Primitive = os_unfair_lock\n#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic)\n    typealias Primitive = pthread_mutex_t\n#elseif canImport(WinSDK)\n    typealias Primitive = SRWLOCK\n#else\n#error(\"Unsupported platform\")\n#endif\n    \n    typealias PlatformLock = UnsafeMutablePointer<Primitive>\n    let platformLock: PlatformLock\n    \n    private init(_ platformLock: PlatformLock) {\n      self.platformLock = platformLock\n    }\n    \n    fileprivate static func initialize(_ platformLock: PlatformLock) {\n#if canImport(Darwin)\n      platformLock.initialize(to: os_unfair_lock())\n#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic)\n      let result = pthread_mutex_init(platformLock, nil)\n      precondition(result == 0, \"pthread_mutex_init failed\")\n#elseif canImport(WinSDK)\n      InitializeSRWLock(platformLock)\n#else\n#error(\"Unsupported platform\")\n#endif\n    }\n    \n    fileprivate static func deinitialize(_ platformLock: PlatformLock) {\n#if canImport(Glibc) || canImport(Musl) || canImport(Bionic)\n      let result = pthread_mutex_destroy(platformLock)\n      precondition(result == 0, \"pthread_mutex_destroy failed\")\n#endif\n      platformLock.deinitialize(count: 1)\n    }\n    \n    fileprivate static func lock(_ platformLock: PlatformLock) {\n#if canImport(Darwin)\n      os_unfair_lock_lock(platformLock)\n#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic)\n      pthread_mutex_lock(platformLock)\n#elseif canImport(WinSDK)\n      AcquireSRWLockExclusive(platformLock)\n#else\n#error(\"Unsupported platform\")\n#endif\n    }\n    \n    fileprivate static func unlock(_ platformLock: PlatformLock) {\n#if canImport(Darwin)\n      os_unfair_lock_unlock(platformLock)\n#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic)\n      let result = pthread_mutex_unlock(platformLock)\n      precondition(result == 0, \"pthread_mutex_unlock failed\")\n#elseif canImport(WinSDK)\n      ReleaseSRWLockExclusive(platformLock)\n#else\n#error(\"Unsupported platform\")\n#endif\n    }\n    \n    static func allocate() -> Lock {\n      let platformLock = PlatformLock.allocate(capacity: 1)\n      initialize(platformLock)\n      return Lock(platformLock)\n    }\n    \n    func deinitialize() {\n      Lock.deinitialize(platformLock)\n      platformLock.deallocate()\n    }\n    \n    func lock() {\n      Lock.lock(platformLock)\n    }\n    \n    func unlock() {\n      Lock.unlock(platformLock)\n    }\n    \n    /// Acquire the lock for the duration of the given block.\n    ///\n    /// This convenience method should be preferred to `lock` and `unlock` in\n    /// most situations, as it ensures that the lock will be released regardless\n    /// of how `body` exits.\n    ///\n    /// - Parameter body: The block to execute while holding the lock.\n    /// - Returns: The value returned by the block.\n    func withLock<T>(_ body: () throws -> T) rethrows -> T {\n      self.lock()\n      defer {\n        self.unlock()\n      }\n      return try body()\n    }\n    \n    // specialise Void return (for performance)\n    func withLockVoid(_ body: () throws -> Void) rethrows -> Void {\n      try self.withLock(body)\n    }\n  }\n\n}\n\n@inline(__always)\nfunc withUncheckedSendable<T>(_ body: () throws -> T) rethrows -> T {\n  try body()\n}\n"
  },
  {
    "path": "Sources/Verge/Library/_BackingStorage+.swift",
    "content": "\nextension _BackingStorage {\n  \n  func map<U>(_ transform: (borrowing Value) throws -> U) rethrows -> _BackingStorage<U> {\n    return .init(\n      try transform(value)\n    )\n  }\n  \n}\n\n"
  },
  {
    "path": "Sources/Verge/Logging/ActivityTrace.swift",
    "content": "//\n// Copyright (c) 2020 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\n/// A trace that indicates the activity where comes from.\npublic struct ActivityTrace: Encodable, Sendable {\n  \n  public let createdAt: Date = .init()\n  public let name: String\n  public let file: String\n  public let function: String\n  public let line: UInt\n  \n}\n"
  },
  {
    "path": "Sources/Verge/Logging/DefaultStoreLogger.swift",
    "content": "//\n// Copyright (c) 2019 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\nimport os\n\npublic struct CommitLog: Encodable, Sendable {\n\n  public let type: String = \"commit\"\n  public let tookMilliseconds: Double\n  public let traces: [MutationTrace]\n  public let store: String\n\n  public init(storeName: String, traces: [MutationTrace], time: CFTimeInterval) {\n    self.store = storeName\n    self.tookMilliseconds = time * 1000\n    self.traces = traces\n  }\n}\n\npublic struct ActivityLog: Encodable, Sendable {\n  \n  public let type: String = \"activity\"\n  public let trace: ActivityTrace\n  public let store: String\n\n  public init(storeName: String, trace: ActivityTrace) {\n    self.store = storeName\n    self.trace = trace\n  }\n}\n\npublic struct DidCreateDispatcherLog: Encodable, Sendable {\n  \n  public let type: String = \"did_create_dispatcher\"\n  public let store: String\n  public let dispatcher: String\n\n  public init(storeName: String, dispatcherName: String) {\n    self.store = storeName\n    self.dispatcher = dispatcherName\n  }\n  \n}\n\npublic struct DidDestroyDispatcherLog: Encodable, Sendable {\n  \n  public let type: String = \"did_destroy_dispatcher\"\n  public let store: String\n  public let dispatcher: String\n\n  public init(storeName: String, dispatcherName: String) {\n    self.store = storeName\n    self.dispatcher = dispatcherName\n  }\n  \n}\n\n/// An object default implementation of VergeStoreLogger.\n/// It uses `os_log` to print inside.\n/// There are OSLog object each type of action.\n/// You can turn off logging each OSLog object.\npublic struct DefaultStoreLogger: StoreLogger {\n  \n  public static var `default`: Self { \n    .init()\n  }\n  \n  public let commitLog = OSLog(subsystem: \"VergeStore\", category: \"Commit\")\n  public let activityLog = OSLog(subsystem: \"VergeStore\", category: \"Activity\")\n\n  public let dispatcherCreationLog = OSLog(subsystem: \"VergeStore\", category: \"Dispatcher_Creation\")\n  public let dispatcherDestructionLog = OSLog(subsystem: \"VergeStore\", category: \"Dispatcher_Destruction\")\n    \n  public init() {\n    \n  }\n  \n  private static let encoder: JSONEncoder = {\n    let encoder = JSONEncoder()\n    encoder.dateEncodingStrategy = .iso8601\n    if #available(iOS 11.0, macOS 10.13, tvOS 11, watchOS 4, *) {\n      encoder.outputFormatting = [.prettyPrinted, .sortedKeys]\n    } else {\n      encoder.outputFormatting = [.prettyPrinted]\n    }\n    return encoder\n  }()\n    \n  public func didCommit(log: CommitLog, sender: AnyObject) {\n    Task { [commitLog]in\n      let string = String(data: try! DefaultStoreLogger.encoder.encode(log), encoding: .utf8)!\n      os_log(\"%@\", log: commitLog, type: .default, string)\n    }\n  }\n  \n  public func didSendActivity(log: ActivityLog, sender: AnyObject) {\n    Task { [activityLog] in\n      let string = String(data: try! DefaultStoreLogger.encoder.encode(log), encoding: .utf8)!\n      os_log(\"%@\", log: activityLog, type: .default, string)\n    }\n  }\n   \n  public func didCreateDispatcher(log: DidCreateDispatcherLog, sender: AnyObject) {    \n    Task { [dispatcherCreationLog] in\n      let string = String(data: try! DefaultStoreLogger.encoder.encode(log), encoding: .utf8)!\n      os_log(\"%@\", log: dispatcherCreationLog, type: .default, string)\n    }\n  }\n  \n  public func didDestroyDispatcher(log: DidDestroyDispatcherLog, sender: AnyObject) {\n    Task { [dispatcherDestructionLog] in\n      let string = String(data: try! DefaultStoreLogger.encoder.encode(log), encoding: .utf8)!\n      os_log(\"%@\", log: dispatcherDestructionLog, type: .default, string)\n    }\n  }\n    \n}\n\n"
  },
  {
    "path": "Sources/Verge/Logging/MutationTrace.swift",
    "content": "//\n// Copyright (c) 2020 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\npublic protocol HasTraces {\n  var traces: [MutationTrace] { get }\n}\n\n/// A trace that indicates the mutation where comes from.\npublic struct MutationTrace: Encodable, Equatable, Sendable {\n  \n  public static func == (lhs: MutationTrace, rhs: MutationTrace) -> Bool {\n    lhs.createdAt == rhs.createdAt &&\n      lhs.name == rhs.name &&\n      lhs.file.description == rhs.file.description &&\n      lhs.function.description == rhs.function.description &&\n      lhs.line == rhs.line\n  }\n\n  public let createdAt: Date = .init()\n  public let name: String\n  public let file: StaticString\n  public let function: StaticString\n  public let line: UInt\n\n  public init(\n    name: String = \"\",\n    file: StaticString = #file,\n    function: StaticString = #function,\n    line: UInt = #line\n  ) {\n    self.name = name\n    self.file = file\n    self.function = function\n    self.line = line\n  }\n\n}\n\nextension StaticString: @retroactive Encodable {\n\n  public func encode(to encoder: Encoder) throws {\n    var container = encoder.singleValueContainer()\n    try container.encode(description)\n  }\n}\n"
  },
  {
    "path": "Sources/Verge/Logging/RuntimeError.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(muukii)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\npublic enum RuntimeError: Swift.Error {\n  \n  case recoveredStateFromReceivingOlderVersion(latestState: AnyChangesType, receivedState: AnyChangesType)\n  case recursiveleyCommit(storeName: String, traces: [MutationTrace])\n}\n"
  },
  {
    "path": "Sources/Verge/Logging/RuntimeSanitizer.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(muukii)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\npublic struct RuntimeSanitizer: Sendable {\n  \n  nonisolated(unsafe)\n  public static var global = RuntimeSanitizer()\n   \n  public var isSanitizerStateReceivingByCorrectOrder: Bool = false\n  public var isRecursivelyCommitDetectionEnabled: Bool = false\n  \n  public var onDidFindRuntimeError: @Sendable (RuntimeError) -> Void = { _ in }\n  \n  public init() {\n    \n  }\n}\n"
  },
  {
    "path": "Sources/Verge/Logging/StoreLogger.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(muukii)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\n/// A protocol to register logger and get the event VergeStore emits.\npublic protocol StoreLogger {\n  \n  func didCommit(log: CommitLog, sender: AnyObject)\n  func didSendActivity(log: ActivityLog, sender: AnyObject)\n\n  func didCreateDispatcher(log: DidCreateDispatcherLog, sender: AnyObject)\n  func didDestroyDispatcher(log: DidDestroyDispatcherLog, sender: AnyObject)\n  \n}\n\n"
  },
  {
    "path": "Sources/Verge/Sendable.swift",
    "content": "\nfinal class UnsafeSendableClass<T>: @unchecked Sendable {\n  var value: T\n  \n  init(_ value: T) {\n    self.value = value\n  }\n}\n\nstruct UnsafeSendableWeak<T: AnyObject>: @unchecked Sendable {\n  weak var value: T?\n  \n  init(_ value: T) {\n    self.value = value\n  }\n}\n\nstruct UnsafeSendableStruct<T: ~Copyable>: ~Copyable, @unchecked Sendable {\n  var value: T\n  \n  init(_ value: consuming T) {\n    self.value = value\n  }\n  \n  consuming func send() -> sending T {\n    return value    \n  }\n  \n  consuming func with<Return: ~Copyable>(_ mutation: (inout sending T) throws -> sending Return) rethrows -> sending Return {\n    try mutation(&value)\n  }\n}\n\nfunc withUnsafeSending<T: ~Copyable>(_ value: consuming T) -> sending T {\n  UnsafeSendableStruct(value).send()\n}\n"
  },
  {
    "path": "Sources/Verge/Store/AnyTargetQueue.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\nimport Atomics\n\npublic protocol TargetQueueType {\n  func execute(_ workItem: sending @escaping @Sendable () -> Void)\n}\n\n/// Describes queue to dispatch event\n/// Currently light-weight impl\n/// A reason why class is to take an object identifier.\npublic final class AnyTargetQueue: TargetQueueType {\n\n  private let _execute: (@escaping @Sendable () -> Void) -> Void\n\n  fileprivate init(\n    _execute: @escaping (@escaping @Sendable () -> Void) -> Void\n  ) {\n    self._execute = _execute\n  }\n\n  public func execute(_ workItem: @escaping @Sendable () -> Void) {\n    _execute(workItem)\n  }\n\n}\n\npublic protocol MainActorTargetQueueType {\n  func execute(_ workItem: @escaping @MainActor () -> Void)\n}\n\nextension MainActorTargetQueueType where Self == ImmediateMainActorTargetQueue {\n  public static func mainIsolated() -> Self {\n    .init()\n  }\n  \n  public static var main: Self {\n    .shared\n  }\n  \n}\n\nextension MainActorTargetQueueType where Self == HoppingMainActorTargetQueue {\n  \n  /// It dispatches to main-queue asynchronously always.\n  public static var asyncMain: Self {\n    return .init()\n  }\n}\n\n/// always dispatches to main-queue asynchronously\npublic struct HoppingMainActorTargetQueue: MainActorTargetQueueType {\n\n  init() {\n  }\n\n  public func execute(_ workItem: @escaping @MainActor () -> Void) {\n \n    DispatchQueue.main.async {\n      workItem()\n    }\n  }\n\n}\n\n/// It dispatches to main-queue as possible as synchronously. Otherwise, it dispatches asynchronously.\npublic struct ImmediateMainActorTargetQueue: Sendable, MainActorTargetQueueType {\n  \n  public static let shared = Self()\n\n  private let numberEnqueued = ManagedAtomic<UInt64>.init(0)\n  \n  init() {\n\n  }\n  \n  public func execute(_ workItem: @escaping @MainActor () -> Void) {\n          \n    let previousNumberEnqueued = numberEnqueued.loadThenWrappingIncrement(ordering: .sequentiallyConsistent)\n    \n    if Thread.isMainThread && previousNumberEnqueued == 0 {\n      MainActor.assumeIsolated {\n        workItem()\n      }\n      numberEnqueued.wrappingDecrement(ordering: .sequentiallyConsistent)\n    } else {\n      DispatchQueue.main.async {\n        workItem()\n        self.numberEnqueued.wrappingDecrement(ordering: .sequentiallyConsistent)\n      }\n    }\n    \n  }\n  \n}\n\nprivate enum StaticMember {\n\n  static let serialBackgroundDispatchQueue: DispatchQueue = .init(\n    label: \"org.verge.background\",\n    qos: .default,\n    attributes: [],\n    autoreleaseFrequency: .workItem,\n    target: nil\n  )\n\n}\n\nextension TargetQueueType where Self == Queues.Passthrough  {\n\n  /// Returns a instance that never dispatches.\n  /// The Sink use this targetQueue performs in the queue which the upstream commit dispatched.\n  public static var passthrough: Queues.Passthrough {\n    .init()\n  }\n\n}\n\nextension TargetQueueType where Self == Queues.AsyncBackground {\n  /// It dispatches to the serial background queue asynchronously.\n  public static var asyncSerialBackground: Self {\n    self.init()\n  }\n}\n\nextension TargetQueueType where Self == AnyTargetQueue {\n\n\n  /// Use specified queue, always dispatches\n  public static func specific(_ targetQueue: DispatchQueue) -> AnyTargetQueue {\n    return .init { workItem in\n      targetQueue.async(execute: workItem)\n    }\n  }\n\n\n  /// Enqueue first item on current-thread(synchronously).\n  /// From then, using specified queue.\n  public static func startsFromCurrentThread(andUse queue: some TargetQueueType) -> AnyTargetQueue {\n    let numberEnqueued = ManagedAtomic<Bool>.init(true)\n\n    let execute = queue.execute\n\n    return .init { workItem in\n\n      let isFirst = numberEnqueued.loadThenLogicalAnd(with: false, ordering: .relaxed)\n\n      if isFirst {\n        workItem()\n      } else {\n        execute(workItem)\n      }\n\n    }\n  }\n\n  /// Enqueue first item on current-thread(synchronously).\n  /// From then, using specified queue.\n  public static func startsFromCurrentThread(andUse queue: some MainActorTargetQueueType) -> AnyTargetQueue {\n    return startsFromCurrentThread(andUse: Queues.MainActor(queue))\n  }\n\n}\n\nextension HoppingMainActorTargetQueue {\n\n  /// It dispatches to main-queue asynchronously always.\n  public static var asyncMain: HoppingMainActorTargetQueue {\n    return .init()\n  }\n\n  /// It dispatches to main-queue as possible as synchronously. Otherwise, it dispatches asynchronously from other background-thread.\n  public static var main: ImmediateMainActorTargetQueue {\n    return .shared\n  }\n\n  /// It dispatches to main-queue as possible as synchronously. Otherwise, it dispatches asynchronously from other background-thread.\n  /// This create isolated queue against using `.main`.\n  public static func mainIsolated() -> ImmediateMainActorTargetQueue {\n    return .init()\n  }\n}\n\npublic enum Queues {\n\n  struct MainActor<Underlying: MainActorTargetQueueType>: TargetQueueType {\n\n    let underlying: Underlying\n\n    init(_ underlying: Underlying) {\n      self.underlying = underlying\n    }\n\n    public func execute(_ workItem: sending @escaping @Sendable () -> Void) {\n      underlying.execute(workItem)\n    }\n\n  }\n\n  public struct Passthrough: TargetQueueType {\n\n    public func execute(_ workItem: sending @escaping @Sendable () -> Void) {\n      workItem()\n    }\n\n  }\n\n  public struct AsyncBackground: TargetQueueType {\n\n    private let executor: BackgroundActor = .init()\n\n    public func execute(_ workItem: sending @escaping @Sendable () -> Void) {\n      Task { [executor, workItem] in\n        await executor.perform(workItem)\n      }\n    }\n    \n    private actor BackgroundActor: Actor {\n\n      init() {\n\n      }\n          \n      func perform<R>(_ operation: sending @Sendable () throws -> R) rethrows -> R {\n        try operation()\n      }\n          \n    }\n\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Store/Changes.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n@_spi(Internal) import TypedComparator\nimport StateStruct\n\nprivate let _shared_changesDeallocationQueue = BackgroundDeallocationQueue()\n\npublic protocol AnyChangesType: AnyObject, Sendable {\n\n  var traces: [MutationTrace] { get }\n  var version: UInt64 { get }\n}\n\npublic protocol ChangesType<Value>: AnyChangesType {\n  \n  associatedtype Value\n  \n  var previousPrimitive: Value? { get }\n  var primitive: Value { get }\n\n  var previous: Self? { get }\n  \n  var modification: Modification? { get }\n\n  func asChanges() -> Changes<Value>\n}\n\n/// An immutable data object to achieve followings:\n/// - To know a property has been modified. (It contains 2 instances (old, new))\n/// - To avoid copying cost with wrapping reference type - So, you can embed this object on the other state.\n///\n/// ```swift\n/// struct MyState: Equatable {\n///   var name: String\n///   var age: String\n///   var height: String\n/// }\n/// ```\n///\n/// ```swift\n/// let changes: Changes<MyState>\n/// ```\n///\n/// It can be accessed with properties of MyState by dynamicMemberLookup\n/// ```swift\n/// changes.name\n/// ```\n///\n/// It would be helpful to update UI partially\n/// ```swift\n/// func updateUI(changes: Changes<MyState>) {\n///\n///   changes.ifChanged(\\.name) { name in\n///   // update UI\n///   }\n///\n///   changes.ifChanged(\\.age) { age in\n///   // update UI\n///   }\n///\n///   changes.ifChanged(\\.height) { height in\n///   // update UI\n///   }\n/// }\n/// ```\n///\n/// - Attention: Equalities calculates with pointer-personality basically, if the Value type compatibles `Equatable`, it does using also Value's equalities.\n/// This means Changes will return equals if different pointer but the value is the same.\n@dynamicMemberLookup\npublic final class Changes<Value>: @unchecked Sendable, ChangesType, Equatable, HasTraces {\n  \n  public typealias ChangesKeyPath<T> = KeyPath<Value, T>\n\n  public static func == (lhs: Changes<Value>, rhs: Changes<Value>) -> Bool {\n    lhs === rhs\n  }\n\n  // MARK: - Stored Properties\n\n  public let previous: Changes<Value>?\n  \n  private let innerBox: InnerBox\n  \n  public private(set) var version: UInt64\n\n  // MARK: - Computed Properties\n\n  @available(*, deprecated, renamed: \"previousPrimitive\")\n  public var old: Value? { previousPrimitive }\n\n  @available(*, deprecated, renamed: \"primitive\")\n  public var current: Value { primitive }\n\n  /// Returns a previous value as primitive\n  /// - Important: a returns value won't change against pointer-personality\n  public var previousPrimitive: Value? { _read { yield previous?.primitive } }\n\n  /// Returns a value as primitive\n  /// - Important: a returns value won't change against pointer-personality\n  public var primitive: Value { _read { yield innerBox.value } }\n\n  public var primitiveBox: InnerBox { innerBox }\n\n  /// Returns a value as primitive\n  /// - Important: a returns value won't change against pointer-personality\n  public var root: Value { _read { yield innerBox.value } }\n\n  public let traces: [MutationTrace]\n  \n  public let modification: Modification?\n    \n  public let _transaction: Transaction\n\n  // MARK: - Initializers\n\n  public convenience init(\n    old: consuming Value?,\n    new: consuming Value\n  ) {\n    self.init(\n      previous: old.map { .init(old: nil, new: $0) },\n      innerBox: .init(consume new),\n      version: 0,\n      traces: [],\n      modification: nil,\n      transaction: .init()\n    )\n  }\n\n  private init(\n    previous: Changes<Value>?,\n    innerBox: InnerBox,\n    version: UInt64,\n    traces: [MutationTrace],\n    modification: consuming Modification?,\n    transaction: Transaction\n  ) {\n    self.previous = previous\n    self.innerBox = innerBox\n    self.version = version\n    self.traces = traces\n    self.modification = modification\n    self._transaction = transaction\n\n    vergeSignpostEvent(\"Changes.init\", label: \"\\(type(of: self))\")\n  }\n\n  deinit {\n    vergeSignpostEvent(\"Changes.deinit\", label: \"\\(type(of: self))\")\n    \n    let unsafeBox = UnsafeSendableStruct(innerBox)\n    \n    Task {\n      await _shared_changesDeallocationQueue.releaseObjectInBackground(object: unsafeBox.value)\n    }\n  }\n\n  @inline(__always)\n  private func cloneWithDropsPrevious() -> Changes<Value> {\n    return .init(\n      previous: nil,\n      innerBox: innerBox,\n      version: version,\n      traces: traces,\n      modification: nil,\n      transaction: _transaction\n    )\n  }\n\n  func replacePrevious(_ previous: Changes<Value>) -> Changes<Value> {\n    return .init(\n      previous: previous,\n      innerBox: innerBox,\n      version: version,\n      traces: traces,\n      modification: nil,\n      transaction: _transaction\n    )\n  }\n\n  @inlinable\n  public func asChanges() -> Changes<Value> {\n    self\n  }\n\n  /// Returns a Changes object that dropped previous value.\n  /// It returns always true in `ifChanged`\n  public func droppedPrevious() -> Changes<Value> {\n    cloneWithDropsPrevious()\n  }\n\n  @inlinable\n  public subscript<T>(dynamicMember keyPath: KeyPath<Value, T>) -> T {\n    _read {\n      yield primitive[keyPath: keyPath]\n    }\n  }\n\n  /// Returns a new instance that projects value by transform closure.\n  ///\n  /// - Warning: modification would be dropped.\n  public func map<U>(_ transform: (borrowing Value) throws -> U) rethrows -> Changes<U> {\n    let signpost = VergeSignpostTransaction(\"Changes.map\")\n    defer {\n      signpost.end()\n    }\n\n    return Changes<U>(\n      previous: try previous.map { try $0.map(transform) },\n      innerBox: try innerBox.map(transform),\n      version: version,\n      traces: traces,\n      modification: modification,\n      transaction: _transaction\n    )\n  }\n\n  /**\n   Returns an ``Changes`` containing the value of mapping the given key path over the root value if value present.\n   */\n  public func mapIfPresent<U>(_ keyPath: KeyPath<Value, U?>) -> Changes<U>? {\n\n    guard self[dynamicMember: keyPath] != nil else {\n      return nil\n    }\n\n    return Changes<U>(\n      previous: previous.flatMap { $0.mapIfPresent(keyPath) },\n      innerBox: innerBox.map { $0[keyPath: keyPath]! },\n      version: version,\n      traces: traces,\n      modification: nil,\n      transaction: _transaction\n    )\n\n  }\n\n  /**\n   Returns an ``Changes`` containing the value of mapping the given key path over the root value if value present.\n   */\n  @available(*, deprecated, renamed: \"mapIfPresent\")\n  public func _beta_map<U>(_ keyPath: KeyPath<Value, U?>) -> Changes<U>? {\n    mapIfPresent(keyPath)\n  }\n\n  public func makeNextChanges(\n    with nextNewValue: Value,\n    modification: Modification?,\n    transaction: Transaction\n  ) -> Changes<Value> {\n    let previous = cloneWithDropsPrevious()\n    let nextVersion = previous.version &+ 1\n    return Changes<Value>.init(\n      previous: previous,\n      innerBox: .init(nextNewValue),\n      version: nextVersion,\n      traces: traces,\n      modification: modification,\n      transaction: transaction\n    )\n  }\n\n  @discardableResult\n  public func _read<Return>(perform: (borrowing Value) -> Return) -> Return {\n    perform(innerBox.value)\n  }\n\n}\n\n// MARK: - Primitive methods\n\nextension Changes {\n  \n  /// Takes a composed value if it's changed from old value.\n  @inline(__always)\n  public func takeIfChanged<Composed>(\n    _ compose: (Value) throws -> Composed,\n    _ comparer: some TypedComparator<Composed>\n  ) rethrows -> Composed? {\n    try _takeIfChanged(compose, comparer)\n  }\n\n  @inline(__always)\n  fileprivate func _takeIfChanged<each Element>(\n    _ compose: (Value) throws -> (repeat each Element),\n    _ comparer: consuming some TypedComparator<(repeat each Element)>\n  ) rethrows -> (repeat each Element)? {\n\n    let current = self.primitive\n\n    guard let previousValue = previous else {\n      return try compose(consume current)\n    }\n\n    let old = previousValue.primitive\n\n    let composedFromCurrent = try compose(consume current)\n    guard !comparer(try compose(consume old), composedFromCurrent) else {\n      return nil\n    }\n\n    return composedFromCurrent\n\n  }\n\n  @inline(__always)\n  fileprivate func _takeIfChanged_packed<each Element: Equatable>(\n    _ compose: (Value) throws -> (repeat each Element)\n  ) rethrows -> (repeat each Element)? {\n\n    let current = self.primitive\n\n    guard let previousValue = previous else {\n      return try compose(consume current)\n    }\n\n    let old = previousValue.primitive\n\n    let composedFromCurrent = try compose(consume current)\n    let composedFromOld = try compose(old)\n\n    guard !areEqual(\n      (repeat each composedFromOld),\n      (repeat each composedFromCurrent)\n    ) else {\n      return nil\n    }\n\n    return composedFromCurrent\n\n  }\n\n  @inline(__always)\n  fileprivate func _takeIfChanged_packed_nonEquatable<each Element>(\n    _ compose: (Value) throws -> (repeat each Element),\n    comparator: some TypedComparator<(repeat each Element)>\n  ) rethrows -> (repeat each Element)? {\n\n    let current = self.primitive\n\n    guard let previousValue = previous else {\n      return try compose(consume current)\n    }\n\n    let old = previousValue.primitive\n\n    let composedFromCurrent = try compose(consume current)\n    let composedFromOld = try compose(old)\n\n    let isEqual = comparator(composedFromOld, composedFromCurrent)\n\n    guard isEqual == false else {\n      return nil\n    }\n\n    return composedFromCurrent\n\n  }\n\n  /// Performs a closure if the selected value changed from the previous one.\n  ///\n  /// - Parameters:\n  ///   - compose: A closure that projects a composed value from self. that executes with both of value(new and old).\n  ///   - comparer: A Comparer that checks if the composed values are different between current and old.\n  ///   - perform: A closure that executes any operation if composed value changed.\n  ///\n  /// - Returns: An instance that returned from the perform closure if performed.\n  @inline(__always)\n  public func ifChanged<Composed, Result>(\n    _ compose: (Value) -> Composed,\n    _ comparer: some TypedComparator<Composed>,\n    _ perform: (Composed) throws -> Result\n  ) rethrows -> Result? {\n    guard let result = takeIfChanged(compose, comparer) else {\n      return nil\n    }\n\n    return try perform(result)\n  }\n}\n\n// MARK: - Convenience methods\n\nextension Changes {\n  /// Takes a composed value if it's changed from old value.\n  @inline(__always)\n  public func takeIfChanged<Composed: Equatable>(\n    _ compose: (Value) throws -> Composed\n  ) rethrows -> Composed? {\n    try takeIfChanged(compose, .equality())\n  }\n\n  public func ifChanged<Composed: Equatable>(\n    _ compose: (Value) -> Composed\n  ) -> IfChangedBox<Value, Composed> {\n    guard let result = takeIfChanged(compose) else {\n      return .init()\n    }\n\n    return .init(value: consume result, source: innerBox)\n  }\n\n  /**\n   Packed\n\n   ```\n   state.ifChanged({ $0.name }).do { value in\n     ...\n   }\n   ```\n   */\n  public borrowing func ifChanged<each Element: Equatable>(\n    _ compose: (borrowing Value) -> (repeat each Element)\n  ) -> IfChangedBox<Value, (repeat each Element)> {\n    guard let result = _takeIfChanged_packed(compose) else {\n      return .init()\n    }\n\n    return .init(value: (repeat each result), source: innerBox)\n  }\n\n  public borrowing func ifChanged<each Element>(\n    _ compose: (borrowing Value) -> (repeat each Element),\n    comparator: some TypedComparator<(repeat each Element)>\n  ) -> IfChangedBox<Value, (repeat each Element)> {\n    guard let result = _takeIfChanged_packed_nonEquatable(compose, comparator: comparator) else {\n      return .init()\n    }\n\n    return .init(value: (repeat each result), source: innerBox)\n  }\n\n  /**\n   singular variant\n   */\n  public func ifChanged<T: Equatable>(\n    _ keyPath: KeyPath<Value, T>\n  ) -> IfChangedBox<Value, T> {\n    ifChanged({ $0[keyPath: keyPath] })\n  }\n\n  /**\n   multiple variant\n   */\n  public func ifChanged<each T: Equatable>(\n    _ keyPaths: repeat KeyPath<Value, each T>\n  ) -> IfChangedBox<Value, (repeat each T)> {\n    ifChanged({ (repeat $0[keyPath: each keyPaths]) })\n  }\n \n}\n\n// MARK: - Has changes\n\nextension Changes {\n  /// Returns boolean that indicates value specified by keyPath contains changes with compared old and new.\n  @inline(__always)\n  public func hasChanges<T: Equatable>(_ keyPath: ChangesKeyPath<T>) -> Bool {\n    hasChanges(keyPath, EqualityComparator())\n  }\n\n  /// Returns boolean that indicates value specified by keyPath contains changes with compared old and new.\n  @inline(__always)\n  public func hasChanges<T>(\n    _ keyPath: ChangesKeyPath<T>,\n    _ comparer: some TypedComparator<T>\n  ) -> Bool {\n    hasChanges({ $0[keyPath: keyPath] }, comparer)\n  }\n\n  @inline(__always)\n  public func hasChanges<Composed: Equatable>(\n    _ compose: (Value) -> Composed\n  ) -> Bool {\n    hasChanges(compose, EqualityComparator())\n  }\n\n  @inline(__always)\n  public func hasChanges<Composed>(\n    _ compose: (Value) -> Composed,\n    _ comparer: some TypedComparator<Composed>\n  ) -> Bool {\n    takeIfChanged(compose, comparer) != nil\n  }\n\n}\n\n// MARK: - NoChanges\n\nextension Changes {\n  /// Returns boolean that indicates value specified by keyPath contains **NO** changes with compared old and new.\n  @inline(__always)\n  public func noChanges<T: Equatable>(_ keyPath: ChangesKeyPath<T>) -> Bool {\n    !hasChanges(keyPath, EqualityComparator())\n  }\n\n  /// Returns boolean that indicates value specified by keyPath contains **NO** changes with compared old and new.\n  @inline(__always)\n  public func noChanges<T>(_ keyPath: ChangesKeyPath<T>, _ comparer: some TypedComparator<T>) -> Bool {\n    !hasChanges(keyPath, comparer)\n  }\n}\n\nextension Changes: CustomReflectable {\n  public var customMirror: Mirror {\n    Mirror(\n      self,\n      children: [\n        \"version\": version,\n        \"previous\": previous as Any,\n        \"primitive\": primitive,\n        \"transaction\": _transaction,\n        \"traces\": traces,\n        \"modification\": modification as Any,\n      ],\n      displayStyle: .struct,\n      ancestorRepresentation: .generated\n    )\n  }\n}\n\n// MARK: - Nested Types\n\nextension Changes {\n\n  public typealias InnerBox = _BackingStorage<Value>\n\n}\n\nextension Changes where Value: Equatable {\n  public var hasChanges: Bool {\n    previousPrimitive != primitive\n  }\n\n  public func ifChanged() -> IfChangedBox<Value, Value> {\n    ifChanged({ $0 })\n  }\n\n}\n\npublic struct IfChangedBox<Source, T>: ~Copyable {\n\n  public let value: T?\n  \n  @usableFromInline\n  let source: Changes<Source>.InnerBox?\n\n  init(value: consuming T, source: Changes<Source>.InnerBox) {\n    self.value = consume value\n    self.source = source\n  }\n\n  init() {\n    self.value = nil  \n    self.source = nil\n  }\n\n  @discardableResult\n  @inlinable\n  public consuming func `do`<Return>(_ perform: (consuming T) throws -> Return) rethrows -> Return? {\n    if let value {\n      return try perform(consume value)\n    }\n    return nil\n  }\n  \n  @discardableResult\n  @inlinable\n  public consuming func doWithSource<Return>(_ perform: (consuming Changes<Source>.InnerBox) throws -> Return) rethrows -> Return? {\n    if let source {\n      return try perform(source)\n    }\n    return nil\n  }\n}\n\n"
  },
  {
    "path": "Sources/Verge/Store/DetachedDispatcher.swift",
    "content": "//\n// Copyright (c) 2019 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\npublic final class DetachedDispatcher<State, Activity: Sendable, Scope>: StoreDriverType\n{\n\n  public let store: Store<State, Activity>\n  public let scope: WritableKeyPath<State, Scope> & Sendable\n\n  init(\n    store: Store<State, Activity>,\n    scope: WritableKeyPath<State, Scope> & Sendable\n  ) {\n    self.store = store\n    self.scope = scope\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Store/KeyObject.swift",
    "content": "\nimport Foundation\n\n@_spi(Internal)\npublic final class KeyObject<Content: Hashable>: NSObject, NSCopying {\n\n  public func copy(with zone: NSZone? = nil) -> Any {\n    return KeyObject(content: content)\n  }\n\n  public let content: Content\n\n  public init(content: consuming Content) {\n    self.content = content\n  }\n\n  public override var hash: Int {\n    content.hashValue\n  }\n\n  public override func isEqual(_ object: Any?) -> Bool {\n\n    guard let other = object as? KeyObject<Content> else {\n      return false\n    }\n\n    guard content == other.content else { return false }\n\n    return true\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Store/NonAtomicCounter.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\n/// A container that manages raw value to describe mark as updated.\npublic struct NonAtomicCounter: Hashable, Sendable {\n  \n  private(set) public var value: UInt64 = 0\n  \n  public init() {}\n  \n  public mutating func increment() {\n    value &+= 1\n  }\n  \n}\n"
  },
  {
    "path": "Sources/Verge/Store/Pipeline.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\nimport TypedComparator\n\npublic enum ContinuousResult<Output> {\n  case new(Output)\n  case noUpdates\n}\n\nextension ContinuousResult: Equatable where Output: Equatable {\n\n}\n\n/// A filter object that yields the output produced from the input.\npublic protocol PipelineType<Input, Output>: Sendable {\n\n  associatedtype Input\n  associatedtype Output\n  associatedtype Storage = Void\n\n  func makeStorage() -> Storage\n\n  /// Yields the output from the input.\n  func yield(_ input: Input, storage: inout Storage) -> Output\n\n  /// Yields the output from the input if it's needed\n  func yieldContinuously(_ input: Input, storage: inout Storage) -> ContinuousResult<Output>\n\n}\n\nextension PipelineType where Storage == Void {\n  public func makeStorage() {\n    ()\n  }\n}\n\n/// It produces outputs from inputs with their own conditions.\n///\n/// Against just using map closure, it can drop output if there are no changes.\n/// This will be helpful in performance. Therefore most type parameters require Equatable.\npublic enum Pipelines {\n\n  /// KeyPath based pipeline, light weight operation just take value from source.\n  public struct ChangesSelectPassthroughPipeline<Source, Output>: PipelineType {\n\n    public typealias Storage = Void\n\n    public typealias Input = Changes<Source>\n\n    public let selector: @Sendable (borrowing Input.Value) -> Output\n\n    public init(\n      selector: @escaping @Sendable (borrowing Input.Value) -> Output\n    ) {\n      self.selector = selector\n    }\n\n    public func yieldContinuously(_ input: Input, storage: inout Storage) -> ContinuousResult<Output> {\n\n      let target = input._read(perform: selector)\n\n      return .new(consume target)\n\n    }\n\n    public func yield(_ input: Input, storage: inout Storage) -> Output {\n      input._read(perform: selector)\n    }\n\n  }\n\n  /// KeyPath based pipeline, light weight operation just take value from source.\n  public struct ChangesSelectPipeline<Source, Output: Equatable>: PipelineType {\n\n    public typealias Input = Changes<Source>\n\n    public let selector: @Sendable (borrowing Input.Value) -> Output\n    public let additionalDropCondition: (@Sendable (Input) -> Bool)?\n\n    public init(\n      selector: @escaping @Sendable (borrowing Input.Value) -> Output,\n      additionalDropCondition: (@Sendable (Input) -> Bool)?\n    ) {\n      self.selector = selector\n      self.additionalDropCondition = additionalDropCondition\n    }\n\n    public func yieldContinuously(_ input: Input, storage: inout Storage) -> ContinuousResult<Output> {\n\n      guard let previous = input.previous else {\n        return .new(input._read(perform: selector))\n      }\n\n      let target = input._read(perform: selector)\n\n      guard\n        previous._read(perform: selector) == target\n      else {\n\n        guard let additionalDropCondition = additionalDropCondition, additionalDropCondition(input)\n        else {\n          return .new(consume target)\n        }\n\n        return .noUpdates\n      }\n\n      return .noUpdates\n\n    }\n\n    public func yield(_ input: Input, storage: inout Storage) -> Output {\n      input._read(perform: selector)\n    }\n\n    public func drop(while predicate: @escaping @Sendable (Input) -> Bool) -> Self {\n      return .init(\n        selector: selector,\n        additionalDropCondition: additionalDropCondition.map { currentCondition in\n          { input in\n            currentCondition(input) || predicate(input)\n          }\n        } ?? predicate\n      )\n    }\n\n  }\n  \n  /// Closure based pipeline,\n  public struct ChangesMapPipeline<Source, Intermediate, Output: Equatable>: PipelineType {\n\n    public typealias Storage = Void\n\n    public typealias Input = Changes<Source>\n\n    // MARK: - Properties\n\n    public let intermediate: @Sendable (Input.Value) -> PipelineIntermediate<Intermediate>\n    public let transform: @Sendable (Intermediate) -> Output\n    public let additionalDropCondition: (@Sendable (Input) -> Bool)?\n\n    public init(\n      @PipelineIntermediateBuilder intermediate: @escaping @Sendable (\n        Input.Value\n      ) -> PipelineIntermediate<Intermediate>,\n      transform: @escaping @Sendable (Intermediate) -> Output,\n      additionalDropCondition: (@Sendable (Input) -> Bool)?\n    ) {\n      self.intermediate = intermediate\n      self.transform = transform\n      self.additionalDropCondition = additionalDropCondition\n    }\n\n    // MARK: - Functions\n\n    public func yieldContinuously(_ input: Input, storage: inout Storage) -> ContinuousResult<Output> {\n\n      guard let previous = input.previous else {\n        return .new(yield(input, storage: &storage))\n      }\n\n      let previousIntermediate = intermediate(previous.primitive)\n      let newIntermediate = intermediate(input.primitive)\n\n      guard previousIntermediate == newIntermediate else {\n\n        let previousMapped = transform(previousIntermediate.value)\n        let newMapped = transform(newIntermediate.value)\n\n        guard previousMapped == newMapped else {\n\n          guard let additionalDropCondition = additionalDropCondition,\n            additionalDropCondition(input)\n          else {\n            return .new(newMapped)\n          }\n\n          return .noUpdates\n        }\n\n        return .noUpdates\n      }\n\n      return .noUpdates\n\n    }\n\n    public func yield(_ input: Input, storage: inout Storage) -> Output {\n      transform(intermediate(input.primitive).value)\n    }\n\n    public func drop(while predicate: @escaping @Sendable (Input) -> Bool) -> Self {\n      return .init(\n        intermediate: intermediate,\n        transform: transform,\n        additionalDropCondition: additionalDropCondition.map { currentCondition in\n          { input in\n            currentCondition(input) || predicate(input)\n          }\n        } ?? predicate\n      )\n    }\n  }\n\n  public struct UniqueFilterEquatable<Map: MapFunction>: PipelineType where Map.Output: Equatable {\n\n    public typealias Input = Map.Input\n    public typealias Output = Map.Output\n\n    private let map: Map\n\n    public init(map: Map) {\n      self.map = map\n    }\n\n    public func makeStorage() -> VergeConcurrency.UnfairLockAtomic<Output?> {\n      .init(nil)\n    }\n\n    public func yield(_ input: Input, storage: inout Storage) -> Output {\n      let result = map.perform(input)\n      storage.swap(result)\n      return result\n    }\n\n    public func yieldContinuously(_ input: Input, storage: inout Storage) -> ContinuousResult<Output> {\n\n      // not to check if input has changed because storing the input may cause performance issue by copying.\n\n      let result = map.perform(input)\n\n      return storage.modify { value in\n        if value != result {\n          value = result\n          return .new(result)\n        } else {\n          return .noUpdates\n        }\n      }\n    }\n\n  }\n\n  public struct UniqueFilter<Map: MapFunction, OutputComparator: TypedComparator>: PipelineType\n  where OutputComparator.Input == Map.Output? {\n\n    public typealias Input = Map.Input\n    public typealias Output = Map.Output\n\n    private let map: Map\n    private let outputComparator: OutputComparator\n\n    public init(map: Map, outputComparator: OutputComparator) {\n      self.map = map\n      self.outputComparator = outputComparator\n    }\n\n    public func makeStorage() -> VergeConcurrency.UnfairLockAtomic<Output?> {\n      .init(nil)\n    }\n\n    public func yield(_ input: Input, storage: inout Storage) -> Output {\n      let result = map.perform(input)\n      storage.swap(result)\n      return result\n    }\n\n    public func yieldContinuously(_ input: Input, storage: inout Storage) -> ContinuousResult<Output> {\n\n      // not to check if input has changed because storing the input may cause performance issue by copying.\n\n      let result = map.perform(input)\n\n      return storage.modify { value in\n        if !outputComparator(value, result) {\n          value = result\n          return .new(result)\n        } else {\n          return .noUpdates\n        }\n      }\n    }\n\n  }\n\n}\n\npublic protocol MapFunction: Sendable {\n  associatedtype Input\n  associatedtype Output\n  func perform(_ input: Input) -> Output\n}\n\npublic struct AnyMapFunction<Input, Output>: MapFunction {\n\n  private let _perform: @Sendable (Input) -> Output\n\n  public init(_ perform: @escaping @Sendable (Input) -> Output) {\n    self._perform = perform\n  }\n\n  public func perform(_ input: Input) -> Output {\n    _perform(input)\n  }\n}\n\nextension PipelineType {\n\n  public static func uniqueMap<Map: MapFunction>(_ mapFunction: Map) -> Self\n  where Map.Output: Equatable, Self == Pipelines.UniqueFilterEquatable<Map> {\n    return .init(map: mapFunction)\n  }\n\n  public static func uniqueMap<Input, Output: Equatable>(\n    _ map: @escaping @Sendable (Input) -> Output\n  ) -> Self\n  where Output: Equatable, Self == Pipelines.UniqueFilterEquatable<AnyMapFunction<Input, Output>> {\n    return uniqueMap(.init(map))\n  }\n\n  public static func uniqueMap<Map: MapFunction, OutputComparator: TypedComparator>(\n    _ mapFunction: Map, _ outputComparator: OutputComparator\n  ) -> Self\n  where Self == Pipelines.UniqueFilter<Map, OutputComparator> {\n    return .init(map: mapFunction, outputComparator: outputComparator)\n  }\n\n  public static func uniqueMap<Input, Output, OutputComparator: TypedComparator>(\n    _ map: @escaping @Sendable (Input) -> Output, _ outputComparator: OutputComparator\n  ) -> Self\n  where Self == Pipelines.UniqueFilter<AnyMapFunction<Input, Output>, OutputComparator> {\n    return .init(map: .init(map), outputComparator: outputComparator)\n  }\n\n}\n\nextension PipelineType {\n\n  /**\n   For Changes input\n   Produces output values using KeyPath-based projection.\n\n   exactly same with ``PipelineType/select(_:)``\n   */\n  public static func map<Input, Output>(\n    _ selector: @escaping @Sendable (\n      borrowing Input\n    ) -> Output\n  ) -> Self\n  where Output: Equatable, Self == Pipelines.ChangesSelectPipeline<Input, Output> {\n    self.init(selector: selector, additionalDropCondition: nil)\n  }\n\n  /**\n   For Changes input\n   Produces output values using KeyPath-based projection.\n\n   exactly same with ``PipelineType/select(_:)``\n   */\n  public static func map<Input, Output>(\n    _ selector: @escaping @Sendable (\n      borrowing Input\n    ) -> Output\n  ) -> Self\n  where Self == Pipelines.ChangesSelectPassthroughPipeline<Input, Output> {\n    self.init(selector: selector)\n  }\n\n  /**\n   For Changes input\n   Produces output values using closure based projection.\n\n   exactly same with ``PipelineType/map(_:)-7xvom``\n   */\n  // needs this overload as making closure from keyPath will not make sendable closure.\n  public static func map<Input, Output>(\n    _ selector: KeyPath<Input, Output> & Sendable\n  ) -> Self\n  where Output: Equatable, Self == Pipelines.ChangesSelectPipeline<Input, Output> {\n    self.init(selector: { $0[keyPath: selector] }, additionalDropCondition: nil)\n  }\n\n  /**\n   For Changes input\n   Produces output values using closure based projection.\n\n   exactly same with ``PipelineType/map(_:)-7xvom``\n   */\n  public static func select<Input, Output: Equatable>(\n    _ selector: KeyPath<Input, Output> & Sendable\n  ) -> Self\n  where Output: Equatable, Self == Pipelines.ChangesSelectPipeline<Input, Output> {\n    self.init(selector: { $0[keyPath: selector] }, additionalDropCondition: nil)\n  }\n  \n  /**\n   For Changes input\n   Produces output values using closure based projection.\n   \n   exactly same with ``PipelineType/map(_:)-7xvom``\n   */\n  public static func select<Input, Output>(\n    _ selector: KeyPath<Input, Output> & Sendable\n  ) -> Self\n  where Self == Pipelines.ChangesSelectPassthroughPipeline<Input, Output> {\n    self.init(selector: { $0[keyPath: selector] })\n  }\n  \n}\n\nextension PipelineType {\n\n  /**\n   For Changes input\n   Produces output values using closure-based projection.\n   `map` closure takes the value projected from `using` closure which is intermediate value.\n   If the intermediate value is not changed, map closure won't perform.\n\n   - Parameters:\n     - using: Specifies values for transforming. This function is annotated ``PipelineIntermediateBuilder``\n     - transform: Transforms the given value from `using` function\n\n   ```swift\n   `.map(using: { $0.a; $0.b;}, transform: { a, b in ... }`\n   ```\n\n   */\n  public static func map<Input, Intermediate, Output>(\n    @PipelineIntermediateBuilder using intermediate: @escaping @Sendable (\n      Input\n    ) -> PipelineIntermediate<Intermediate>,\n    transform: @escaping @Sendable (Intermediate) -> Output\n  ) -> Self\n  where\n    Input: Equatable, Output: Equatable,\n    Self == Pipelines.ChangesMapPipeline<Input, Intermediate, Output>\n  {\n\n    self.init(\n      intermediate: intermediate,\n      transform: transform,\n      additionalDropCondition: nil\n    )\n  }\n\n  /**\n   For Changes input\n   Produces output values using closure-based projection.\n   Using Edge as intermediate, output value will be unwrapped value from the Edge.\n   */\n  public static func map<Input, EdgeIntermediate>(\n    @PipelineIntermediateBuilder using intermediate: @escaping @Sendable (Input) ->\n      PipelineIntermediate<Edge<EdgeIntermediate>>\n  ) -> Self\n  where\n    Input: Equatable, Output: Equatable,\n    Self == Pipelines.ChangesMapPipeline<Input, Edge<EdgeIntermediate>, EdgeIntermediate>\n  {\n\n    self.init(\n      intermediate: intermediate,\n      transform: { $0.wrappedValue },\n      additionalDropCondition: nil\n    )\n  }\n\n}\n\npublic struct PipelineIntermediate<T>: Equatable {\n\n  public static func == (lhs: Self, rhs: Self) -> Bool {\n    lhs.comparer(lhs.value, rhs.value)\n  }\n\n  public var value: T\n  public let comparer: ((T, T) -> Bool)\n\n  @inlinable\n  public init(value: T, comparer: @escaping (T, T) -> Bool) {\n    self.value = value\n    self.comparer = comparer\n  }\n\n  @inlinable\n  public init(value: T) where T: Equatable {\n    self.value = value\n    self.comparer = (==)  // this won't be called\n  }\n\n}\n\nextension PipelineIntermediate where T: Equatable {\n\n  public static func == (lhs: Self, rhs: Self) -> Bool {\n    lhs.value == rhs.value\n  }\n\n}\n\n/// A result-builder that builds ``PipelineIntermediate``.\n/// It converts tuple into ``PipelineIntermediate`` implementing Equatable.\n///\n/// projects:\n/// ```\n/// {\n///   $0.a\n///   $0.b\n/// }\n///\n/// // alternative syntax.\n/// { $0.a; $0.b; }\n/// ```\n///\n/// into:\n/// ```\n/// PipelineIntermediate<(A, B)>\n/// ```\n@resultBuilder\npublic enum PipelineIntermediateBuilder {\n\n  public static func buildBlock<IntermediateValue>(_ i: PipelineIntermediate<IntermediateValue>)\n    -> PipelineIntermediate<IntermediateValue>\n  {\n    return i\n  }\n\n  public static func buildBlock<S1: Equatable>(_ s1: S1) -> PipelineIntermediate<S1> {\n    .init(value: s1)\n  }\n\n  public static func buildBlock<S1: Equatable, S2: Equatable>(_ s1: S1, _ s2: S2)\n    -> PipelineIntermediate<(S1, S2)>\n  {\n    .init(value: (s1, s2), comparer: ==)\n  }\n\n  public static func buildBlock<S1: Equatable, S2: Equatable, S3: Equatable>(\n    _ s1: S1, _ s2: S2, _ s3: S3\n  ) -> PipelineIntermediate<(S1, S2, S3)> {\n    .init(value: (s1, s2, s3), comparer: ==)\n  }\n\n  public static func buildBlock<S1: Equatable, S2: Equatable, S3: Equatable, S4: Equatable>(\n    _ s1: S1, _ s2: S2, _ s3: S3, _ s4: S4\n  ) -> PipelineIntermediate<(S1, S2, S3, S4)> {\n    .init(value: (s1, s2, s3, s4), comparer: ==)\n  }\n\n  public static func buildBlock<\n    S1: Equatable, S2: Equatable, S3: Equatable, S4: Equatable, S5: Equatable\n  >(_ s1: S1, _ s2: S2, _ s3: S3, _ s4: S4, _ s5: S5) -> PipelineIntermediate<(S1, S2, S3, S4, S5)>\n  {\n    .init(value: (s1, s2, s3, s4, s5), comparer: ==)\n  }\n\n  public static func buildBlock<\n    S1: Equatable, S2: Equatable, S3: Equatable, S4: Equatable, S5: Equatable, S6: Equatable\n  >(_ s1: S1, _ s2: S2, _ s3: S3, _ s4: S4, _ s5: S5, _ s6: S6) -> PipelineIntermediate<\n    (S1, S2, S3, S4, S5, S6)\n  > {\n    .init(value: (s1, s2, s3, s4, s5, s6), comparer: ==)\n  }\n}\n"
  },
  {
    "path": "Sources/Verge/Store/Scan.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\npublic final class Scan<Element, Accumulate>: Sendable {\n\n  public typealias Accumulator = @Sendable (inout Accumulate, Element) -> Void\n\n  public var value: Accumulate {\n    _value.value\n  }\n\n  private let _value: VergeConcurrency.UnfairLockAtomic<Accumulate>\n  private let _accumulator: Accumulator\n\n  public init(seed: Accumulate, accumulator: @escaping Accumulator) {\n    self._value = .init(seed)\n    self._accumulator = accumulator\n  }\n\n  public func accumulate(_ element: Element) -> Accumulate {\n    _value.modify { _v -> Accumulate in\n      _accumulator(&_v, element)\n      return _v\n    }\n  }\n\n}\n\nextension Scan {\n\n  /// A Scan instance that increments itself integer value each event received\n  public static func counter() -> Scan<Element, Int> {\n    .init(seed: 0, accumulator: { n, _ in n += 1 })\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Store/StateType.swift",
    "content": "//\n// Copyright (c) 2019 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\nimport StateStruct\n\n/**\n An opt-in protocol that indicates it's used as a state of the State.\n */\npublic protocol StateType {\n\n  /**\n   A chance of modifying state alongside the commit.\n   You may use this to make another value that consists of the state's self.\n   It's better to use it for better performance to get the value rather than using computed property.\n   */\n  @Sendable\n  static func reduce(\n    modifying: inout Self,\n    transaction: inout Transaction,\n    current: Changes<Self>\n  )\n}\n"
  },
  {
    "path": "Sources/Verge/Store/Store+Combine.swift",
    "content": "//\n// Copyright (c) 2019 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Combine\n\n@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)\nextension Store {\n\n  /// A publisher that repeatedly emits the changes when state updated\n  ///\n  /// Guarantees to emit the first event on started subscribing.\n  ///\n  /// - Parameter startsFromInitial: Make the first changes object's hasChanges always return true.\n  /// - Returns:\n  @_spi(Package)\n  public func _statePublisher() -> some Combine.Publisher<Changes<Value>, Never> {\n\n    return\n      publisher\n      .associate(resource: self, retains: keepsAliveForSubscribers)\n      .flatMap { event in\n        guard case .state(.didUpdate(let state)) = event else {\n          return Empty<Changes<Value>, Never>().eraseToAnyPublisher()\n        }\n        return Just<Changes<Value>>(state)\n          .eraseToAnyPublisher()\n      }\n      .merge(with: Just(state.droppedPrevious()))\n\n  }\n\n  //  @_spi(Package)\n  public func _activityPublisher() -> some Combine.Publisher<Activity, Never> {\n\n    return\n      publisher\n      .associate(resource: self, retains: keepsAliveForSubscribers)\n      .flatMap { event in\n        guard case .activity(let a) = event else {\n          return Empty<Activity, Never>().eraseToAnyPublisher()\n        }\n        return Just(a).eraseToAnyPublisher()\n      }\n  }\n\n}\n\nextension Publisher {\n\n  func associate(resource: AnyObject, retains: Bool) -> some Publisher<Output, Failure> {\n\n    let box = ResourceBox(object: resource, retains: retains)\n\n    return handleEvents(receiveCancel: {\n      // retain self until subscription finsihed\n      withExtendedLifetime(box) {}\n    })\n  }\n\n}\n\nprivate final class ResourceBox {\n\n  private let object: AnyObject?\n\n  init(object: AnyObject, retains: Bool) {\n    if retains {\n      self.object = object\n    } else {\n      self.object = nil\n    }\n  }\n}\n"
  },
  {
    "path": "Sources/Verge/Store/Store+RunLoop.swift",
    "content": "import Foundation\n\nextension Store {\n\n  /// Push an event to run event loop.\n  public func updateMainLoop() {\n    RunLoop.main.perform(inModes: [.common]) {}\n  }\n\n  /**\n   Subscribes state updates in given run-loop.\n   */\n  @MainActor\n  public func pollMainLoop(receive: @escaping @MainActor (Changes<State>) -> Void) -> VergeAnyCancellable {\n\n    var latestState: Changes<State>? = nil\n\n    let subscription = RunLoopActivityObserver.addObserver(acitivity: .beforeWaiting, in: .main) {\n\n      MainActor.assumeIsolated {\n        let newState = self.state\n\n        guard (latestState?.version ?? 0) < newState.version else {\n          return\n        }\n\n        let state: Changes<State>\n\n        if let latestState {\n          state = newState.replacePrevious(latestState)\n        } else {\n          state = newState.droppedPrevious()\n        }\n\n        latestState = newState\n\n        receive(state)\n      }\n\n    }\n\n    let firstState = state.droppedPrevious()\n\n    latestState = firstState\n\n    receive(firstState)\n\n    return .init {\n      RunLoopActivityObserver.remove(subscription)\n    }\n  }\n\n}\n\nenum RunLoopActivityObserver {\n\n  struct Subscription {\n    let mode: CFRunLoopMode\n    let observer: CFRunLoopObserver?\n    weak var targetRunLoop: RunLoop?\n  }\n\n  static func addObserver(acitivity: CFRunLoopActivity, in runLoop: RunLoop, callback: @escaping () -> Void) -> Subscription {\n\n    let o = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, acitivity.rawValue, true, Int.max, { observer, activity in\n      callback()\n    });\n\n    assert(o != nil)\n\n    let mode = CFRunLoopMode.commonModes!\n    let cfRunLoop = runLoop.getCFRunLoop()\n\n    CFRunLoopAddObserver(cfRunLoop, o, mode);\n\n    return .init(mode: mode, observer: o, targetRunLoop: runLoop)\n  }\n\n  static func remove(_ subscription: consuming Subscription) {\n\n    guard let observer = subscription.observer, let targetRunLoop = subscription.targetRunLoop else {\n      return\n    }\n\n    CFRunLoopRemoveObserver(targetRunLoop.getCFRunLoop(), observer, subscription.mode);\n  }\n\n}\n\n#if DEBUG && canImport(SwiftUI)\nimport SwiftUI\n\n#Preview {\n  Content()\n}\n\n@Tracking\nprivate struct StoreState {\n  var count: Int = 0\n}\n\nprivate struct Content: View {\n\n  let store = Store<_, Never>(initialState: StoreState())\n\n  @State var subscription: VergeAnyCancellable?\n  @State var timer: Timer?\n\n  var body: some View {\n    VStack {\n      Button(\"Up\") {\n        store.commit {\n          $0.count += 1\n        }\n      }\n      Button(\"Background Up\") {\n\n        for _ in 0..<10 {\n          store.commit {\n            $0.count += 1\n          }\n        }\n\n      }\n      Button(\"Run\") {\n        RunLoop.main.run(until: Date(timeIntervalSinceNow: 19))\n      }\n    }\n      .onAppear {\n        subscription = store.pollMainLoop { state in\n          print(state.count)\n        }\n      }\n  }\n\n}\n#endif\n\n"
  },
  {
    "path": "Sources/Verge/Store/Store.swift",
    "content": "//\n// Copyright (c) 2019 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Atomics\nimport ConcurrencyTaskManager\nimport Foundation\nimport os.log\nimport StateStruct\n\n#if canImport(Combine)\n  import Combine\n#endif\n\n/// A protocol that indicates itself is a reference-type and can convert to concrete Store type.\npublic protocol StoreType<State>: AnyObject, Sendable {\n  associatedtype State\n  associatedtype Activity: Sendable = Never\n\n  func asStore() -> Store<State, Activity>\n\n  var state: Changes<State> { get }\n  \n  func lock()\n  func unlock()\n}\n\npublic typealias NoActivityStoreBase<State> = Store<State, Never>\n\nprivate let sanitizerQueue = DispatchQueue.init(label: \"org.vergegroup.verge.sanitizer\")\n\npublic enum _StoreEvent<State, Activity>: EventEmitterEventType {\n\n  public enum StateEvent {\n    case willUpdate\n    case didUpdate(Changes<State>)\n  }\n\n  case state(StateEvent)\n  case activity(Activity)\n  case waiter(() -> Void)\n\n  public func onComsume() {\n    switch self {\n    case .state:\n      break\n    case .activity:\n      break\n    case .waiter(let closure):\n      closure()\n    }\n  }\n}\n\nactor Writer {\n\n  init() {\n\n  }\n\n  func perform<R>(_ operation: () throws -> sending R) rethrows -> sending R {\n    try operation()\n  }\n\n}\n\n/// An object that retains a latest state value and receives mutations that modify itself state.\n/// Those updates would be shared all of the subscribers these are sink(s), Derived(s)\n///\n/// You may create subclass of VergeDefaultStore\n/// ```\n/// final class MyStore: Store<MyState> {\n///   init() {\n///     super.init(initialState: .init(), logger: nil)\n///   }\n/// }\n/// ```\n/// You may use also `StoreWrapperType` to define State and Activity as inner types.\n///\nopen class Store<State, Activity: Sendable>: EventEmitter<_StoreEvent<State, Activity>>,\n                                             CustomReflectable,\n                                             StoreType,\n                                             StoreDriverType,\n                                             DerivedMaking,\n                                             @unchecked Sendable,\n                                             Hashable\n{\n  \n  // MARK: Equatable\n  public static func == (lhs: Store<State, Activity>, rhs: Store<State, Activity>) -> Bool {\n    lhs === rhs\n  }\n\n  // MARK: Hashable \n  public func hash(into hasher: inout Hasher) {\n    hasher.combine(ObjectIdentifier(self))\n  }\n  \n  public let scope: any WritableKeyPath<State, State> & Sendable = \\State.self\n\n  private let tracker = VergeConcurrency.SynchronizationTracker()\n\n  /// A name of the store.\n  /// Specified or generated automatically from file and line.\n  public let name: String\n\n  public let logger: StoreLogger?\n\n  public let sanitizer: RuntimeSanitizer\n\n  private var middlewares: [AnyStoreMiddleware<State>] = []\n\n  private let externalOperation: @Sendable (inout InoutRef<State>, Changes<State>, inout Transaction) -> Void\n\n  private(set) var nonatomicValue: Changes<State>\n\n  private let _lock: StoreOperation\n\n  /**\n   Holds subscriptions for sink State and Activity to finish them with its store life-cycle.\n   */\n  private let storeLifeCycleCancellable: VergeAnyCancellable = .init()\n\n  open var keepsAliveForSubscribers: Bool { false }\n\n  private let wasInvalidated = Atomics.ManagedAtomic(false)\n    \n  // MARK: - Deinit\n\n  deinit {\n    invalidate()\n  }\n\n  // MARK: - Task\n\n  public let taskManager: TaskManager = .init()\n\n  let writer: Writer = .init()\n\n  // MARK: - Initializers\n\n  /// An initializer\n  /// - Parameters:\n  ///   - initialState: A state instance that will be modified by the first commit.\n  ///   - backingStorageRecursiveLock: A lock instance for mutual exclusion.\n  ///   - logger: You can also use `DefaultLogger.shared`.\n  public nonisolated init(\n    name: String? = nil,\n    initialState: State,\n    storeOperation: StoreOperation = .atomic,\n    logger: StoreLogger? = nil,\n    sanitizer: RuntimeSanitizer? = nil,\n    _ file: StaticString = #file,\n    _ line: UInt = #line\n  ) {\n\n    self.nonatomicValue = .init(old: nil, new: initialState)\n    self._lock = storeOperation\n\n    self.logger = logger\n    self.sanitizer = sanitizer ?? RuntimeSanitizer.global\n    self.name = name ?? \"\\(file):\\(line)\"\n    self.externalOperation = { @Sendable _, _, _ in }\n\n    super.init()\n  }\n\n  public nonisolated init(\n    name: String? = nil,\n    initialState: State,\n    storeOperation: StoreOperation = .atomic,\n    logger: StoreLogger? = nil,\n    sanitizer: RuntimeSanitizer? = nil,\n    _ file: StaticString = #file,\n    _ line: UInt = #line\n  ) where State: StateType {\n\n    // making reduced state\n    var _initialState = initialState\n\n    let reduced = withUnsafeMutablePointer(to: &_initialState) { pointer in\n      var inoutRef = InoutRef<_>.init(pointer)\n      inoutRef.modify { state in\n        var transaction = Transaction()\n        State.reduce(modifying: &state, transaction: &transaction, current: .init(old: nil, new: initialState))\n      }\n      return inoutRef.wrapped\n    }\n\n    self.nonatomicValue = .init(old: nil, new: reduced)\n    self._lock = storeOperation\n\n    self.logger = logger\n    self.sanitizer = sanitizer ?? RuntimeSanitizer.global\n    self.name = name ?? \"\\(file):\\(line)\"\n    \n    self.externalOperation = { @Sendable inoutRef, state, transaction in\n      let intermediate = state.makeNextChanges(\n        with: inoutRef.wrapped,\n        modification: inoutRef.modification,\n        transaction: transaction\n      )\n      inoutRef.modify { state in\n        State.reduce(\n          modifying: &state,\n          transaction: &transaction,\n          current: intermediate\n        )\n      }\n    }\n\n    super.init()\n  }\n\n  @_spi(Internal)\n  public final override func receiveEvent(_ event: consuming _StoreEvent<State, Activity>) {\n\n    switch event {\n    case .state(let stateEvent):\n      switch stateEvent {\n      case .willUpdate:\n        break\n      case .didUpdate(let state):\n        stateDidUpdate(newState: state)\n      }\n    case .activity:\n      break\n    case .waiter:\n      break\n    }\n  }\n\n  open func stateDidUpdate(newState: Changes<State>) {\n    \n  }\n\n  final func invalidate() {\n    guard\n      wasInvalidated.compareExchange(expected: false, desired: true, ordering: .relaxed).exchanged\n    else {\n      // already invalidated\n      return\n    }\n    performInvalidation()\n  }\n\n  func performInvalidation() {\n\n    storeLifeCycleCancellable.cancel()\n\n    taskManager.cancelAll()\n  }\n\n}\n\n// MARK: - Typealias\nextension Store {\n\n  public typealias Scope = State\n  public typealias Value = State\n}\n\n// MARK: - Computed Properties\nextension Store {\n\n  public var store: Store<State, Activity> { self }\n\n  /// Returns a current state with thread-safety.\n  ///\n  /// It causes locking and unlocking with a bit cost.\n  /// It may cause blocking if any other is doing mutation or reading.\n  public var state: Changes<State> {\n    _lock.lock()\n    defer {\n      _lock.unlock()\n    }\n    return nonatomicValue\n  }\n\n}\n\n// MARK: - Convenience Initializers\nextension Store {\n\n  /// An initializer for preventing using the refence type as a state.\n  @available(\n    *, deprecated,\n    message:\n      \"Using the reference type for the state is restricted. it must be a value type to run correctly.\"\n  )\n  public convenience init(\n    name: String? = nil,\n    initialState: State,\n    storeOperation: StoreOperation = .atomic,\n    logger: StoreLogger? = nil,\n    _ file: StaticString = #file,\n    _ line: UInt = #line\n  ) where State: AnyObject {\n\n    preconditionFailure(\n      \"Using the reference type for the state is restricted. it must be a value type to run correctly.\"\n    )\n\n  }\n\n}\n\n// MARK: - Wait\nextension Store {\n\n  /**\n   Commit operation does not mean that emitting latest state for all of subscribers synchronously.\n   Updating state of the store will be updated immediately.\n\n   To wait until all of the subscribers get the latest state, you can use this method.\n   */\n  public func waitUntilAllEventConsumed() async {\n    await withCheckedContinuation { c in\n      accept(\n        .waiter({\n          c.resume()\n        }))\n    }\n  }\n\n}\n\n// MARK: - Middleware\nextension Store {\n\n  /// Registers a middleware.\n  /// MIddleware can execute additional operations unified with mutations.\n  ///\n  public func add(middleware: some StoreMiddlewareType<State>) {\n    // use lock\n    lock()\n    defer {\n      unlock()\n    }\n    middlewares.append(.init(modify: middleware.modify))\n  }\n}\n\nextension Store {\n\n  // MARK: - CustomReflectable\n  public var customMirror: Mirror {\n    return Mirror(\n      self,\n      children: KeyValuePairs.init(\n        dictionaryLiteral: (\"stateVersion\", state.version),\n        (\"middlewares\", middlewares)\n      ),\n      displayStyle: .class\n    )\n  }\n\n  @inline(__always)\n  public func asStore() -> Store<State, Activity> {\n    self\n  }\n\n  /**\n   Adds an asynchronous task to perform.\n\n   Use this function to perform an asynchronous task with a lifetime that matches that of this store.\n   If this store is deallocated ealier than the given task finished, that asynchronous task will be cancelled.\n\n   Carefully use this function - If the task retains this store, it will continue to live until the task is finished.\n\n   - Parameters:\n     - key:\n     - mode:\n     - priority:\n     - action\n   - Returns: A Task for tracking given async operation's completion.\n   */\n  @discardableResult\n  public func task<Return>(\n    key: ConcurrencyTaskManager.TaskKey = .distinct(),\n    mode: ConcurrencyTaskManager.TaskManager.Mode = .dropCurrent,\n    priority: TaskPriority = .userInitiated,\n    @_inheritActorContext _ action: @Sendable @escaping () async throws -> Return\n  ) -> Task<Return, Error> {\n    return taskManager.task(key: key, mode: mode, priority: priority, action)\n  }\n\n  /**\n   Adds an asynchronous task to perform.\n\n   Use this function to perform an asynchronous task with a lifetime that matches that of this store.\n   If this store is deallocated ealier than the given task finished, that asynchronous task will be cancelled.\n\n   Carefully use this function - If the task retains this store, it will continue to live until the task is finished.\n\n   - Parameters:\n   - key:\n   - mode:\n   - priority:\n   - action\n   - Returns: A Task for tracking given async operation's completion.\n   */\n  @discardableResult\n  public func taskDetached<Return>(\n    key: ConcurrencyTaskManager.TaskKey = .distinct(),\n    mode: ConcurrencyTaskManager.TaskManager.Mode = .dropCurrent,\n    priority: TaskPriority = .userInitiated,\n    _ action: @Sendable @escaping () async throws -> Return\n  ) -> Task<Return, Error> {\n    return taskManager.taskDetached(key: key, mode: mode, priority: priority, action)        \n  }\n\n  // MARK: - Internal\n\n  /// Receives mutation\n  ///\n  /// - Parameters:\n  ///   - mutation: (`inout` attributes to prevent escaping `Inout<State>` inside the closure.)\n  @inline(__always)\n  func _receive_sending<Result>(\n    mutation: (inout State, inout Transaction) throws -> Result\n  ) rethrows -> Result {\n\n    let signpost = VergeSignpostTransaction(\"Store.commit\")\n    defer {\n      signpost.end()\n    }\n\n    let warnings: Set<VergeConcurrency.SynchronizationTracker.Warning>\n    if RuntimeSanitizer.global.isRecursivelyCommitDetectionEnabled {\n      warnings = tracker.register()\n    } else {\n      warnings = .init()\n    }\n\n    defer {\n      if RuntimeSanitizer.global.isRecursivelyCommitDetectionEnabled {\n        tracker.unregister()\n      }\n    }\n\n    var valueFromMutation: Result!\n    var elapsed: CFTimeInterval = 0\n    var commitLog: CommitLog?\n\n    let __sanitizer__ = sanitizer\n\n    /** a ciritical session */\n    try _update { (state) -> UpdateResult in\n         \n      let startedTime = CFAbsoluteTimeGetCurrent()\n      defer {\n        elapsed = CFAbsoluteTimeGetCurrent() - startedTime\n      }\n\n      var modifying = state.primitive\n      \n      // TODO: better performant way\n      if var trackingObject = modifying as? TrackingObject {\n        trackingObject.startNewTracking()\n        modifying = trackingObject as! State\n      }\n\n      let updateResult = try withUnsafeMutablePointer(to: &modifying) {\n        (stateMutablePointer) -> UpdateResult in\n\n        var transaction = Transaction()\n        \n        var inoutRef = InoutRef<_>.init(stateMutablePointer)\n                \n        let result = try inoutRef.modify { modifying in          \n          try mutation(&modifying, &transaction)\n        }\n\n        valueFromMutation = consume result\n\n        /**\n         Step-1:\n         Checks if the state has been modified\n         */\n        guard inoutRef.hasModified else {          \n          // No emits update event\n//          Log.storeCommit.debug(\"\\(type(of: self)) No updates\")\n          return .nothingUpdates\n        }\n\n        /**\n         Step-2:\n         Reduce modifying state with externalOperation\n         */\n\n        externalOperation(&inoutRef, state, &transaction)\n\n        /**\n         Step-3\n         Applying by middlewares\n         */\n        self.middlewares.forEach { middleware in\n\n          let intermediate = state.makeNextChanges(\n            with: stateMutablePointer.pointee,\n            modification: inoutRef.modification,\n            transaction: transaction\n          )\n          inoutRef.modify { modifying in          \n            middleware.modify(\n              modifyingState: &modifying,\n              transaction: &transaction,\n              current: intermediate\n            )\n          }\n        }\n\n        /**\n         Make a new state\n         */\n        state = state.makeNextChanges(\n          with: stateMutablePointer.pointee,\n          modification: inoutRef.modification,\n          transaction: transaction\n        )\n\n        commitLog = CommitLog(storeName: self.name, traces: transaction.traces, time: elapsed)\n\n        return .updated\n      }\n\n      return updateResult\n\n    }\n\n    if let logger = logger, let _commitLog = commitLog {\n      logger.didCommit(log: _commitLog, sender: self)\n    }\n\n    return UnsafeSendableStruct(valueFromMutation).send()\n  }\n\n  @inline(__always)\n  func _send(\n    activity: Activity,\n    trace: ActivityTrace\n  ) {\n\n    accept(.activity(activity))\n\n    let log = ActivityLog(storeName: self.name, trace: trace)\n    logger?.didSendActivity(log: log, sender: self)\n  }\n\n  func _mainActor_sinkState(\n    keepsAliveSource: Bool? = nil,\n    dropsFirst: Bool = false,\n    queue: some MainActorTargetQueueType,\n    receive: @escaping @MainActor (Changes<State>) -> Void\n  ) -> StoreStateSubscription {\n    return _primitive_sinkState(\n      dropsFirst: dropsFirst,\n      queue: Queues.MainActor(queue),\n      receive: { e in\n        MainActor.assumeIsolated {\n          receive(e)\n        }\n      }\n    )\n  }\n\n  func _primitive_sinkState(\n    dropsFirst: Bool = false,\n    queue: some TargetQueueType,\n    receive: @escaping @Sendable (Changes<State>) -> Void\n  ) -> StoreStateSubscription {\n\n    let cancellable = _base_primitive_sinkState(\n      dropsFirst: dropsFirst,\n      queue: queue,\n      receive: receive\n    )\n\n    if keepsAliveForSubscribers {\n      return .init(cancellable, storeCancellable: storeLifeCycleCancellable)\n        .associate(store: self)  // while subscribing its Store will be alive\n    } else {\n      return .init(cancellable, storeCancellable: storeLifeCycleCancellable)\n    }\n\n  }\n\n  private func _base_primitive_sinkState(\n    dropsFirst: Bool = false,\n    queue: some TargetQueueType,\n    receive: @escaping @Sendable (Changes<State>) -> Void\n  ) -> EventEmitterCancellable {\n\n    let executor = queue.execute\n\n    nonisolated(unsafe)\n      var latestStateWrapper: Changes<State>? = nil\n\n    let __sanitizer__ = sanitizer\n\n    let lock = VergeConcurrency.UnfairLock()\n\n    /// Firstly, it registers a closure to make sure that it receives all of the updates, even updates inside the first call.\n    /// To get recursive updates that comes from first call receive closure.\n    let cancellable = _sinkStateEvent { (event) in\n      switch event {\n      case .willUpdate:\n        break\n      case .didUpdate(let receivedState):\n\n        executor {\n\n          lock.lock()\n\n          var resolvedReceivedState = receivedState\n\n          // To escaping from critical issue\n          if let latestState = latestStateWrapper {\n            if latestState.version <= receivedState.version {\n              /*\n               No issues case:\n               It has received newer version than previous version\n               */\n              latestStateWrapper = receivedState\n            } else {\n\n              /*\n               Serious problem case:\n               Received an older version than the state received before.\n               To recover this case, send latest version state with dropping previous value in order to make `ifChanged` returns always true.\n               */\n              resolvedReceivedState = latestState.droppedPrevious()\n\n              if __sanitizer__.isSanitizerStateReceivingByCorrectOrder {\n\n                sanitizerQueue.async {\n                  __sanitizer__.onDidFindRuntimeError(\n                    .recoveredStateFromReceivingOlderVersion(\n                      latestState: latestState,\n                      receivedState: receivedState\n                    )\n                  )\n\n                  Log.store.warning(\n                    \"\"\"\n                    ⚠️ [Verge Error] Received older version(\\(receivedState.version)) value rather than latest received version(\\(latestState.version)).\n                    \n                    The root cause might be from the following things:\n                    - Committed concurrently from multiple threads.\n                    \n                    To solve, make sure to commit in series, for example using DispatchQueue.\n                    \n                    Verge can't use a lock to process serially because the dead-lock will happen in some of the cases.\n                    RxSwift's BehaviorSubject takes the same deal.\n                    \n                    Regarding: Extra commit was dispatched inside sink synchronously\n                    This issue has been fixed by https://github.com/VergeGroup/Verge/pull/222\n                    ---\n                    \n                    Received older version (\\(receivedState.version)): (\\(String(describing: receivedState.traces)))\n                    \n                    Latest Version (\\(latestState.version)): (\\(String(describing: latestState.traces)))\n                    \n                    ===\n                    \"\"\"\n                  )\n                  \n                }\n              }\n            }\n\n          } else {\n            // first item\n            latestStateWrapper = receivedState\n          }\n\n          lock.unlock()\n\n          receive(resolvedReceivedState)\n        }\n      }\n    }\n\n    if !dropsFirst {\n\n      let value = state.droppedPrevious()\n\n      executor {\n        lock.lock()\n        latestStateWrapper = value\n        lock.unlock()\n        // this closure might contains some mutations.\n        // It depends outside usages.\n        receive(value)\n      }\n    }\n\n    return cancellable\n  }\n\n  func _mainActor_scan_sinkState<Accumulate>(\n    scan: Scan<Changes<State>, Accumulate>,\n    dropsFirst: Bool = false,\n    queue: some MainActorTargetQueueType,\n    receive: @escaping @MainActor (Changes<State>, Accumulate) -> Void\n  ) -> StoreStateSubscription {\n\n    _mainActor_sinkState(dropsFirst: dropsFirst, queue: queue) { (changes) in\n\n      let accumulate = scan.accumulate(changes)\n      receive(changes, accumulate)\n    }\n\n  }\n\n  func _primitive_scan_sinkState<Accumulate>(\n    scan: Scan<Changes<State>, Accumulate>,\n    dropsFirst: Bool = false,\n    queue: some TargetQueueType,\n    receive: @escaping @Sendable (Changes<State>, Accumulate) -> Void\n  ) -> StoreStateSubscription {\n\n    _primitive_sinkState(dropsFirst: dropsFirst, queue: queue) { (changes) in\n\n      let accumulate = scan.accumulate(changes)\n      receive(changes, accumulate)\n    }\n\n  }\n\n  func _mainActor_sinkActivity(\n    queue: some MainActorTargetQueueType,\n    receive: @escaping @MainActor (sending Activity) -> Void\n  ) -> StoreActivitySubscription {\n    return _primitive_sinkActivity(\n      queue: Queues.MainActor(queue),\n      receive: { e in\n        MainActor.assumeIsolated {\n          receive(e)\n        }\n      }\n    )\n  }\n\n  func _primitive_sinkActivity(\n    queue: some TargetQueueType,\n    receive: @escaping @Sendable (sending Activity) -> Void\n  ) -> StoreActivitySubscription {\n\n    let execute = queue.execute\n    let cancellable = self._sinkActivityEvent { activity in\n      execute {\n        receive(activity)\n      }\n    }\n\n    return .init(cancellable, storeCancellable: storeLifeCycleCancellable)\n\n  }\n\n}\n\n// MARK: - Storage Implementation\nextension Store {\n\n  public func lock() {\n    _lock.lock()\n  }\n\n  public func unlock() {\n    _lock.unlock()\n  }\n\n  final func _sinkStateEvent(\n    subscriber: @escaping (_StoreEvent<State, Activity>.StateEvent) -> Void\n  ) -> EventEmitterCancellable {\n    addEventHandler { event in\n      guard case .state(let stateEvent) = event else { return }\n      subscriber(stateEvent)\n    }\n  }\n\n  final func _sinkActivityEvent(subscriber: @escaping (sending Activity) -> Void)\n    -> EventEmitterCancellable\n  {\n    addEventHandler { event in\n      guard case .activity(let activity) = event else { return }\n      subscriber(activity)\n    }\n  }\n\n  enum UpdateResult {\n    case updated\n    case nothingUpdates\n  }\n\n  @inline(__always)\n  final func _update(_ update: (inout Changes<State>) throws -> UpdateResult) rethrows {\n\n    let signpost = VergeSignpostTransaction(\"Storage.update\")\n    defer {\n      signpost.end()\n    }\n\n    lock()\n    do {\n\n      let result = try update(&nonatomicValue)\n\n      switch result {\n      case .nothingUpdates:\n        unlock()\n      case .updated:\n        let afterValue = nonatomicValue\n\n        /**\n         Unlocks lock before emitting event to avoid dead-locking.\n         But it causes cracking the order of event.\n         SeeAlso: testOrderOfEvents\n         */\n        unlock()\n\n        // it's not actual `will` 👨🏻❓\n        accept(.state(.willUpdate))\n        accept(.state(.didUpdate(afterValue)))\n\n      }\n\n    } catch {\n      unlock()\n      throw error\n    }\n  }\n\n}\n\nextension Store {\n\n  /// [Experimental]\n  public func stateStream() -> AsyncStream<Changes<State>> {\n    return .init(Changes<State>.self, bufferingPolicy: .unbounded) { continuation in\n\n      let subscription = self.sinkState(queue: .passthrough) { state in\n        continuation.yield(state)\n      }\n\n      continuation.onTermination = { termination in\n        subscription.cancel()\n      }\n\n    }\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Store/StoreDriverType+Accumulator.swift",
    "content": "import StateStruct\n\nextension StoreDriverType where TargetStore.State : TrackingObject {\n  \n  /**\n   Subscribes states and accumulates into components.\n   Against sink method, it does not use Changes object.\n   It allows to check if values has changed in the unit of accumulation, not Changes view.\n   */\n  public func accumulate<T>(\n    queue: some MainActorTargetQueueType = .mainIsolated(),\n    @AccumulationSinkComponentBuilder<Scope> _ buildSubscription: @escaping @MainActor (consuming AccumulationBuilder<Scope>) -> _AccumulationSinkGroup<Scope, T>\n  ) -> StoreStateSubscription {\n\n    var previousBox: ReferenceEdge<_AccumulationSinkGroup<Scope, T>?> = .init(wrappedValue: nil)\n    \n    let scope = self.scope\n    \n    return store.asStore().sinkState(dropsFirst: false, queue: queue) { state in\n        \n      let builder = AccumulationBuilder<Scope>(previousLoader: {\n        previousBox.wrappedValue\n      })\n\n      var group = buildSubscription(consume builder)\n      \n      // sets the previous value\n      if let previous = previousBox.wrappedValue {\n        group = group.receive(previous: previous)\n      }\n                  \n      // sets the latest value\n      group = group.receive(\n        source: { state.primitive.tracked()[keyPath: scope] },\n        modification: state.modification ?? .indeterminate\n      )\n   \n      // runs sink\n      group = group.consume()\n\n      previousBox.wrappedValue = group\n\n    }\n\n  }\n\n  /**\n   Subscribes states and accumulates into components.\n   Against sink method, it does not use Changes object.\n   It allows to check if values has changed in the unit of accumulation, not Changes view.\n   */\n  @_disfavoredOverload\n  public func accumulate<T>(\n    queue: some TargetQueueType,\n    @AccumulationSinkComponentBuilder<Scope> _ buildSubscription: @escaping @Sendable (consuming AccumulationBuilder<Scope>) -> _AccumulationSinkGroup<Scope, T>\n  ) -> StoreStateSubscription {\n\n    let previousBox: UnsafeSendableClass<ReferenceEdge<_AccumulationSinkGroup<Scope, T>?>> = .init(\n      .init(wrappedValue: nil)\n    )\n    let lock = VergeConcurrency.UnfairLock()\n    \n    let scope = self.scope\n\n    return store.asStore().sinkState(dropsFirst: false, queue: queue) { @Sendable state in\n\n      lock.lock()\n      defer {\n        lock.unlock()\n      }\n\n      withUncheckedSendable {\n\n        let builder = AccumulationBuilder<Scope>(previousLoader: {\n          previousBox.value.wrappedValue\n        })\n\n        var group = buildSubscription(consume builder)\n\n        // sets the previous value\n        if let previous = previousBox.value.wrappedValue {\n          group = group.receive(previous: previous)\n        }\n        \n        // sets the latest value\n        group = group.receive(\n          source: { state.primitive.tracked()[keyPath: scope] },\n          modification: state.modification ?? .indeterminate\n        )\n      \n        // runs sink\n        group = group.consume()\n\n        previousBox.value.wrappedValue = group\n\n      }\n    }\n\n  }\n\n}\n\npublic protocol AccumulationSink<Source> {\n  associatedtype Source\n  consuming func receive(source: () -> Source, modification: Modification) -> Self\n  consuming func receive(previous: consuming Self) -> Self\n  consuming func consume() -> Self\n}\n\npublic struct AccumulationBuilder<Source>: ~Copyable {\n\n  public var previous: (any AccumulationSink)? {\n    previousLoader()\n  }\n\n  private let previousLoader: () -> (any AccumulationSink)?\n\n  init(previousLoader: @escaping () -> (any AccumulationSink)?) {\n    self.previousLoader = previousLoader\n  }\n\n  public func ifChanged<Value: Equatable>(_ selector: @escaping (borrowing Source) -> Value) -> AccumulationSinkIfChanged<Source, Value> {\n    .init(\n      selector: selector\n    )\n  }\n  \n}\n\npublic struct AccumulationSinkIfChanged<Source: TrackingObject, Target: Equatable>: AccumulationSink {\n\n  private let selector: (borrowing Source) -> Target\n\n  private var latestValue: Target?\n  private var previousValue: Target?\n  private var readingGraph: PropertyNode?\n  private var source: Source?\n\n  private var counter: UInt64 = 0\n  private var countToEmit: UInt64 = 0\n\n  private var handlerWithSelectedValue: ((consuming Target) -> Void)?\n  private var handlerWithSource: ((Source) -> Void)?\n\n  init(\n    selector: @escaping (borrowing Source) -> Target\n  ) {\n    self.selector = selector\n  }\n\n  public consuming func dropFirst(_ k: UInt64 = 1) -> Self {\n    countToEmit = k\n    return self\n  }\n\n  /**\n   the closure will be released after consumed.\n   */\n  public consuming func `do`(@_inheritActorContext @_implicitSelfCapture _ perform: @escaping (consuming Target) -> Void) -> Self {\n    self.handlerWithSelectedValue = perform\n    return self\n  }\n  \n  public consuming func `doWithSource`(@_inheritActorContext @_implicitSelfCapture _ perform: @escaping (Source) -> Void) -> Self {\n    self.handlerWithSource = perform\n    return self\n  }\n\n  public consuming func receive(\n    source: () -> Source,\n    modification: Modification\n  ) -> Self {\n            \n    switch modification {\n    case .graph(let propertyNode):\n      \n      guard let readingGraph, \n          PropertyNode.hasChanges(\n            writeGraph: propertyNode,\n            readGraph: readingGraph\n          ) else {\n            // no changes\n        \n        self.latestValue = self.previousValue \n        \n        return self\n      }\n      \n      break\n    case .indeterminate:\n      \n      break\n      \n    }\n    \n    let tracked = source()\n    \n    self.latestValue = selector(tracked)\n    \n    self.readingGraph = tracked.trackingResult?.graph\n    \n    tracked.endTracking()\n    \n    if handlerWithSource != nil {\n      self.source = tracked\n    }\n    \n    return self\n          \n  }\n\n  public consuming func receive(previous: consuming Self) -> Self {\n\n    self.previousValue = previous.latestValue\n    self.readingGraph = previous.readingGraph\n    self.counter = previous.counter\n\n    return self\n  }\n\n  public consuming func consume() -> Self {\n\n    if latestValue != previousValue {\n      if counter >= countToEmit {        \n        handlerWithSelectedValue?(latestValue!)\n        handlerWithSource?(source!)\n      }\n      counter &+= 1\n    }\n\n    self.handlerWithSource = nil\n    self.handlerWithSelectedValue = nil\n\n    return self\n\n  }\n}\n\npublic struct _AccumulationSinkGroup<Source, Component>: AccumulationSink {\n\n  private var component: Component\n  private var _receiveSource: (\n    () -> Source,\n    Modification,\n    Component\n  ) -> Component\n  private var _receiveOther: (Component, Component) -> Component\n  private var _consume: (Component) -> Component\n\n  init(\n    component: Component,\n    receiveSource: @escaping (() -> Source, Modification, Component) -> Component,\n    receiveOther: @escaping (Component, Component) -> Component,\n    consume: @escaping (Component) -> Component\n  ) {\n    self.component = component\n    self._receiveSource = receiveSource\n    self._receiveOther = receiveOther\n    self._consume = consume\n  }\n\n  init() where Component == Void {\n    self.component = ()\n    self._receiveSource = { _, _, component in component }\n    self._receiveOther = { _, component in component }\n    self._consume = { component in component }\n  }\n\n  public consuming func receive(source: () -> Source, modification: Modification) -> Self {\n    component = _receiveSource(source, modification, component)\n    return self\n  }\n\n  public consuming func receive(previous: Self) -> Self {\n    component = _receiveOther(previous.component, component)\n    return self\n  }\n\n  public consuming func consume() -> Self {\n    component = _consume(component)\n    return self\n  }\n\n}\n\npublic struct _AccumulationSinkCondition<Source, TrueComponent: AccumulationSink, FalseComponent: AccumulationSink>: AccumulationSink where TrueComponent.Source == Source, FalseComponent.Source == Source {\n\n  private var trueComponent: TrueComponent?\n  private var falseComponent: FalseComponent?\n\n  init(\n    trueComponent: TrueComponent?,\n    falseComponent: FalseComponent?\n  ) {\n    self.trueComponent = trueComponent\n    self.falseComponent = falseComponent\n  }\n\n  public consuming func receive(source: () -> Source, modification: Modification) -> Self {\n    if let trueComponent = trueComponent {\n      self.trueComponent = trueComponent.receive(source: source, modification: modification)\n    } else if let falseComponent = falseComponent {\n      self.falseComponent = falseComponent.receive(source: source, modification: modification)\n    }\n    return self\n  }\n\n  public consuming func receive(previous: Self) -> Self {\n    if let trueComponent = trueComponent, let previousTrueComponent = previous.trueComponent {\n      self.trueComponent = trueComponent.receive(previous: previousTrueComponent)\n    } else if let falseComponent = falseComponent, let previousFalseComponent = previous.falseComponent {\n      self.falseComponent = falseComponent.receive(previous: previousFalseComponent)\n    }\n    return self\n  }\n\n  public consuming func consume() -> Self {\n    if let trueComponent = trueComponent {\n      self.trueComponent = trueComponent.consume()\n    } else if let falseComponent = falseComponent {\n      self.falseComponent = falseComponent.consume()\n    }\n    return self\n  }\n\n}\n\nstruct _AccumulationSinkOptional<Source, Component: AccumulationSink>: AccumulationSink where Component.Source == Source {\n\n  private var component: Component?\n\n  init(\n    component: Component?\n  ) {\n    self.component = component\n  }\n\n  consuming func receive(source: () -> Source, modification: Modification) -> Self {\n    if let component = component {\n      self.component = component.receive(source: source, modification: modification)\n    }\n    return self\n  }\n\n  consuming func receive(previous: Self) -> Self {\n    if let component = component, let previousComponent = previous.component {\n      self.component = component.receive(previous: previousComponent)\n    }\n    return self\n  }\n\n  consuming func consume() -> Self {\n    if let component = component {\n      self.component = component.consume()\n    }\n    return self\n  }\n\n}\n\n@resultBuilder\npublic struct AccumulationSinkComponentBuilder<Source> {\n\n  public static func buildExpression<S: AccumulationSink>(_ expression: S) -> S where S.Source == Source {\n    expression\n  }\n\n  public static func buildBlock() -> some AccumulationSink {\n    return _AccumulationSinkGroup<Source, Void>()\n  }\n\n  public static func buildEither<TrueComponent: AccumulationSink, FalseComponent: AccumulationSink>(first component: TrueComponent) -> _AccumulationSinkCondition<Source, TrueComponent, FalseComponent> where TrueComponent.Source == Source, FalseComponent.Source == Source {\n\n    return _AccumulationSinkCondition<Source, TrueComponent, FalseComponent>(\n      trueComponent: component,\n      falseComponent: nil\n    )\n\n  }\n\n  public static func buildEither<TrueComponent: AccumulationSink, FalseComponent: AccumulationSink>(second component: FalseComponent) -> _AccumulationSinkCondition<Source, TrueComponent, FalseComponent> where TrueComponent.Source == Source, FalseComponent.Source == Source {\n\n    return _AccumulationSinkCondition<Source, TrueComponent, FalseComponent>(\n      trueComponent: nil,\n      falseComponent: component\n    )\n  }\n\n  public static func buildOptional<Component>(_ component: Component?) -> some AccumulationSink where Component : AccumulationSink {\n    return _AccumulationSinkOptional.init(component: component)\n  }\n\n  // FIXME: add `where repeat (each S).Source == Source`\n  public static func buildBlock<each S: AccumulationSink>(_ sinks: repeat each S) -> _AccumulationSinkGroup<Source, (repeat each S)> {\n\n    return _AccumulationSinkGroup<Source, (repeat each S)>(\n      component: (repeat each sinks),\n      receiveSource: { source, modification, component in\n        // Waiting https://www.swift.org/blog/pack-iteration/\n        func iterate<T: AccumulationSink>(_ left: T) -> T {\n          return left.receive(\n            source: { unsafeBitCast(source(), to: T.Source.self) },\n            modification: modification\n          )\n        }\n\n        let modified = (repeat iterate(each component))\n\n        return modified\n      },\n      receiveOther: { other, current in\n        // Waiting https://www.swift.org/blog/pack-iteration/\n        func iterate<T: AccumulationSink>(previous: consuming T, current: consuming T) -> T {\n          return current.receive(previous: previous)\n        }\n\n        let modified = (repeat iterate(previous: each other, current: each current))\n\n        return modified\n      },\n      consume: { component in\n        // Waiting https://www.swift.org/blog/pack-iteration/\n        func iterate<T: AccumulationSink>(_ component: consuming T) -> T {\n          return component.consume()\n        }\n\n        let modified = (repeat iterate(each component))\n\n        return modified\n      }\n    )\n\n  }\n\n}\n\n"
  },
  {
    "path": "Sources/Verge/Store/StoreDriverType.swift",
    "content": "//\n// Copyright (c) 2019 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\n@available(*, deprecated, renamed: \"StoreDriverType\")\npublic typealias DispatcherType<Scope> = StoreDriverType<Scope>\n\n/// A protocol that uses external Store inside and provides the functions.\n/// ```\n/// final class MyViewModel: StoreDriverType {\n///\n///   struct State {\n///     ...\n///   }\n///\n///   // If you don't need Activity, you can remove it.\n///   enum Activity {\n///     ...\n///   }\n///\n///   let store: Store<State, Activity>\n///\n///   init() {\n///     self.store = .init(initialState: .init(), logger: nil)\n///   }\n///\n/// }\n/// ```\npublic protocol StoreDriverType<Scope>: AnyObject where Activity == TargetStore.Activity {\n\n  associatedtype TargetStore: StoreType\n\n  associatedtype Scope = TargetStore.State\n\n  var store: TargetStore { get }\n  var scope: WritableKeyPath<TargetStore.State, Scope> & Sendable { get }\n\n  var state: Changes<Scope> { get }\n\n  // WORKAROUND: for activityPublisher()\n  associatedtype Activity: Sendable = TargetStore.Activity\n\n}\n\nextension StoreDriverType {\n\n  public func statePublisher() -> some Combine.Publisher<Changes<TargetStore.State>, Never> {\n    store.asStore()._statePublisher()\n  }\n\n  public func activityPublisher() -> some Combine.Publisher<Activity, Never> {\n    store.asStore()._activityPublisher()\n  }\n\n  /// A state that cut out from root-state with the scope key path.\n  public nonisolated var state: Changes<Scope> {\n    store.state.map { $0[keyPath: scope] }\n  }\n\n  public nonisolated var rootState: Changes<TargetStore.State> {\n    return store.state\n  }\n}\n\nextension StoreDriverType where Scope == TargetStore.State {\n\n  public var scope: WritableKeyPath<TargetStore.State, TargetStore.State> & Sendable {\n    \\TargetStore.State.self\n  }\n\n  // MARK: - Subscribings\n\n  /// Subscribe the state changes\n  ///\n  /// First object always returns true from ifChanged / hasChanges / noChanges unless dropsFirst is true.\n  ///\n  /// - Parameters:\n  ///   - dropsFirst: Drops the latest value on started. if true, receive closure will call from next state updated.\n  ///   - queue: Specify a queue to receive changes object.\n  /// - Returns: A subscriber that performs the provided closure upon receiving values.\n  public func sinkState(\n    dropsFirst: Bool = false,\n    queue: some TargetQueueType,\n    receive: @escaping @Sendable (Changes<TargetStore.State>) -> Void\n  ) -> StoreStateSubscription {\n    store.asStore()._primitive_sinkState(dropsFirst: dropsFirst, queue: queue, receive: receive)\n  }\n\n  /// Subscribe the state changes\n  ///\n  /// First object always returns true from ifChanged / hasChanges / noChanges unless dropsFirst is true.\n  ///\n  /// - Parameters:\n  ///   - dropsFirst: Drops the latest value on started. if true, receive closure will call from next state updated.\n  ///   - queue: Specify a queue to receive changes object.\n  /// - Returns: A subscriber that performs the provided closure upon receiving values.\n  public func sinkState(\n    dropsFirst: Bool = false,\n    queue: some MainActorTargetQueueType = .mainIsolated(),\n    receive: @escaping @MainActor (Changes<TargetStore.State>) -> Void\n  ) -> StoreStateSubscription {\n    store.asStore()._mainActor_sinkState(dropsFirst: dropsFirst, queue: queue, receive: receive)\n  }\n\n  /// Subscribe the state changes\n  ///\n  /// First object always returns true from ifChanged / hasChanges / noChanges unless dropsFirst is true.\n  ///\n  /// - Parameters:\n  ///   - scan: Accumulates a specified type of value over receiving updates.\n  ///   - dropsFirst: Drops the latest value on started. if true, receive closure will call from next state updated.\n  ///   - queue: Specify a queue to receive changes object.\n  /// - Returns: A subscriber that performs the provided closure upon receiving values.\n  @_disfavoredOverload\n  public func sinkState<Accumulate>(\n    scan: Scan<Changes<TargetStore.State>, Accumulate>,\n    dropsFirst: Bool = false,\n    queue: some TargetQueueType,\n    receive: @escaping @Sendable (Changes<TargetStore.State>, Accumulate) -> Void\n  ) -> StoreStateSubscription {\n    store.asStore()._primitive_scan_sinkState(\n      scan: scan,\n      dropsFirst: dropsFirst,\n      queue: queue,\n      receive: receive\n    )\n  }\n\n  /// Subscribe the state changes\n  ///\n  /// First object always returns true from ifChanged / hasChanges / noChanges unless dropsFirst is true.\n  ///\n  /// - Parameters:\n  ///   - scan: Accumulates a specified type of value over receiving updates.\n  ///   - dropsFirst: Drops the latest value on started. if true, receive closure will call from next state updated.\n  ///   - queue: Specify a queue to receive changes object.\n  /// - Returns: A subscriber that performs the provided closure upon receiving values.\n  @discardableResult\n  public func sinkState<Accumulate>(\n    scan: Scan<Changes<TargetStore.State>, Accumulate>,\n    dropsFirst: Bool = false,\n    queue: some MainActorTargetQueueType = .mainIsolated(),\n    receive: @escaping @MainActor (Changes<TargetStore.State>, Accumulate) -> Void\n  ) -> StoreStateSubscription {\n    store.asStore()._mainActor_scan_sinkState(\n      scan: scan, dropsFirst: dropsFirst, queue: queue, receive: receive)\n  }\n\n  /// Subscribe the activity\n  ///\n  /// - Returns: A subscriber that performs the provided closure upon receiving values.\n  @_disfavoredOverload\n  public func sinkActivity(\n    queue: some TargetQueueType,\n    receive: @escaping @Sendable (sending TargetStore.Activity) -> Void\n  ) -> StoreActivitySubscription {\n\n    store.asStore()._primitive_sinkActivity(queue: queue, receive: receive)\n\n  }\n\n  /// Subscribe the activity\n  ///\n  /// - Returns: A subscriber that performs the provided closure upon receiving values.\n  public func sinkActivity(\n    queue: some MainActorTargetQueueType = .mainIsolated(),\n    receive: @escaping @MainActor (sending TargetStore.Activity) -> Void\n  ) -> StoreActivitySubscription {\n\n    store.asStore()._mainActor_sinkActivity(queue: queue) { activity in\n      MainActor.assumeIsolated {\n        receive(activity)\n      }\n    }\n\n  }\n\n}\n\nextension StoreDriverType {\n\n  /**\n   Commit operation does not mean that emitting latest state for all of subscribers synchronously.\n   Updating state of the store will be updated immediately.\n\n   To wait until all of the subscribers get the latest state, you can use this method.\n   */\n  public func waitUntilAllEventConsumed() async {\n    await store.asStore().waitUntilAllEventConsumed()\n  }\n}\n\nextension StoreDriverType {\n\n  /**\n    Subscribe the state that scoped\n\n    First object always returns true from ifChanged / hasChanges / noChanges unless dropsFirst is true.\n\n    - Parameters:\n      - dropsFirst: Drops the latest value on started. if true, receive closure will call from next state updated.\n      - queue: Specify a queue to receive changes object.\n    - Returns: A subscriber that performs the provided closure upon receiving values.\n   */\n  @_disfavoredOverload\n  public func sinkState(\n    dropsFirst: Bool = false,\n    queue: some TargetQueueType,\n    receive: @escaping @Sendable (Changes<Scope>) -> Void\n  ) -> StoreStateSubscription {\n    let _scope = scope\n\n    return store.asStore().sinkState(dropsFirst: dropsFirst, queue: queue) { state in\n      receive(state.map { $0[keyPath: _scope] })\n    }\n  }\n\n  /**\n    Subscribe the state that scoped\n\n    First object always returns true from ifChanged / hasChanges / noChanges unless dropsFirst is true.\n\n    - Parameters:\n      - dropsFirst: Drops the latest value on started. if true, receive closure will call from next state updated.\n      - queue: Specify a queue to receive changes object.\n    - Returns: A subscriber that performs the provided closure upon receiving values.\n   */\n  @_disfavoredOverload\n  public func sinkState(\n    dropsFirst: Bool = false,\n    queue: some MainActorTargetQueueType = .mainIsolated(),\n    receive: @escaping @MainActor (Changes<Scope>) -> Void\n  ) -> StoreStateSubscription {\n    let _scope = scope\n\n    return store.asStore().sinkState(dropsFirst: dropsFirst, queue: queue) { @MainActor state in\n      receive(state.map { $0[keyPath: _scope] })\n    }\n  }\n\n  /// Subscribe the state changes\n  ///\n  /// First object always returns true from ifChanged / hasChanges / noChanges unless dropsFirst is true.\n  ///\n  /// - Parameters:\n  ///   - scan: Accumulates a specified type of value over receiving updates.\n  ///   - dropsFirst: Drops the latest value on started. if true, receive closure will call from next state updated.\n  ///   - queue: Specify a queue to receive changes object.\n  /// - Returns: A subscriber that performs the provided closure upon receiving values.\n  @_disfavoredOverload\n  public func sinkState<Accumulate>(\n    scan: Scan<Changes<Scope>, Accumulate>,\n    dropsFirst: Bool = false,\n    queue: some TargetQueueType,\n    receive: @escaping @Sendable (Changes<Scope>, Accumulate) -> Void\n  ) -> StoreStateSubscription {\n    sinkState(dropsFirst: dropsFirst, queue: queue) { (changes) in\n      let accumulate = scan.accumulate(changes)\n      receive(changes, accumulate)\n    }\n  }\n\n  /// Subscribe the state changes\n  ///\n  /// First object always returns true from ifChanged / hasChanges / noChanges unless dropsFirst is true.\n  ///\n  /// - Parameters:\n  ///   - scan: Accumulates a specified type of value over receiving updates.\n  ///   - dropsFirst: Drops the latest value on started. if true, receive closure will call from next state updated.\n  ///   - queue: Specify a queue to receive changes object.\n  /// - Returns: A subscriber that performs the provided closure upon receiving values.\n  @_disfavoredOverload\n  public func sinkState<Accumulate>(\n    scan: Scan<Changes<Scope>, Accumulate>,\n    dropsFirst: Bool = false,\n    queue: some MainActorTargetQueueType = .mainIsolated(),\n    receive: @escaping @MainActor (Changes<Scope>, Accumulate) -> Void\n  ) -> StoreStateSubscription {\n    sinkState(dropsFirst: dropsFirst, queue: queue) { @MainActor changes in\n      let accumulate = scan.accumulate(changes)\n      receive(changes, accumulate)\n    }\n  }\n\n  /// Send activity\n  /// - Parameter activity:\n  public func send(\n    _ name: String = \"\",\n    _ activity: TargetStore.Activity,\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line\n  ) {\n    let trace = ActivityTrace(\n      name: name,\n      file: file.description,\n      function: function.description,\n      line: line\n    )\n\n    store.asStore()._send(activity: activity, trace: trace)\n  }\n\n  /// Send activity\n  /// - Parameter activity:\n  public func send(\n    _ activity: TargetStore.Activity,\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line\n  ) {\n    send(\"\", activity, file, function, line)\n  }\n\n  /// Run Mutation that created inline\n  ///\n  /// Throwable\n  public func commit<Result>(\n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    mutation: (inout Scope) throws -> Result\n  ) rethrows -> Result {\n\n    let trace = MutationTrace(\n      name: name,\n      file: file,\n      function: function,\n      line: line\n    )\n\n    return try store.asStore()._receive_sending(\n      mutation: { [scope] state, _ -> Result in\n        try mutation(&state[keyPath: scope])\n      }\n    )\n\n  }\n\n  /// Run Mutation that created inline\n  ///\n  /// Throwable\n  public func commit<Result>(\n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    mutation: (inout Scope, inout Transaction) throws -> Result\n  ) rethrows -> Result {\n    \n    let trace = MutationTrace(\n      name: name,\n      file: file,\n      function: function,\n      line: line\n    )\n\n    return try store.asStore()._receive_sending(\n      mutation: { [scope] state, transaction -> Result in\n        transaction.append(trace: trace)\n        return try mutation(&state[keyPath: scope], &transaction)\n      }\n    )\n  }\n\n  /// Run Mutation that created inline\n  ///\n  /// Throwable\n  public func commit<Result>(\n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    mutation: (inout Scope) throws -> Result\n  ) rethrows -> Result where Scope == TargetStore.State {\n    \n    let trace = MutationTrace(\n      name: name,\n      file: file,\n      function: function,\n      line: line\n    )\n    \n    return try store.asStore()._receive_sending(\n      mutation: { state, transaction -> Result in        \n        transaction.append(trace: trace)\n        return try mutation(&state)        \n      }\n    )\n  }\n\n  /// Run Mutation that created inline\n  ///\n  /// Throwable\n  public func commit<Result>(\n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    mutation: (inout Scope, inout Transaction) throws -> Result\n  ) rethrows -> Result where Scope == TargetStore.State {\n    let trace = MutationTrace(\n      name: name,\n      file: file,\n      function: function,\n      line: line\n    )\n    return try store.asStore()._receive_sending(\n      mutation: { state, transaction -> Result in\n        transaction.append(trace: trace)\n        return try mutation(&state, &transaction)\n      }\n    )\n  }\n\n  /// Run Mutation that created inline\n  ///\n  /// Throwable\n  public func backgroundCommit<Result>(\n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    mutation: sending (inout Scope) throws -> sending Result\n  ) async rethrows -> Result {\n\n    let trace = MutationTrace(\n      name: name,\n      file: file,\n      function: function,\n      line: line\n    )\n\n    let result = try await store.asStore().writer.perform { [store = self.store, scope] in\n\n      let r = try store.asStore()._receive_sending { state, transaction in\n        \n        transaction.append(trace: trace)\n        let r = try mutation(&state[keyPath: scope])\n\n        return r\n      }\n\n      let workaround = { r }\n      return workaround()\n    }\n\n    await self.waitUntilAllEventConsumed()\n\n    return result\n  }\n\n  /// Run Mutation that created inline\n  ///\n  /// Throwable\n  public func backgroundCommit<Result>(\n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    mutation: sending (inout Scope, inout Transaction) throws -> sending Result\n  ) async rethrows -> Result {\n\n    let trace = MutationTrace(\n      name: name,\n      file: file,\n      function: function,\n      line: line\n    )\n\n    let result = try await store.asStore().writer.perform { [store = self.store, scope] in\n      \n      let r = try store.asStore()._receive_sending { state, transaction in\n        \n        transaction.append(trace: trace)\n        let r = try mutation(&state[keyPath: scope], &transaction)\n        \n        return r\n      }\n      \n      let workaround = { r }\n      return workaround()\n    }\n\n    await self.waitUntilAllEventConsumed()\n\n    return result\n  }\n\n  /// Run Mutation that created inline\n  ///\n  /// Throwable\n  public func backgroundCommit<Result>(\n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    mutation: sending (inout Scope) throws -> sending Result\n  ) async rethrows -> Result where Scope == TargetStore.State {\n\n    let trace = MutationTrace(\n      name: name,\n      file: file,\n      function: function,\n      line: line\n    )\n\n    let result = try await store.asStore().writer.perform { [store = self.store] in\n\n      let r = try store.asStore()._receive_sending { state, transaction in\n        transaction.append(trace: trace)        \n        let r = try mutation(&state)\n        return r\n      }\n\n      let workaround = { r }\n      return workaround()\n    }\n\n    await self.waitUntilAllEventConsumed()\n\n    return result\n\n  }\n\n  /// Run Mutation that created inline\n  ///\n  /// Throwable\n  public func backgroundCommit<Result>(\n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    mutation: sending (inout Scope, inout Transaction) throws -> Result\n  ) async rethrows -> Result where Scope == TargetStore.State, Self: Sendable {\n\n    let trace = MutationTrace(\n      name: name,\n      file: file,\n      function: function,\n      line: line\n    )\n\n    let result = try await store.asStore().writer.perform { [store = self.store] in\n\n      let r = try store.asStore()._receive_sending { state, transaction in\n        transaction.append(trace: trace)\n        let r = try mutation(&state, &transaction)\n        return r\n      }\n\n      let workaround = { r }\n      return workaround()\n    }\n\n    await self.waitUntilAllEventConsumed()\n\n    return result\n  }\n\n  @available(*, deprecated, message: \"A detached scope does not support TrackingObject.\")\n  public func detached<NewScope>(\n    from newScope: WritableKeyPath<TargetStore.State, NewScope> & Sendable\n  ) -> DetachedDispatcher<TargetStore.State, TargetStore.Activity, NewScope> {\n    .init(store: store.asStore(), scope: newScope)\n  }\n  \n  public func detached<NewScope: TrackingObject>(\n    from newScope: WritableKeyPath<TargetStore.State, NewScope> & Sendable\n  ) -> DetachedDispatcher<TargetStore.State, TargetStore.Activity, NewScope> {\n    .init(store: store.asStore(), scope: newScope)\n  }\n\n  // https://muukii.notion.site/Appending-Sendable-WritableKeyPath-makes-non-sendable-KeyPath-10618017d4c1800a8835fce9d6bffeba?pvs=4\n  /*\n  public func detached<NewScope: Equatable>(\n    by appendingScope: WritableKeyPath<Scope, NewScope> & Sendable\n  ) -> DetachedDispatcher<TargetStore.State, TargetStore.Activity, NewScope> {\n\n    return .init(\n      store: store.asStore(),\n      scope: scope.appending(path: appendingScope)\n    )\n  }\n   */\n}\n"
  },
  {
    "path": "Sources/Verge/Store/StoreMiddleware.swift",
    "content": "//\n// Copyright (c) 2019 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\npublic protocol StoreMiddlewareType<State>: Sendable {\n\n  associatedtype State\n\n  @Sendable\n  func modify(modifyingState: inout State, transaction: inout Transaction, current: Changes<State>)\n\n}\n\npublic struct AnyStoreMiddleware<State>: StoreMiddlewareType, Sendable {\n\n  private let closure: @Sendable (_ modifyingState: inout State, _ transaction: inout Transaction, _ current: Changes<State>) -> Void\n\n  init(\n    modify: @escaping @Sendable (\n      _ modifyingState: inout State, _ transaction: inout Transaction, _ current: Changes<State>\n    )\n      -> Void\n  ) {\n    self.closure = modify\n  }\n\n  public func modify(\n    modifyingState: inout State, transaction: inout Transaction, current: Changes<State>\n  ) {\n    self.closure(&modifyingState, &transaction, current)\n  }\n\n}\n\nextension StoreMiddlewareType {\n\n  /**\n   Creates an instance that commits mutations according to the original committing.\n   */\n  public static func modify<State>(\n    modify: @escaping @Sendable (\n      _ modifyingState: inout State, _ transaction: inout Transaction, _ current: Changes<State>\n    )\n      -> Void\n  ) -> Self where Self == AnyStoreMiddleware<State> {\n    return .init(modify: modify)\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Store/StoreOperation.swift",
    "content": "import class Foundation.NSRecursiveLock\n\npublic enum StoreOperation: Sendable {\n  case nonAtomic\n  case atomic(NSRecursiveLock)\n\n  func lock() {\n    switch self {\n    case .nonAtomic:\n      break\n    case .atomic(let lock):\n      lock.lock()\n    }\n  }\n\n  func unlock() {\n    switch self {\n    case .nonAtomic:\n      break\n    case .atomic(let lock):\n      lock.unlock()\n    }\n  }\n\n  public static var atomic: Self {\n    return .atomic(.init())\n  }\n}\n\n"
  },
  {
    "path": "Sources/Verge/Store/StoreType+Assignee.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\nextension StoreDriverType {\n\n  public typealias Assignee<Value> = @Sendable (Value) -> Void\n\n  /**\n   Returns an asignee function to asign\n\n   ```\n   let store1 = Store()\n   let store2 = Store()\n\n   store1\n   .derived(.map(\\.count))\n   .assign(to: store2.assignee(\\.count))\n   ```\n   */\n  public func assignee<Value>(\n    _ keyPath: WritableKeyPath<TargetStore.State, Value> & Sendable\n  ) -> Assignee<Changes<Value>> {\n    return { [weak store] value in\n      store?.asStore().commit {\n        $0[keyPath: keyPath] = value.primitive\n      }\n    }\n  }\n\n  /**\n   Returns an asignee function to asign\n\n   ```\n   let store1 = Store()\n   let store2 = Store()\n\n   store1\n   .derived(.map(\\.count))\n   .assign(to: store2.assignee(\\.count))\n   ```\n   */\n  public func assignee<Value>(\n    _ keyPath: WritableKeyPath<TargetStore.State, Value?> & Sendable\n  ) -> Assignee<Changes<Value?>> {\n    return { [weak store] value in\n      store?.asStore().commit {\n        $0[keyPath: keyPath] = value.primitive\n      }\n    }\n  }\n\n  /**\n   Returns an asignee function to asign\n\n   ```\n   let store1 = Store()\n   let store2 = Store()\n\n   store1\n   .derived(.map(\\.count))\n   .assign(to: store2.assignee(\\.count))\n   ```\n   */\n  public func assignee<Value>(\n    _ keyPath: WritableKeyPath<TargetStore.State, Value?> & Sendable\n  ) -> Assignee<Changes<Value>> {\n    return { [weak store] value in\n      let changes = value.map { Optional.some($0) }\n      store?.asStore().commit {\n        $0[keyPath: keyPath] = .some(value.primitive)\n      }\n    }\n  }\n\n  /**\n   Assignee to asign Changes object directly.\n   */\n  public func assignee<Value>(\n    _ keyPath: WritableKeyPath<TargetStore.State, Value> & Sendable\n  ) -> Assignee<Value> {\n    return { [weak store] value in\n      store?.asStore().commit {\n        $0[keyPath: keyPath] = value\n      }\n    }\n  }\n\n  /**\n   Assignee to asign Changes object directly.\n   */\n  public func assignee<Value>(\n    _ keyPath: WritableKeyPath<TargetStore.State, Value?> & Sendable\n  ) -> Assignee<Value?> {\n    return { [weak store] value in\n      store?.asStore().commit { [value] a in        \n        a[keyPath: keyPath] = value\n      }\n    }\n  }\n\n  /**\n   Assignee to asign Changes object directly.\n   */\n  public func assignee<Value>(\n    _ keyPath: WritableKeyPath<TargetStore.State, Value?> & Sendable\n  ) -> Assignee<Value> {\n    return { [weak store] value in\n      store?.asStore().commit {\n        $0[keyPath: keyPath] = .some(value)\n      }\n    }\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Store/StoreType+BindingDerived.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport class Foundation.NSString\n\nprivate enum CommitFromBindingDerived: TransactionKey {\n  static var defaultValue: Bool { false }\n}\n\nextension Transaction {\n\n  var isFromBindingDerived: Bool {\n    get {\n      self[CommitFromBindingDerived.self]\n    }\n    set {\n      self[CommitFromBindingDerived.self] = newValue\n    }\n  }\n\n}\n\nprivate struct BindingDerivedPipeline<Source, Output, BackingPipeline: PipelineType>: PipelineType where BackingPipeline.Input == Changes<Source>, BackingPipeline.Output == Output {\n\n  typealias Input = Changes<Source>\n\n  private let backingPipeline: BackingPipeline\n\n  init(backingPipeline: BackingPipeline) {\n    self.backingPipeline = backingPipeline\n  }\n\n  func makeStorage() -> BackingPipeline.Storage {\n    backingPipeline.makeStorage()\n  }\n\n  func yield(_ input: Changes<Source>, storage: inout Storage) -> Output {\n    backingPipeline.yield(input, storage: &storage)\n  }\n\n  func yieldContinuously(_ input: Changes<Source>, storage: inout Storage) -> ContinuousResult<Output> {\n    if input._transaction.isFromBindingDerived {\n      return .noUpdates\n    }\n    return backingPipeline.yieldContinuously(input, storage: &storage)\n  }\n\n}\n\nextension StoreDriverType {\n\n  /// Returns Binding Derived object\n  ///\n  /// - Complexity: 💡 It's better to set `dropsOutput` predicate.\n  /// - Parameters:\n  ///   - name:\n  ///   - get:\n  ///   - dropsOutput: Predicate to drops object if found a duplicated output\n  ///   - set:\n  /// - Returns:\n  public func bindingDerived<Pipeline: PipelineType>(\n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    get pipeline: Pipeline,\n    set: sending @escaping @Sendable (inout TargetStore.State, Pipeline.Output) -> Void,\n    queue: some TargetQueueType = .passthrough\n  ) -> BindingDerived<Pipeline.Output> where Pipeline.Input == Changes<TargetStore.State> {\n\n    let derived = BindingDerived<Pipeline.Output>.init(\n      get: BindingDerivedPipeline(backingPipeline: pipeline),\n      set: { [weak self] state in       \n        self?.store.asStore()\n          ._receive_sending { inoutRef, transaction in\n            transaction.isFromBindingDerived = true\n            set(&inoutRef, state)\n          }\n      },\n      initialUpstreamState: store.asStore().state,\n      subscribeUpstreamState: { callback in\n        store.asStore()._primitive_sinkState(\n          dropsFirst: true,\n          queue: queue,\n          receive: callback\n        )\n      },\n      retainsUpstream: nil\n    )\n\n    store.asStore().onDeinit { [weak derived] in\n      derived?.invalidate()\n    }\n\n    return derived\n  }\n\n  public func bindingDerived<Select>(    \n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    select: WritableKeyPath<TargetStore.State, Select> & Sendable,\n    queue: some TargetQueueType = .passthrough\n  ) -> BindingDerived<Select> {\n\n    bindingDerived(\n      name, file, function, line,\n      get: .select(select),\n      set: { state, newValue in\n        state[keyPath: select] = newValue\n      }\n    )\n  }\n  \n  public func bindingDerived<Select: Equatable>(    \n    _ name: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    select: WritableKeyPath<TargetStore.State, Select> & Sendable,\n    queue: some TargetQueueType = .passthrough\n  ) -> BindingDerived<Select> {\n    \n    bindingDerived(\n      name, file, function, line,\n      get: .select(select),\n      set: { state, newValue in\n        state[keyPath: select] = newValue\n      }\n    )\n  }\n\n}\n\n"
  },
  {
    "path": "Sources/Verge/Store/StoreType+Derived.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport class Foundation.NSString\n\nextension StoreDriverType {\n\n  /**\n   Creates a derived state object from a given pipeline.\n\n   This function can be used to create a Derived object that contains only a selected part of the state. The selected part is determined by a pipeline that is passed in as an argument.\n\n   - Parameters:\n   - pipeline: The pipeline object that selects a part of the state to be passed to other components.\n   - queue: The target queue for dispatching events.\n   */\n  public func derived<Pipeline: PipelineType>(\n    _ pipeline: Pipeline,\n    queue: some MainActorTargetQueueType\n  ) -> Derived<Pipeline.Output> where Pipeline.Input == Changes<TargetStore.State> {\n    self.derived(pipeline, queue: Queues.MainActor(queue))\n  }\n\n  /**\n   Creates a derived state object from a given pipeline.\n\n   This function can be used to create a Derived object that contains only a selected part of the state. The selected part is determined by a pipeline that is passed in as an argument.\n\n   - Parameters:\n     - pipeline: The pipeline object that selects a part of the state to be passed to other components.\n     - queue: The target queue for dispatching events.\n   */\n  public func derived<Pipeline: PipelineType>(\n    _ pipeline: Pipeline,\n    queue: some TargetQueueType = .passthrough\n  ) -> Derived<Pipeline.Output> where Pipeline.Input == Changes<TargetStore.State> {\n\n    vergeSignpostEvent(\"Store.derived.new\", label: \"\\(type(of: TargetStore.State.self)) -> \\(type(of: Pipeline.Output.self))\")\n\n    let derived = Derived<Pipeline.Output>(\n      get: pipeline,\n      set: { _ in /* no operation as read only */},\n      initialUpstreamState: store.state,\n      subscribeUpstreamState: { callback in\n        store.asStore()._primitive_sinkState(\n          dropsFirst: true,\n          queue: queue,\n          receive: callback\n        )\n      },\n      retainsUpstream: nil\n    )\n\n    store.asStore().onDeinit { [weak derived] in\n      derived?.invalidate()\n    }\n\n    return derived\n  }\n\n  public func _derived<Pipeline: PipelineType>(\n    _ pipeline: Pipeline,\n    queue: some MainActorTargetQueueType\n  ) -> Derived<Pipeline.Output> where Pipeline.Input == TargetStore.State {\n    self._derived(pipeline, queue: Queues.MainActor(queue))\n  }\n  \n  public func _derived<Pipeline: PipelineType>(\n    _ pipeline: Pipeline,\n    queue: some TargetQueueType = .passthrough\n  ) -> Derived<Pipeline.Output> where Pipeline.Input == TargetStore.State {\n    \n    vergeSignpostEvent(\"Store.derived.new\", label: \"\\(type(of: TargetStore.State.self)) -> \\(type(of: Pipeline.Output.self))\")\n    \n    let derived = Derived<Pipeline.Output>(\n      get: pipeline,\n      set: { _ in /* no operation as read only */},\n      initialUpstreamState: store.state.primitive,\n      subscribeUpstreamState: { callback in\n        store.asStore()._primitive_sinkState(\n          dropsFirst: true,\n          queue: queue,\n          receive: { state in\n            callback(state.primitive)\n          }\n        )\n      },\n      retainsUpstream: nil\n    )\n    \n    store.asStore().onDeinit { [weak derived] in\n      derived?.invalidate()\n    }\n    \n    return derived\n  }\n}\n"
  },
  {
    "path": "Sources/Verge/Store/StoreWrapperType.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\n@available(*, deprecated, renamed: \"StoreDriverType\")\npublic typealias StoreComponentType = StoreDriverType\n\n/// It would be deprecated in the future.\n@available(*, deprecated, renamed: \"StoreDriverType\")\npublic typealias StoreWrapperType = StoreComponentType\n"
  },
  {
    "path": "Sources/Verge/Store/Transaction.swift",
    "content": "//\n// Copyright (c) 2021 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\n/**\n Value storage for commit operation.\n The commit operation accepts adding context about its operation.\n It brings contextual operation into state-driven.\n For instance, same value changes but it's not the same meaning actually.\n\n ``Changes`` has ``Changes/transaction`` property.\n */\npublic struct Transaction: Sendable {\n  \n  private var values: [ObjectIdentifier : Any & Sendable] = [:]\n  \n  /// - Attention: non-atomic property\n  public private(set) var traces: [MutationTrace] = []\n  \n  mutating func append(trace: MutationTrace) {\n    traces.append(trace)\n  }\n  \n  mutating func append(traces otherTraces: [MutationTrace]) {\n    traces.append(contentsOf: otherTraces)\n  }\n\n  public subscript<K>(key: K.Type) -> K.Value where K : TransactionKey {\n    get {\n      values[ObjectIdentifier(K.self)] as? K.Value ?? K.defaultValue\n    }\n    mutating set {\n      values[ObjectIdentifier(K.self)] = newValue\n    }\n  }\n\n  public init() {\n  }\n\n}\n\n/**\n A type based key for transaction.\n It's like SwiftUI's EnvironmentValue.\n Making a new type as key, gat and set values over the key.\n It's much safer than using string directly as avoiding conflict by using same value.\n\n ```\n enum MyKey: TransactionKey {\n   static var defaultValue: String? { nil }\n }\n ```\n\n ```\n extension Transaction {\n   var myValue: String? {\n     get {\n       self[MyKey.self]\n     }\n     set {\n       self[MyKey.self] = newValue\n     }\n   }\n }\n ```\n */\npublic protocol TransactionKey {\n\n  associatedtype Value: Sendable\n\n  static var defaultValue: Value { get }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Store/UIStateStore.swift",
    "content": "//\n// Copyright (c) 2021 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/// A store that optimized for only using in UI thread.\n/// No using locks.\n@MainActor\npublic final class UIStateStore<State, Activity: Sendable>: Store<State, Activity>, @unchecked Sendable {\n\n  public nonisolated init(\n    initialState: State,\n    logger: StoreLogger? = nil\n  ) {\n    super.init(\n      initialState: initialState,\n      storeOperation: .nonAtomic,\n      logger: logger\n    )\n  }\n\n}\n\n@propertyWrapper\n@MainActor\npublic struct UIState<State>: Sendable {\n\n  private let store: UIStateStore<State, Never>\n\n  public nonisolated init(wrappedValue: State) {\n    self.store = .init(initialState: wrappedValue)\n  }\n\n  // MARK: - PropertyWrapper\n\n  public var wrappedValue: State {\n    get { store.state.primitive }\n    nonmutating set {\n      store.commit {\n        $0 = newValue\n      }\n    }\n  }\n\n  public var projectedValue: UIStateStore<State, Never> {\n    return store\n  }\n  \n}\n\n@propertyWrapper\npublic struct AtomicState<State>: Sendable {\n  \n  private let store: Store<State, Never>\n  \n  public nonisolated init(wrappedValue: State) {\n    self.store = .init(initialState: wrappedValue)\n  }\n  \n  // MARK: - PropertyWrapper\n  \n  public var wrappedValue: State {\n    get { store.state.primitive }\n    nonmutating set {\n      store.commit {\n        $0 = newValue\n      }\n    }\n  }\n  \n  public var projectedValue: Store<State, Never> {\n    return store\n  }\n  \n}\n"
  },
  {
    "path": "Sources/Verge/SwiftUI/.swift",
    "content": "//\n//  Untitled.swift\n//  Verge\n//\n//  Created by Muukii on 2025/03/19.\n//\n\n"
  },
  {
    "path": "Sources/Verge/SwiftUI/OnReceive.swift",
    "content": "import SwiftUI\n\nextension View {\n\n  /// Adds an action to perform when the specified `DispatcherType` publishes a state change.\n  ///\n  /// Use `onReceiveState(_ instance: perform:)` to perform an action when a `DispatcherType` instance publishes a state change.\n  /// The system calls the `perform` closure on the main thread each time the `State` changes.\n  ///\n  ///     struct MyView: View {\n  ///\n  ///      let viewModel: MyViewModel\n  ///\n  ///      var body: some View {\n  ///        Text(\"Hello, World!\")\n  ///          .onReceiveState(viewModel) { state in\n  ///            // Handle state changes here\n  ///          }\n  ///      }\n  ///     }\n  ///\n  /// - Parameters:\n  ///   - instance: The `DispatcherType` instance to subscribe to.\n  ///   - perform: A closure to execute when the `State` changes.\n  public func onReceiveState<D: StoreDriverType>(\n    _ instance: D,\n    perform: @escaping @MainActor (Changes<D.TargetStore.State>) -> Void\n  ) -> some View {\n    onReceive(\n      instance.store.asStore()._statePublisher().receive(on: DispatchQueue.main),\n      perform: { value in\n        MainActor.assumeIsolated {\n          perform(value)\n        }\n      }\n    )\n  }\n\n  /// Adds an action to perform when the specified `DispatcherType` publishes an activity.\n  ///\n  /// Use `onReceiveActivity(_ instance: perform:)` to perform an action when a `DispatcherType` instance publishes an activity.\n  /// The system calls the `perform` closure on the main thread each time the `Activity` is published.\n  ///\n  ///     struct MyView: View {\n  ///\n  ///      let viewModel: MyViewModel\n  ///\n  ///      var body: some View {\n  ///        Text(\"Hello, World!\")\n  ///          .onReceiveActivity(viewModel) { activity in\n  ///            // Handle activities here\n  ///          }\n  ///      }\n  ///     }\n  ///\n  /// - Parameters:\n  ///   - instance: The `DispatcherType` instance to subscribe to.\n  ///   - perform: A closure to execute when the `Activity` is published.\n  public func onReceiveActivity<D: StoreDriverType>(\n    _ instance: D,\n    perform: @escaping @MainActor (D.TargetStore.Activity) -> Void\n  ) -> some View {\n    onReceive(\n      instance.store.asStore()._activityPublisher().receive(on: DispatchQueue.main),\n      perform: { value in\n        MainActor.assumeIsolated {\n          perform(value)\n        }\n      }\n    )\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/SwiftUI/Reading.swift",
    "content": "import StateStruct\nimport SwiftUI\n\npublic protocol ReadingType: DynamicProperty {\n  \n  associatedtype Driver: StoreDriverType where Driver.TargetStore.State : TrackingObject \n  \n  @MainActor\n  @preconcurrency\n  var wrappedValue: Driver.TargetStore.State { get }\n  \n  @MainActor\n  @preconcurrency\n  var driver: Driver { get }\n}\n\n/**\n  A property wrapper that provides a state from a given store.\n  It tracks which properties are accessed and updates the view when those properties change.\n */\n@propertyWrapper\npublic struct Reading<Driver: StoreDriverType>: ReadingType, @preconcurrency DynamicProperty\nwhere Driver.TargetStore.State: TrackingObject {\n\n  public enum ReferencingType {\n    case strong\n    case unowned\n  }\n\n  private let instantiated: RetainBox\n\n  @StateObject private var coordinator = Coordinator<Driver>()\n\n  @MainActor\n  @preconcurrency\n  public var wrappedValue: Driver.TargetStore.State {\n\n    guard let state = coordinator.currentState() else {\n      fatalError(\"State is not being tracked\")\n    }\n    return state\n  }\n\n  @MainActor\n  @preconcurrency\n  public var projectedValue: BindableReading<Self> {\n    return .init(reading: self)\n  }\n  \n  @MainActor\n  @preconcurrency\n  public var driver: Driver {\n    instantiated.value\n  }\n\n  private let file: StaticString\n  private let line: UInt\n  private let label: StaticString?\n\n  /**\n   Passing already owned by someone else and uses it.\n   */\n  public nonisolated init(\n    file: StaticString = #file,\n    line: UInt = #line,\n    label: StaticString? = nil,\n    mode: ReferencingType = .strong,\n    _ driver: Driver\n  ) {\n    self.instantiated = .init(mode: mode, object: driver)\n    self.label = label\n    self.file = file\n    self.line = line\n  }\n\n  public init(projectedValue: Reading<Driver>) {\n    self = projectedValue\n  }\n\n  @MainActor\n  @preconcurrency\n  public mutating func update() {\n\n    coordinator.startTracking(using: driver)\n  }\n\n  private final class RetainBox: Equatable {\n    \n    static func == (lhs: RetainBox, rhs: RetainBox) -> Bool {\n      return lhs === rhs\n    }\n\n    unowned let value: Driver\n    let mode: ReferencingType\n\n    init(mode: ReferencingType, object: Driver) {\n      switch mode {\n      case .strong:\n        Unmanaged.passUnretained(object).retain()\n      case .unowned:\n        break\n      }\n      self.value = object\n      self.mode = mode\n    }\n\n    deinit {\n      switch mode {\n      case .strong:\n        Unmanaged.passUnretained(value).release()\n      case .unowned:\n        break\n      }\n    }\n  }\n\n}\n\n/**\n A property wrapper that provides a state from a given store.\n It tracks which properties are accessed and updates the view when those properties change.\n Compared to ``Reading``, this property wrapper instantiates a store via a closure and retains it alongside the view.\n */\n@propertyWrapper\npublic struct ReadingObject<Driver: StoreDriverType>: ReadingType, @preconcurrency DynamicProperty\nwhere Driver.TargetStore.State: TrackingObject {\n\n  private let stateObject: StateObject<Wrapper>\n  \n  @StateObject private var coordinator = Coordinator<Driver>()\n  \n  @MainActor\n  @preconcurrency\n  public var wrappedValue: Driver.TargetStore.State {\n    \n    guard let state = coordinator.currentState() else {\n      fatalError(\"State is not being tracked\")\n    }\n    return state\n  }\n  \n  @MainActor\n  @preconcurrency\n  public var projectedValue: BindableReading<Self> {\n    return .init(reading: self)\n  }\n  \n  @MainActor\n  @preconcurrency\n  public var driver: Driver {        \n    return stateObject.wrappedValue.object!        \n  }\n  \n  private let file: StaticString\n  private let line: UInt\n  private let label: StaticString?\n  \n  /**\n   Creates a new instance of the model object only once during the\n   lifetime of the container that declares\n   */\n  public nonisolated init(\n    file: StaticString = #file,\n    line: UInt = #line,\n    label: StaticString? = nil,\n    _ driver: @escaping () -> Driver\n  ) {\n    self.stateObject = .init(wrappedValue: .init(object: driver()))\n    self.label = label\n    self.file = file\n    self.line = line\n  }\n     \n  public init(projectedValue: ReadingObject<Driver>) {\n    self = projectedValue\n  }\n  \n  @MainActor\n  @preconcurrency\n  public mutating func update() {\n    \n    coordinator.startTracking(using: driver)\n  }\n  \n  /// A wrapper for the `Store` that serves as a bridge to `ObservableObject`.\n  private final class Wrapper: ObservableObject, Equatable {\n    \n    static func == (lhs: Wrapper, rhs: Wrapper) -> Bool {\n      return lhs === rhs\n    }\n    \n    let object: Driver?\n    \n    init(object: Driver?) {\n      self.object = object\n    }\n  }\n  \n}\n\nprivate final class Coordinator<Driver: StoreDriverType>: ObservableObject, Equatable where Driver.TargetStore.State: TrackingObject {\n  \n  public static func == (lhs: Coordinator, rhs: Coordinator) -> Bool {\n    return lhs === rhs\n  }\n  \n  private weak var driver: Driver?\n  private var _currentState: Driver.TargetStore.State?\n  private var _currentStateVersion: UInt64?\n  private var subscription: StoreStateSubscription?\n  \n  init() {\n    //      Log.reading.debug(\"Init Coordinator\")\n  }\n  \n  deinit {\n    //      Log.reading.debug(\"Deinit Coordinator\")\n  }\n    \n  @MainActor\n  func startTracking(using driver: Driver) {\n    \n    setTargetDriver(driver)\n    \n    let store = driver.store.asStore()\n    \n    store.lock()\n    defer {\n      store.unlock()\n    }\n    \n    let trackingState = store.nonatomicValue.primitive.tracked()\n    let version = store.nonatomicValue.version\n    \n    self._currentState = trackingState\n    self._currentStateVersion = version\n  }\n  \n  @MainActor\n  private func setTargetDriver(_ driver: Driver) {\n    \n    subscription?.cancel()\n    \n    self.driver = driver\n    \n    let _publisher = objectWillChange\n    \n    subscription = driver.store.asStore()\n      .sinkState { [weak self] state in\n        guard let self else {\n          return\n        }\n        Self.onUpdateState(\n          readGraph: self._currentState?.trackingResult?.graph,\n          modification: state.modification,\n          publisher: _publisher\n        )\n      }\n    \n  }\n  \n  @MainActor\n  private static func onUpdateState(\n    readGraph: PropertyNode?,\n    modification: Modification?,\n    publisher: ObjectWillChangePublisher\n  ) {\n    \n    switch modification {\n    case .graph(let writeGraph):\n      \n      guard let readGraph else {\n        return\n      }\n      \n      //        Log.reading.debug(\"Reading: \\(readGraph.prettyPrint())\")\n      \n      let hasChanges = PropertyNode.hasChanges(\n        writeGraph: consume writeGraph,\n        readGraph: readGraph\n      )\n      \n      guard hasChanges else {\n        return\n      }\n      \n    case .indeterminate:\n      break\n    case nil:\n      return\n    }\n    \n    // do\n    Task { @MainActor in\n      publisher.send()\n    }\n       \n  }\n     \n  func currentState() -> Driver.TargetStore.State? {\n    \n    guard let driver else {\n      return nil\n    }\n    \n    let store = driver.store.asStore()\n    \n    store.lock()\n    defer {\n      store.unlock()\n    }\n    \n    guard var _currentState, let _currentStateVersion else {\n      return nil\n    }\n    \n    let version = store.nonatomicValue.version\n    if _currentStateVersion != version {\n      \n      guard let ref = _currentState._tracking_context.trackingResultRef else {\n        return nil\n      }\n      \n      let latestState = store.nonatomicValue.primitive.tracked(using: ref.result.graph)\n      \n      self._currentState = latestState\n      self._currentStateVersion = version\n      \n      return latestState\n    } else {\n      return _currentState\n    }\n    \n  }\n  \n}\n\n\n@propertyWrapper\n@dynamicMemberLookup\npublic struct BindableReading<Source: ReadingType> {\n  \n  public let reading: Source\n  \n  @MainActor\n  @preconcurrency\n  public var wrappedValue: Source.Driver.TargetStore.State {\n    reading.wrappedValue\n  }\n  \n  public init(reading: Source) {\n    self.reading = reading\n  }\n  \n  public var projectedValue: BindableReading<Source> {\n    self\n  }\n  \n  public init(projectedValue: BindableReading<Source>) {\n    self = projectedValue\n  }\n  \n  @MainActor\n  @preconcurrency\n  public var driver: Source.Driver {\n    reading.driver\n  }\n  \n  @MainActor\n  @preconcurrency\n  public subscript<T>(dynamicMember keyPath: WritableKeyPath<Source.Driver.Scope, T>) -> Binding<T> {\n    binding(keyPath)\n  }\n  \n  @MainActor\n  @preconcurrency\n  public func binding<T>(_ keyPath: WritableKeyPath<Source.Driver.Scope, T>) -> SwiftUI.Binding<T> {\n    return .init { [keyPath = reading.driver.scope.appending(path: keyPath)] in\n      return reading.wrappedValue[keyPath: keyPath]\n    } set: { [weak driver = reading.driver] newValue, _ in\n      driver?.commit { [keyPath] state in\n        state[keyPath: keyPath] = newValue\n      }\n    }\n  }\n  \n  @MainActor\n  public func binding<T: Sendable>(_ keyPath: WritableKeyPath<Source.Driver.Scope, T> & Sendable)\n  -> SwiftUI.Binding<T>\n  {        \n    return .init { [keyPath = reading.driver.scope.appending(path: keyPath)] in\n      return reading.wrappedValue[keyPath: keyPath]\n    } set: { [weak driver = reading.driver] newValue, _ in\n      driver?.commit { [keyPath] state in\n        state[keyPath: keyPath] = newValue\n      }\n    }\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/SwiftUI/StoreObject.swift",
    "content": "import SwiftUI\n\n/**\n A property wrapper that instantiates a `Store` for the view lifecycle.\n\n This property wrapper is designed to manage a `Store` object for the view lifecycle without making the view reactive to `Store` changes, which is the behavior of `@StateObject` with `ObservableObject`. This is because `Store` updates can be handled through `StoreReader`, and it's often undesirable to have the entire view refreshed whenever the `Store` updates.\n\n - Note: The `Store` is a type that conforms to `DispatcherType`.\n\n - Warning: This property wrapper should only be used for store objects that are expected to have a lifetime matching the lifetime of the view.\n */\n@available(iOS 14, watchOS 7.0, tvOS 14, *)\n@MainActor\n@propertyWrapper\npublic struct StoreObject<Store: StoreDriverType>: DynamicProperty {\n\n  @StateObject private var backing: Wrapper\n\n  /// The current value of the store object.\n  public var wrappedValue: Store {\n    self.backing.object\n  }\n\n  /// Creates a new store object.\n  ///\n  /// - Parameter thunk: A closure that creates the initial store.\n  public init(wrappedValue thunk: @autoclosure @escaping () -> Store) {\n    self._backing = .init(wrappedValue: .init(object: thunk()))\n  }\n\n  /// A wrapper for the `Store` that serves as a bridge to `ObservableObject`.\n  private final class Wrapper: ObservableObject {\n    let object: Store\n\n    init(object: Store) {\n      self.object = object\n    }\n  }\n}\n\n#if DEBUG\n\n@available(iOS 14, watchOS 7.0, tvOS 14, *)\nenum Preview_StoreObject: PreviewProvider {\n\n  static var previews: some View {\n\n    Group {\n      Container()\n    }\n\n  }\n\n  struct Container: View {\n\n    @State var count = 0\n\n    var body: some View {\n\n      VStack {\n        Button(\"Reset\") {\n          count += 1\n        }\n        Child()\n          .id(count)\n      }\n\n    }\n\n  }\n\n  struct Child: View {\n\n    @StoreObject var store: ViewModel = .init()\n\n    var body: some View {\n      let _ = print(\"render\")\n      VStack {\n        Text(\"here is child\")\n        StoreReader(store) { $state in\n          Text(\"count: \\(state.count)\")\n          Text(state.count.description)\n        }\n        Button(\"up\") {\n          store.increment()\n        }\n        Button(\"up dummy\") {\n          store.incrementDummy()\n        }\n      }\n      \n    }\n  }\n\n  final class ViewModel: StoreDriverType {\n\n    @Tracking\n    struct State: Equatable {\n      var count: Int = 0\n      var count_dummy: Int = 0\n    }\n\n    let store: Store<State, Never>\n\n    init() {\n      self.store = .init(initialState: .init())\n      print(\"Init\")\n    }\n\n    func increment() {\n      commit {\n        $0.count += 1\n      }\n    }\n\n    func incrementDummy() {\n      commit {\n        $0.count_dummy += 1\n      }\n    }\n\n    deinit {\n      print(\"deinit\")\n    }\n  }\n\n}\n\n#endif\n"
  },
  {
    "path": "Sources/Verge/SwiftUI/StoreReader.swift",
    "content": "import Combine\nimport Foundation\nimport StateStruct\nimport SwiftUI\n\n/**\n A view that reads the state from Store and displays content according to the state.\n The view subscribes to the state updates and updates the content when the state changes.\n\n The state requires `@Tracking` macro to be used.\n\n ```swift\n @Tracking\n struct State {\n   var count: Int = 0\n }\n ```\n\n If you have nested types, you can use `@Tracking` macro to the nested types.\n Then the StoreReader can track through the nested types.\n\n ```swift\n @Tracking\n struct Nested {\n   var count: Int = 0\n }\n\n @Tracking\n struct State {\n   var nested: Nested = .init()\n }\n \n ## How to make Binding\n\n Use ``StoreBindable`` to make binding.\n\n ```swift\n @StoreBindable var store = store\n $store.count\n ```\n */\n@available(iOS 14, watchOS 7.0, tvOS 14, *)\npublic struct StoreReader<Driver: StoreDriverType, Content: View>: View where Driver.TargetStore.State : TrackingObject {\n  \n  let storeReading: Reading<Driver>\n\n  private let file: StaticString\n  private let line: UInt\n\n  /// Needs to use Reading directly to provide the latest state when it's accessed. from escaping closure.\n  private let content: (BindableReading<Reading<Driver>>) -> Content\n\n  /// Initialize from `Store`\n  ///\n  /// - Parameters:\n  ///   - store:\n  ///   - content:\n  public init(\n    file: StaticString = #file,\n    line: UInt = #line,\n    label: StaticString? = nil,\n    _ driver: Driver,\n    @ViewBuilder content: @escaping (BindableReading<Reading<Driver>>) -> Content\n  ) {\n    self.file = file\n    self.line = line\n    self.storeReading = .init(\n      file: file,\n      line: line,\n      label: label,\n      driver\n    )\n    self.content = content\n\n  }\n\n  public var body: some View {    \n    content(storeReading.projectedValue)\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Utility/Edge.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\nimport Atomics\n\npublic protocol EdgeType : Equatable {\n  associatedtype State\n  var wrappedValue: State { get }\n}\n\nprivate let _edge_global_counter = ManagedAtomic<UInt64>.init(0)\n\n/**\n A wrapper structure provides equatability as False-negative.\n Helpful in adding members which can’t conform to Equatable into a state due to the state of Store requiring Equatable.\n \n This structure holds two identifiers inside, a unique identifier (global-id) and a version number incrementally.\n the global id will be issued distinct each initialization.\n the version will increment each modification.\n \n If the wrapped type does not conform to Equatable, it compares using those identifiers. It will be `true` if they have not changed.\n But if `false`,  it might be false-negative because it can’t compare wrapped values.\n \n If the wrapped type conforms to Equatable, it compares using those identifiers and wrapped values. The result would be fully correct.\n Even in this case, using this structure works useful if comparing wrapped values takes much more expensive.\n \n Warnings: Do not assign a reference type object. It does not completely work.\n */\n@propertyWrapper\n@dynamicMemberLookup\npublic struct Edge<Value>: EdgeType {\n\n  public static func == (lhs: Edge<Value>, rhs: Edge<Value>) -> Bool {\n    lhs.globalID == rhs.globalID && lhs.version == rhs.version || lhs.comparerForNonEquatable(lhs.wrappedValue, rhs.wrappedValue)\n  }\n  \n  public subscript <U>(dynamicMember keyPath: KeyPath<Value, U>) -> U {\n    _read { yield wrappedValue[keyPath: keyPath] }\n  }\n  \n  public subscript <U>(dynamicMember keyPath: KeyPath<Value, U?>) -> U? {\n    _read { yield wrappedValue[keyPath: keyPath] }\n  }\n  \n  public subscript <U>(dynamicMember keyPath: WritableKeyPath<Value, U>) -> U {\n    _read { yield wrappedValue[keyPath: keyPath] }\n    _modify { yield &wrappedValue[keyPath: keyPath] }\n  }\n  \n  public subscript <U>(dynamicMember keyPath: WritableKeyPath<Value, U?>) -> U? {\n    _read { yield wrappedValue[keyPath: keyPath] }\n    _modify { yield &wrappedValue[keyPath: keyPath] }\n  }\n\n  /// A number value that indicates how many times State was updated.\n  public var version: UInt64 {\n    _read {\n      yield counter.value\n    }\n  }\n\n  public let globalID: UInt64\n  \n  private(set) public var counter: NonAtomicCounter = .init()\n  private let middleware: Middleware?\n  \n  private let comparerForNonEquatable: @Sendable (Value, Value) -> Bool\n     \n  public func next(_ value: Value) -> Self {\n    var copy = self\n    copy.counter.increment()\n    copy.wrappedValue = value\n    return copy\n  }\n\n  @_disfavoredOverload\n  public init(\n    wrappedValue: Value,\n    middleware: Middleware? = nil,\n    comparer: @escaping @Sendable (Value, Value) -> Bool = { @Sendable _, _ in false }\n  ) {\n    \n    self.globalID = _edge_global_counter.loadThenWrappingIncrement(ordering: .relaxed)\n    self.middleware = middleware\n    self.comparerForNonEquatable = comparer\n\n    if let middleware = middleware {\n      var mutable = wrappedValue\n      middleware._onSet(&mutable)\n      _wrappedValue = mutable\n    } else {\n      _wrappedValue = wrappedValue\n    }\n\n  }\n\n  /// A value that wrapped with Edge.\n  public var wrappedValue: Value {\n    get {\n      _wrappedValue\n    }\n    set {\n      if let middleware = middleware {\n        var mutable = newValue\n        middleware._onSet(&mutable)\n        _wrappedValue = mutable\n      } else {\n        _wrappedValue = newValue\n      }\n    }\n  }\n\n  private var _wrappedValue: Value {\n    didSet {\n      counter.increment()\n    }\n  }\n\n  public var projectedValue: Edge<Value> {\n    get {\n      self\n    }\n    set {\n      self = newValue\n    }\n  }\n\n}\n\nextension Edge : Sendable where Value : Sendable {\n  \n}\n\nextension Edge {\n  \n  /**\n   Tuple binding initializer - S1\n   It compares equality using `==` operator.\n   */\n  public init(\n    wrappedValue tuple: (Value),\n    middleware: Middleware? = nil\n  ) where Value : Equatable {\n    self.init(wrappedValue: tuple, middleware: middleware, comparer: { @Sendable in $0 == $1 })\n  }\n  \n  /**\n   Tuple binding initializer - S1, S2\n   It compares equality using `==` operator.\n   */\n  public init<S1: Equatable, S2: Equatable>(\n    wrappedValue tuple: (S1, S2),\n    middleware: Middleware? = nil\n  ) where Value == (S1, S2) {\n    self.init(wrappedValue: tuple, middleware: middleware, comparer: { @Sendable in $0 == $1 })\n  }\n  \n  /**\n   Tuple binding initializer - S1, S2, S3\n   It compares equality using `==` operator.\n   */\n  public init<S1: Equatable, S2: Equatable, S3: Equatable>(\n    wrappedValue tuple: (S1, S2, S3),\n    middleware: Middleware? = nil\n  ) where Value == (S1, S2, S3) {\n    self.init(wrappedValue: tuple, middleware: middleware, comparer: { @Sendable in $0 == $1 })\n  }\n  \n  /**\n   Tuple binding initializer - S1, S2, S3, S4\n   It compares equality using `==` operator.\n   */\n  public init<S1: Equatable, S2: Equatable, S3: Equatable, S4: Equatable>(\n    wrappedValue tuple: (S1, S2, S3, S4),\n    middleware: Middleware? = nil\n  ) where Value == (S1, S2, S3, S4) {\n    self.init(wrappedValue: tuple, middleware: middleware, comparer: { @Sendable in $0 == $1 })\n  }\n  \n  /**\n   Tuple binding initializer - S1, S2, S3, S4, S5\n   It compares equality using `==` operator.\n   */\n  public init<S1: Equatable, S2: Equatable, S3: Equatable, S4: Equatable, S5: Equatable>(\n    wrappedValue tuple: (S1, S2, S3, S4, S5),\n    middleware: Middleware? = nil\n  ) where Value == (S1, S2, S3, S4, S5) {\n    self.init(wrappedValue: tuple, middleware: middleware, comparer: { @Sendable in $0 == $1 })\n  }\n  \n  /**\n   Tuple binding initializer - S1, S2, S3, S4, S5, S6\n   It compares equality using `==` operator.\n   */\n  public init<S1: Equatable, S2: Equatable, S3: Equatable, S4: Equatable, S5: Equatable, S6: Equatable>(\n    wrappedValue tuple: (S1, S2, S3, S4, S5, S6),\n    middleware: Middleware? = nil\n  ) where Value == (S1, S2, S3, S4, S5, S6) {\n    self.init(wrappedValue: tuple, middleware: middleware, comparer: { @Sendable in $0 == $1 })\n  }\n   \n}\n\nextension Edge where Value : Equatable {\n  public static func == (lhs: Edge<Value>, rhs: Edge<Value>) -> Bool {\n    (lhs.globalID == rhs.globalID && lhs.version == rhs.version) || lhs.wrappedValue == rhs.wrappedValue\n  }\n}\n\nextension Edge {\n\n  public struct VersionComparison: TypedComparator {\n\n    public func callAsFunction(_ lhs: Edge, _ rhs: Edge) -> Bool {\n      lhs.globalID == rhs.globalID && lhs.version == rhs.version\n    }\n  }\n\n}\n\nextension TypedComparator {\n\n  public static func versionEquals<T>() -> Self where Self == Edge<T>.VersionComparison {\n    .init()\n  }\n}\n\nextension Edge {\n\n  /**\n   A handler that can modify a new state.\n\n   ```swift\n   @Edge(middleware: .assert { $0 >= 0 }) var count: Int = 0\n   ```\n   */\n  public struct Middleware: Sendable {\n\n    let _onSet: @Sendable (inout Value) -> Void\n\n    /// Initialize a instance that performs multiple middlewares from start index\n    /// - Parameter onSet: It can access a new value and modify to validate something.\n    public init(\n      onSet: @escaping @Sendable (inout Value) -> Void\n    ) {\n      self._onSet = onSet\n    }\n\n    /// Initialize a instance that performs multiple middlewares from start index\n    /// - Parameter middlewares:\n    public init<C: Collection>(\n      _ middlewares: C\n    ) where C.Element == Middleware, C : Sendable {\n\n      self._onSet = { state in\n        middlewares.forEach {\n          $0._onSet(&state)\n        }\n      }\n\n    }\n\n    /// Raises an Swift.assertionFailure when its new value does not fit the condition.\n    /// - Parameter condition:\n    /// - Returns: A Middleware instance\n    public static func assert(_ condition: @escaping @Sendable (Value) -> Bool, _ failureReason: String? = nil) -> Self {\n      #if DEBUG\n      return .init(onSet: { state in\n        let message = failureReason ?? \"[Verge] \\(Edge<Value>.self) raised a failure in the assertion. \\(state)\"\n        Swift.assert(condition(state), message)\n      })\n      #else\n      return empty()\n      #endif\n    }\n\n    /// Returns a Middleware instance that does nothing.\n    /// - Returns: A Middleware instance\n    public static func empty() -> Self {\n      return .init(onSet: { _ in })\n    }\n\n    /// Returns a Middleware that perform a closure\n    /// It won't mutate the value\n    ///\n    /// - Returns: A Middleware instance\n    public static func `do`(_ perform: @escaping @Sendable (Value) -> Void) -> Self {\n      return .init(onSet: { perform($0) })\n    }\n\n  }\n\n}\n"
  },
  {
    "path": "Sources/Verge/Utility/ReferenceEdge.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\n/**\n Copy-on-Write property wrapper.\n Stores the value in reference type storage.\n */\n@propertyWrapper\n@dynamicMemberLookup\npublic struct ReferenceEdge<State>: EdgeType {\n\n  public static func == (lhs: Self, rhs: Self) -> Bool {\n    lhs.storage === rhs.storage\n  }\n\n  public subscript <U>(dynamicMember keyPath: KeyPath<State, U>) -> U {\n    _read { yield wrappedValue[keyPath: keyPath] }\n  }\n\n  public subscript <U>(dynamicMember keyPath: KeyPath<State, U?>) -> U? {\n    _read { yield wrappedValue[keyPath: keyPath] }\n  }\n\n  public subscript <U>(dynamicMember keyPath: WritableKeyPath<State, U>) -> U {\n    _read { yield wrappedValue[keyPath: keyPath] }\n    _modify { yield &wrappedValue[keyPath: keyPath] }\n  }\n\n  public subscript <U>(dynamicMember keyPath: WritableKeyPath<State, U?>) -> U? {\n    _read { yield wrappedValue[keyPath: keyPath] }\n    _modify { yield &wrappedValue[keyPath: keyPath] }\n  }\n\n\n  public init(wrappedValue: consuming State) {\n    self.storage = ReferenceEdgeStorage(consume wrappedValue)\n  }\n\n  public var _storagePointer: OpaquePointer {\n    return .init(Unmanaged.passUnretained(storage).toOpaque())\n  }\n\n  private var storage: ReferenceEdgeStorage<State>\n\n  public var wrappedValue: State {\n    _read {\n      yield storage.value\n    }\n    _modify {\n      let oldValue = storage.value\n      if isKnownUniquelyReferenced(&storage) {\n        // modify\n        yield &storage.value\n      } else {\n        // make copy\n        storage = ReferenceEdgeStorage(oldValue)\n        yield &storage.value\n      }\n    }\n  }\n\n  public var projectedValue: Self {\n    get {\n      self\n    }\n    mutating set {\n      self = newValue\n    }\n  }\n\n  public func read<T>(_ thunk: (borrowing State) -> T) -> T {\n    thunk(wrappedValue)\n  }\n\n}\n\nextension ReferenceEdge where State : Equatable {\n  public static func == (lhs: Self, rhs: Self) -> Bool {\n    lhs.storage === rhs.storage || lhs.wrappedValue == rhs.wrappedValue\n  }\n}\n\nfinal class ReferenceEdgeStorage<Value>: @unchecked Sendable {\n\n  var value: Value\n\n  init(_ value: consuming Value) {\n    self.value = value\n  }\n\n  func read<T>(_ thunk: (borrowing Value) -> T) -> T {\n    thunk(value)\n  }\n\n}\n\nextension ReferenceEdge: Sendable where State: Sendable {\n\n}\n"
  },
  {
    "path": "Sources/Verge/Utility/ThunkToMainActor.swift",
    "content": "import Foundation\n\n@preconcurrency\n@MainActor\n@inline(__always)\nfunc thunkToMainActor(_ run: @MainActor () throws -> Void) rethrows {\n  assert(Thread.isMainThread)\n  try run()\n}\n\n@preconcurrency\n@MainActor\n@inline(__always)\nfunc thunkToMainActor(_ run: @MainActor () -> Void) {\n  assert(Thread.isMainThread)\n  run()\n}\n"
  },
  {
    "path": "Sources/Verge/Verge.swift",
    "content": "\n@_exported import ConcurrencyTaskManager\n@_exported import Combine\n@_exported import TypedComparator\n@_exported import VergeMacros\n@_exported import StateStruct\n\n"
  },
  {
    "path": "Sources/Verge/macros.swift",
    "content": "\n"
  },
  {
    "path": "Sources/VergeClassic/Emitter.swift",
    "content": "//\n//  Activity.swift\n//  Verge\n//\n//  Created by muukii on 2019/07/16.\n//  Copyright © 2019 muukii. All rights reserved.\n//\n\nimport Foundation\n\nimport RxRelay\n\npublic final class Emitter<Event> {\n  \n  private var source: Signal<Event> {\n    return emitter.asSignal()\n  }\n  \n  private let emitter: PublishRelay<Event> = .init()\n  \n  public init() {\n    \n  }\n  \n  public func emit(onNext: ((Event) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable {\n    return source.emit(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed)\n  }\n  \n  public func asSignal() -> Signal<Event> {\n    return source\n  }\n  \n  public func asObservable() -> Observable<Event> {\n    return source.asObservable()\n  }\n  \n  func makeEmitter() -> Accepter<Event> {\n    return .init(backingEmitter: emitter)\n  }\n}\n\npublic struct Accepter<Event> {\n  \n  private let backingEmitter: PublishRelay<Event>\n  \n  fileprivate init(backingEmitter: PublishRelay<Event>) {\n    self.backingEmitter = backingEmitter\n  }\n  \n  public func accept(_ event: Event) {\n    backingEmitter.accept(event)\n  }\n}\n"
  },
  {
    "path": "Sources/VergeClassic/Extensions.swift",
    "content": "import RxSwift\nimport Foundation\nimport Verge\n\nnonisolated(unsafe) fileprivate var storage_subject: Void?\n\nextension ReadonlyStorage {\n\n  private var subject: BehaviorSubject<Value> {\n\n    objc_sync_enter(self)\n    defer {\n      objc_sync_exit(self)\n    }\n\n    if let associated = objc_getAssociatedObject(self, &storage_subject) as? BehaviorSubject<Value> {\n\n      return associated\n\n    } else {\n\n      let associated = BehaviorSubject<Value>.init(value: value)\n      objc_setAssociatedObject(self, &storage_subject, associated, .OBJC_ASSOCIATION_RETAIN)\n\n      let lock = VergeConcurrency.RecursiveLock()\n\n      sinkEvent { (event) in\n        switch event {\n        case .willUpdate:\n          break\n        case .didUpdate(let newValue):\n          lock.lock(); defer { lock.unlock() }\n          associated.onNext(newValue)\n        case .willDeinit:\n          lock.lock(); defer { lock.unlock() }\n          associated.onCompleted()\n        }\n      }\n\n      return associated\n    }\n  }\n\n  /// Returns an observable sequence\n  ///\n  /// - Returns: Returns an observable sequence\n  public func asObservable() -> Observable<Value> {\n    subject.asObservable()\n  }\n\n  /// Returns an infallible sequence\n  public func asInfallible() -> Infallible<Value> {\n    subject.asInfallible(onErrorRecover: { _ in fatalError() })\n  }\n\n  public func asObservable<S>(keyPath: KeyPath<Value, S>) -> Observable<S> {\n    asObservable()\n      .map { $0[keyPath: keyPath] }\n  }\n\n  /// Returns an infallible sequence\n  public func asInfallible<S>(keyPath: KeyPath<Value, S>) -> Infallible<S> {\n    subject.asInfallible(onErrorRecover: { _ in fatalError() })\n      .map { $0[keyPath: keyPath] }\n  }\n\n  public func asDriver() -> Driver<Value> {\n    subject.asDriver(onErrorDriveWith: .empty())\n  }\n\n  public func asDriver<S>(keyPath: KeyPath<Value, S>) -> Driver<S> {\n    return asDriver()\n      .map { $0[keyPath: keyPath] }\n  }\n\n}\n"
  },
  {
    "path": "Sources/VergeClassic/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>$(DEVELOPMENT_LANGUAGE)</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>FMWK</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>3.0.0</string>\n\t<key>CFBundleVersion</key>\n\t<string>$(CURRENT_PROJECT_VERSION)</string>\n\t<key>NSPrincipalClass</key>\n\t<string></string>\n</dict>\n</plist>\n"
  },
  {
    "path": "Sources/VergeClassic/Storage+Rx.swift",
    "content": "\nimport Foundation\n\nimport RxSwift\nimport RxCocoa\n\n#if !COCOAPODS\nimport Verge\nimport VergeRx\n#endif\n\nextension Storage: ReactiveCompatible {}\n\nnonisolated(unsafe) private var storage_subject: Void?\nnonisolated(unsafe) private var storage_diposeBag: Void?\n\nextension ReadonlyStorage {\n  \n  /// Returns an observable sequence that contains only changed elements according to the `comparer`.\n  ///\n  /// - Parameters:\n  ///   - selector:\n  ///   - comparer:\n  /// - Returns: Returns an observable sequence that contains only changed elements according to the `comparer`.\n  public func changed<S>(_ selector: @escaping (Value) -> S, _ comparer: @escaping (S, S) throws -> Bool) -> Observable<S> {\n    asObservable()\n      .map { selector($0) }\n      .distinctUntilChanged(comparer)\n  }\n  \n  /// Returns an observable sequence that contains only changed elements according to the `comparer`.\n  ///\n  /// - Parameters:\n  ///   - selector:\n  ///   - comparer:\n  /// - Returns: Returns an observable sequence that contains only changed elements according to the `comparer`.\n  public func changed<S : Equatable>(_ selector: @escaping (Value) -> S) -> Observable<S> {\n    changed(selector, ==)\n  }\n  \n  /// Returns an observable sequence that contains only changed elements according to the `comparer`.\n  ///\n  /// - Parameters:\n  ///   - selector:\n  ///   - comparer:\n  /// - Returns: Returns an observable sequence that contains only changed elements according to the `comparer`.\n  public func changedDriver<S>(_ selector: @escaping (Value) -> S, _ comparer: @escaping (S, S) throws -> Bool) -> Driver<S> {\n    asObservable()\n      .map { selector($0) }\n      .distinctUntilChanged(comparer)\n      .asDriver(onErrorRecover: { _ in .empty() })\n  }\n  \n  /// Returns an observable sequence that contains only changed elements according to the `comparer`.\n  ///\n  /// - Parameters:\n  ///   - selector:\n  ///   - comparer:\n  /// - Returns: Returns an observable sequence that contains only changed elements according to the `comparer`.\n  public func changedDriver<S : Equatable>(_ selector: @escaping (Value) -> S) -> Driver<S> {\n    changedDriver(selector, ==)\n  }\n  \n}\n"
  },
  {
    "path": "Sources/VergeClassic/Storage.swift",
    "content": "//\n// Copyright (c) 2019 muukii\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n@_spi(EventEmitter) import Verge\n\nopen class ReadonlyStorage<Value>: @unchecked Sendable, CustomReflectable {\n\n  public enum Event: EventEmitterEventType {\n    case willUpdate\n    case didUpdate(Value)\n    case willDeinit\n\n    public func onComsume() {\n      \n    }\n  }\n\n  private let eventEmitter = EventEmitter<Event>()\n\n  /// Returns a current value with thread-safety.\n  ///\n  /// It causes locking and unlocking with a bit cost.\n  /// It may cause blocking if any other is doing mutation or reading.\n  public final var wrappedValue: Value {\n    return value\n  }\n\n  /// Returns a current value with thread-safety.\n  ///\n  /// It causes locking and unlocking with a bit cost.\n  /// It may cause blocking if any other is doing mutation or reading.\n  public final var value: Value {\n    _lock.lock()\n    defer {\n      _lock.unlock()\n    }\n    return nonatomicValue\n  }\n  \n  fileprivate var nonatomicValue: Value\n  \n  private let _lock: NSRecursiveLock\n  \n  fileprivate let upstreams: [AnyObject]\n\n  public init(\n    _ value: Value,\n    upstreams: [AnyObject] = []\n  ) {\n\n    self._lock = .init()\n    self.nonatomicValue = value\n    self.upstreams = upstreams\n\n    if _verge_signpost_enabled {\n      eventEmitter.addEventHandler { event in\n        switch event {\n        case .willUpdate:\n          vergeSignpostEvent(\"Storage.willUpdate\")\n        case .didUpdate(_):\n          break\n        case .willDeinit:\n          break\n        }\n      }\n    }\n\n  }\n  \n  deinit {\n    eventEmitter.accept(.willDeinit)\n  }\n  \n  public func lock() {\n    _lock.lock()\n  }\n  \n  public func unlock() {\n    _lock.unlock()\n  }\n\n  @discardableResult\n  public final func sinkEvent(subscriber: @escaping (Event) -> Void) -> EventEmitterCancellable {\n    eventEmitter.addEventHandler { event in\n      subscriber(event)\n    }\n  }\n    \n  @inline(__always)\n  fileprivate func notifyWillUpdate(value: Value) {\n    eventEmitter.accept(.willUpdate)\n  }\n  \n  @inline(__always)\n  fileprivate func notifyDidUpdate(value: Value) {\n    eventEmitter.accept(.didUpdate(value))\n  }\n  \n  public var customMirror: Mirror {\n    Mirror(\n      self,\n      children: [\"value\": value],\n      displayStyle: .struct\n    )\n  }\n  \n}\n\nopen class Storage<Value>: ReadonlyStorage<Value>, @unchecked Sendable {\n  \n  public enum UpdateResult {\n    case updated\n    case nothingUpdates\n  }\n\n  @inline(__always)\n  public final func _update(_ update: (inout Value) throws -> UpdateResult) rethrows {\n\n    let signpost = VergeSignpostTransaction(\"Storage.update\")\n    defer {\n      signpost.end()\n    }\n\n    lock()\n    do {\n\n      let previousValue = nonatomicValue\n\n      let result = try update(&nonatomicValue)\n\n      switch result {\n      case .nothingUpdates:\n        unlock()\n      case .updated:\n        let afterValue = nonatomicValue\n        \n        /**\n         Unlocks lock before emitting event to avoid dead-locking.\n         But it causes cracking the order of event.\n         SeeAlso: testOrderOfEvents\n         */\n        unlock()\n      \n        // it's not actual `will` 👨🏻❓\n        notifyWillUpdate(value: previousValue)\n        notifyDidUpdate(value: afterValue)\n            \n      }\n\n    } catch {\n      unlock()\n      throw error\n    }\n  }\n  \n  @discardableResult\n  @inline(__always)\n  public final func update<Result>(_ update: (inout Value) throws -> Result) rethrows -> Result {\n    let signpost = VergeSignpostTransaction(\"Storage.update\")\n    defer {\n      signpost.end()\n    }\n    do {\n      let notifyValue: Value\n      lock()\n      notifyValue = nonatomicValue\n      unlock()\n      notifyWillUpdate(value: notifyValue)\n    }\n    \n    lock()\n    do {\n      let r = try update(&nonatomicValue)\n      let notifyValue = nonatomicValue\n      unlock()\n      // TODO: cause cracking the order of event\n      notifyDidUpdate(value: notifyValue)\n      return r\n    } catch {\n      unlock()\n      throw error\n    }\n  }\n    \n}\n\nextension ReadonlyStorage {\n  \n  /// Transform value with filtering.\n  /// - Attention: Retains upstream storage\n  public func map<U>(\n    filter: @escaping (Value) -> Bool = { _ in false },\n    transform: @escaping (Value) -> U\n  ) -> ReadonlyStorage<U> {\n    \n    let initialValue = transform(value)\n    let newStorage = Storage<U>.init(\n      initialValue,\n      upstreams: [self]\n    )\n\n    var token: EventEmitterCancellable?\n    token = sinkEvent { [weak newStorage] (event) in\n      switch event {\n      case .willUpdate:\n        break\n      case .didUpdate(let newValue):\n        guard !filter(newValue) else {\n          return\n        }\n        newStorage?.update {\n          $0 = transform(newValue)\n        }\n      case .willDeinit:\n        token?.cancel()\n      }\n    }\n\n    return newStorage\n  }\n}\n\n#if canImport(Combine)\n\nimport Combine\n\n// MARK: - Integrate with Combine\n\nnonisolated(unsafe) fileprivate var _didChangeAssociated: Void?\n\n@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)\nextension ReadonlyStorage {\n    \n  public var objectDidChange: AnyPublisher<Value, Never> {\n    valuePublisher.dropFirst().eraseToAnyPublisher()\n  }\n  \n  public var valuePublisher: AnyPublisher<Value, Never> {\n\n    objc_sync_enter(self)\n    defer {\n      objc_sync_exit(self)\n    }\n    \n    if let associated = objc_getAssociatedObject(self, &_didChangeAssociated) as? CurrentValueSubject<Value, Never> {\n      return associated.eraseToAnyPublisher()\n    } else {\n      let associated = CurrentValueSubject<Value, Never>(value)\n      objc_setAssociatedObject(self, &_didChangeAssociated, associated, .OBJC_ASSOCIATION_RETAIN)\n\n      sinkEvent { (event) in\n        switch event {\n        case .willUpdate:\n          break\n        case .didUpdate(let newValue):\n          associated.send(newValue)\n        case .willDeinit:\n          break\n        }\n      }\n      \n      return associated.eraseToAnyPublisher()\n    }\n  }\n    \n}\n\n#endif\n"
  },
  {
    "path": "Sources/VergeClassic/Verge+Extension.swift",
    "content": "\nimport Foundation\n\nimport RxCocoa\n\nextension VergeType {\n  \n  public func commitBinder<S>(\n    name: String = \"\",\n    description: String = \"\",\n    file: StaticString = #file,\n    function: StaticString = #function,\n    line: UInt = #line,\n    mutate: @escaping (inout State, S) -> Void\n    ) -> Binder<S> {\n    \n    return Binder<S>(self) { t, e in\n      t.commit(name, description, file, function, line) { s in\n        mutate(&s, e)\n      }\n    }\n  }\n  \n  public func commitBinder<S>(\n    name: String = \"\",\n    description: String = \"\",\n    file: StaticString = #file,\n    function: StaticString = #function,\n    line: UInt = #line,\n    mutate: @escaping (inout State, S?) -> Void\n    ) -> Binder<S?> {\n    \n    return Binder<S?>(self) { t, e in\n      t.commit(name, description, file, function, line) { s in\n        mutate(&s, e)\n      }\n    }\n  }\n  \n  public func commitBinder<S>(\n    name: String = \"\",\n    description: String = \"\",\n    target: WritableKeyPath<State, S>,\n    file: StaticString = #file,\n    function: StaticString = #function,\n    line: UInt = #line\n    ) -> Binder<S> {\n    \n    return Binder<S>(self) { t, e in\n      t.commit(name, description, file, function, line) { s in\n        s[keyPath: target] = e\n      }\n    }\n  }\n  \n  public func commitBinder<S>(\n    name: String = \"\",\n    description: String = \"\",\n    target: WritableKeyPath<State, S?>,\n    file: StaticString = #file,\n    function: StaticString = #function,\n    line: UInt = #line\n    ) -> Binder<S?> {\n    \n    return Binder<S?>(self) { t, e in\n      t.commit(name, description, file, function, line) { s in\n        s[keyPath: target] = e\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "Sources/VergeClassic/Verge.h",
    "content": "\n#import <Foundation/Foundation.h>\n\n//! Project version number for CycleViewModel.\nFOUNDATION_EXPORT double VergeVersionNumber;\n\n//! Project version string for CycleViewModel.\nFOUNDATION_EXPORT const unsigned char VergeVersionString[];\n\n// In this header, you should import all the public headers of your framework using statements like #import <CycleViewModel/PublicHeader.h>\n\n\n"
  },
  {
    "path": "Sources/VergeClassic/VergeClassic.swift",
    "content": "\nimport Foundation\nimport ObjectiveC\n\n#if !COCOAPODS\nimport Verge\n#endif\n\n@_exported import RxSwift\n@_exported import RxCocoa\n\npublic enum VergeInternalError : Error {\n  case vergeObjectWasDeallocated\n}\n\npublic enum NoActivity {}\npublic struct NoState {\n  public init() {}\n}\n\npublic protocol VergeLogging {\n\n  func didEmit(activity: Any, file: StaticString, function: StaticString, line: UInt, on verge: AnyVergeType)\n  func willDispatch(name: String, description: String, file: StaticString, function: StaticString, line: UInt, on verge: AnyVergeType)\n  func willMutate(name: String, description: String, file: StaticString, function: StaticString, line: UInt, on verge: AnyVergeType)\n  func didMutate(name: String, description: String, file: StaticString, function: StaticString, line: UInt, on verge: AnyVergeType)\n}\n\nextension VergeLogging {\n  static func empty() -> EmptyVergeLogger {\n    return .init()\n  }\n}\n\npublic struct EmptyVergeLogger : VergeLogging {\n\n  public init() {}\n\n  public func didChange(root: Any) {}\n  public func didReplace(root: Any) {}\n  public func didEmit(activity: Any, file: StaticString, function: StaticString, line: UInt, on: AnyVergeType) {}\n  public func willDispatch(name: String, description: String, file: StaticString, function: StaticString, line: UInt, on verge: AnyVergeType) {}\n  public func willMutate(name: String, description: String, file: StaticString, function: StaticString, line: UInt, on verge: AnyVergeType) {}\n  public func didMutate(name: String, description: String, file: StaticString, function: StaticString, line: UInt, on verge: AnyVergeType) {}\n}\n\npublic protocol AnyVergeType : AnyObject {\n\n}\n\n/// The protocol is core of Cycler\npublic protocol VergeType : AnyVergeType {\n  associatedtype State\n  associatedtype Activity  \n  var activity: Emitter<Activity> { get }\n  var state: Storage<State> { get }\n}\n\nextension VergeType {\n  @available(*, deprecated, message: \"For Migration\")\n  public typealias DefaultStore = Storage<State>\n}\n\nnonisolated(unsafe) private var _associated: Void?\n\nextension VergeType {\n\n  private var associated: VergeAssociated<Activity> {\n    if let associated = objc_getAssociatedObject(self, &_associated) as? VergeAssociated<Activity> {\n      return associated\n    } else {\n      let associated = VergeAssociated<Activity>()\n      objc_setAssociatedObject(self, &_associated, associated, .OBJC_ASSOCIATION_RETAIN)\n      return associated\n    }\n  }\n  \n  private var logger: VergeLogging {\n    return associated.logger ?? EmptyVergeLogger.init()\n  }\n\n  public func set(logger: VergeLogging) {\n    lock.lock(); defer { lock.unlock() }\n    associated.logger = logger\n  }\n\n  public var activity: Emitter<Activity> {\n    return associated.activity\n  }\n\n  private var lock: NSRecursiveLock {\n    return associated.lock\n  }\n\n  /// Commit\n  ///\n  /// - Parameters:\n  ///   - name:\n  ///   - description:\n  ///   - file:\n  ///   - function:\n  ///   - line:\n  ///   - mutate:\n  /// - Throws: \n  public func commit(\n    _ name: String = \"\",\n    _ description: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    _ mutate: (inout State) throws -> Void\n    ) rethrows {\n\n    defer {\n      logger.didMutate(name: name, description: description, file: file, function: function, line: line, on: self)\n    }\n\n    logger.willMutate(name: name, description: description, file: file, function: function, line: line, on: self)\n\n    try state.update(mutate)\n  }\n  \n  /// Commit\n  ///\n  /// - Parameters:\n  ///   - name:\n  ///   - description:\n  ///   - file:\n  ///   - function:\n  ///   - line:\n  ///   - newState:\n  public func commit(\n    _ name: String = \"\",\n    _ description: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    replace newState: State\n  ) {\n    \n    defer {\n      logger.didMutate(name: name, description: description, file: file, function: function, line: line, on: self)\n    }\n    \n    logger.willMutate(name: name, description: description, file: file, function: function, line: line, on: self)\n    state.update {\n      $0 = newState\n    }\n  }\n  \n  /// Dispatch\n  ///\n  /// - Parameters:\n  ///   - name:\n  ///   - description:\n  ///   - file:\n  ///   - function:\n  ///   - line:\n  ///   - action:\n  /// - Returns:\n  /// - Throws:\n  @discardableResult\n  public func dispatch<Return>(\n    _ name: String = \"\",\n    _ description: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    _ action: (DispatchingContext<Self>) throws -> Return\n    ) rethrows -> Return {\n    \n    logger.willDispatch(\n      name: name,\n      description: description,\n      file: file,\n      function: function,\n      line: line,\n      on: self\n    )\n    \n    let context = DispatchingContext.init(\n      actionName: name,\n      source: self\n    )\n    \n    let returnValue = try action(context)\n    \n    return returnValue\n\n  }\n  \n  public func send(\n    _ activity: Activity,\n    file: StaticString = #file,\n    function: StaticString = #function,\n    line: UInt = #line\n  ) {\n    \n    self.activity.makeEmitter().accept(activity)\n    logger.didEmit(activity: activity, file: file, function: function, line: line, on: self)\n  }\n   \n  @available(*, deprecated, renamed: \"send\")\n  public func emit(\n    _ activity: Activity,\n    file: StaticString = #file,\n    function: StaticString = #function,\n    line: UInt = #line\n    ) {\n\n    self.activity.makeEmitter().accept(activity)\n    logger.didEmit(activity: activity, file: file, function: function, line: line, on: self)\n  }\n}\n\npublic final class DispatchingContext<Verge : VergeType> {\n\n  private let source: Verge\n  private let state: Storage<Verge.State>\n  private let actionName: String\n\n  public var currentState: Verge.State {\n    return state.value\n  }\n\n  init(actionName: String, source: Verge) {\n    self.source = source\n    self.state = source.state\n    self.actionName = actionName\n  }\n\n  deinit {\n\n  }\n\n  public func commit(\n    _ name: String = \"\",\n    _ description: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    _ mutate: (inout Verge.State) throws -> Void\n    ) rethrows {\n\n    try source.commit(name, description, file, function, line, mutate)\n  }\n  \n  /// Commit\n  ///\n  /// - Parameters:\n  ///   - name:\n  ///   - description:\n  ///   - file:\n  ///   - function:\n  ///   - line:\n  ///   - newState:\n  public func commit(\n    _ name: String = \"\",\n    _ description: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    replace newState: Verge.State\n  ) {\n           \n    source.commit(name, description, file, function, line, replace: newState)\n  }\n  \n  @discardableResult\n  public func dispatch<Return>(\n    _ name: String = \"\",\n    _ description: String = \"\",\n    _ file: StaticString = #file,\n    _ function: StaticString = #function,\n    _ line: UInt = #line,\n    _ action: (DispatchingContext<Verge>) throws -> Return\n    ) rethrows -> Return {\n    \n    try source.dispatch(name, description, file, function, line, action)\n    \n  }\n  \n  public func send(\n    _ activity: Verge.Activity,\n    file: StaticString = #file,\n    function: StaticString = #function,\n    line: UInt = #line\n  ) {\n    source.send(activity, file: file, function: function, line: line)\n  }\n   \n  @available(*, deprecated, renamed: \"send\")\n  public func emit(\n    _ activity: Verge.Activity,\n    file: StaticString = #file,\n    function: StaticString = #function,\n    line: UInt = #line\n    ) {\n    source.send(activity, file: file, function: function, line: line)\n  }\n\n}\n\nfinal class VergeAssociated<Activity> {\n\n  let lock: NSRecursiveLock = .init()\n\n  var logger: VergeLogging?\n\n  lazy var activity: Emitter<Activity> = .init()\n\n  init() {\n\n  }\n}\n"
  },
  {
    "path": "Sources/VergeMacros/Source.swift",
    "content": "\n@freestanding(expression)\npublic macro keyPathMap<U, each T>(_ keyPaths: repeat KeyPath<U, each T>) -> (borrowing U) -> (repeat each T) = #externalMacro(module: \"VergeMacrosPlugin\", type: \"KeyPathMap\")\n"
  },
  {
    "path": "Sources/VergeMacrosPlugin/KeyPathMap.swift",
    "content": "import SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\npublic struct KeyPathMap: Macro {\n\n\n}\n\nextension KeyPathMap: ExpressionMacro {\n\n  public static func expansion(of node: some SwiftSyntax.FreestandingMacroExpansionSyntax, in context: some SwiftSyntaxMacros.MacroExpansionContext) throws -> SwiftSyntax.ExprSyntax {\n\n    let keyPahts = node.argumentList\n\n    let names: [(String, KeyPathComponentListSyntax)] = {\n      return keyPahts.map { keyPath in\n        let components = keyPath.cast(LabeledExprSyntax.self).expression.cast(\n          KeyPathExprSyntax.self\n        ).components\n\n        let name =\n        components\n          .map {\n            $0.cast(KeyPathComponentSyntax.self).component.cast(\n              KeyPathPropertyComponentSyntax.self\n            ).declName.baseName.description\n          }\n          .joined(separator: \"_\")\n\n        return (name, components)\n      }\n    }()\n\n    let line = names.map { arg in\n      \"$0\\(arg.1)\"\n    }\n    .joined(separator: \", \")\n\n    return \"{ (\\(raw: line)) }\"\n  }\n\n}\n"
  },
  {
    "path": "Sources/VergeMacrosPlugin/MacroError.swift",
    "content": "\nimport SwiftDiagnostics\n\npublic struct MacroError: Error, DiagnosticMessage {\n  \n  public var message: String\n  \n  public var diagnosticID: SwiftDiagnostics.MessageID {\n    .init(domain: \"Verge\", id: \"MacroError\")\n  }\n\n  public var severity: SwiftDiagnostics.DiagnosticSeverity = .error\n\n  init(message: String) {\n    self.message = message\n  }\n}\n"
  },
  {
    "path": "Sources/VergeMacrosPlugin/Plugin.swift",
    "content": "import SwiftCompilerPlugin\nimport SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\n@main\nstruct Plugin: CompilerPlugin {\n  let providingMacros: [Macro.Type] = [\n    KeyPathMap.self,\n  ]\n}\n"
  },
  {
    "path": "Sources/VergeNormalizationDerived/DerivedMaking+.swift",
    "content": "import Foundation\nimport Normalization\n@_spi(Internal) import Verge\nimport Verge\n\nextension StoreDriverType {\n\n  fileprivate func derivedEntity<\n    _StorageSelector: StorageSelector,\n    _TableSelector: TableSelector\n  >(\n    selector: AbsoluteTableSelector<_StorageSelector, _TableSelector>,\n    entityID: consuming _TableSelector.Table.Entity.TypedID\n  ) -> Derived<EntityWrapper<_TableSelector.Table.Entity>>\n  where\n    _StorageSelector.Storage == _TableSelector.Storage,\n    _StorageSelector.Source == Self.TargetStore.State\n  {\n\n    return _derived(\n      SingleEntityPipeline(\n        targetIdentifier: entityID,\n        selector: selector\n      ),\n      queue: .passthrough\n    )\n\n  }\n\n  fileprivate func derivedEntityNonNull<\n    _StorageSelector: StorageSelector,\n    _TableSelector: TableSelector\n  >(\n    selector: AbsoluteTableSelector<_StorageSelector, _TableSelector>,\n    entity: consuming _TableSelector.Table.Entity\n  ) -> Derived<NonNullEntityWrapper<_TableSelector.Table.Entity>>\n  where\n  _StorageSelector.Storage == _TableSelector.Storage,\n  _StorageSelector.Source == Self.TargetStore.State\n  {\n\n    return _derived(\n      NonNullSingleEntityPipeline(\n        initialEntity: entity,\n        selector: selector\n      ),\n      queue: .passthrough\n    )\n\n  }\n}\n\npublic enum NormalizedStorageError: Swift.Error {\n  case notFoundEntityToMakeDerived\n}\n\n/**\n The entrypoint to make Derived object from the storage\n */\npublic struct NormalizedStoragePath<\n  Store: DerivedMaking & AnyObject,\n  _StorageSelector: StorageSelector\n>: ~Copyable where Store.State == _StorageSelector.Source {\n  \n  public typealias Storage = _StorageSelector.Storage\n  unowned let store: Store\n  let storageSelector: _StorageSelector\n  \n  public init(\n    store: Store,\n    storageSelector: _StorageSelector\n  ) {\n    \n    self.store = store\n    self.storageSelector = storageSelector\n  }\n  \n  public func table<Selector: TableSelector>(\n    _ selector: Selector\n  ) -> NormalizedStorageTablePath<Store, _StorageSelector, Selector> where Selector.Storage == _StorageSelector.Storage {\n    return .init(\n      store: store,\n      storageSelector: storageSelector,\n      tableSelector: selector\n    )\n  }\n  \n  /**\n   Make a new Derived of a composed object from the storage.\n   This is an effective way to resolving relationship entities into a single object. it's like SQLite's view.\n   \n   ```\n   store.normalizedStorage(.keyPath(\\.db)).derived {\n   MyComposed(\n   book: $0.book.find(...)\n   author: $0.author.find(...)\n   )\n   }\n   ```\n   \n   This Derived makes a new composed object if the storage has updated.\n   There is not filters for entity tables so that Derived possibly makes a new object if not related entity has updated.\n   */\n  public func derived<Composed: Equatable>(query: @escaping @Sendable (Self.Storage) -> Composed) -> Derived<Composed> {\n    return store._derived(QueryPipeline(storageSelector: storageSelector, query: query), queue: .passthrough)\n  }\n}\n\n/**\n The entrypoint to make Derived object from the specific table.\n */\npublic struct NormalizedStorageTablePath<\n  Store: StoreDriverType,\n  _StorageSelector: StorageSelector,\n  _TableSelector: TableSelector\n>: ~Copyable where _StorageSelector.Storage == _TableSelector.Storage, Store.TargetStore.State == _StorageSelector.Source {\n  \n  public typealias Entity = _TableSelector.Table.Entity\n  \n  unowned let store: Store\n  let storageSelector: _StorageSelector\n  let tableSelector: _TableSelector\n  \n  public func derived(\n    from entityID: consuming Entity.TypedID\n  ) -> Derived<EntityWrapper<Entity>> {\n    \n    return store.derivedEntity(\n      selector: .init(storage: storageSelector, table: tableSelector),\n      entityID: entityID\n    )\n    \n  }\n  \n  public func derived(\n    entityIDs: some Sequence<Entity.TypedID>\n  ) -> DerivedResult<Entity, Derived<EntityWrapper<Entity>>> {\n    \n    var result = DerivedResult<Entity, Derived<EntityWrapper<Entity>>>()\n    \n    for id in entityIDs {\n      result.append(\n        derived: store.derivedEntity(\n          selector: .init(storage: storageSelector, table: tableSelector),\n          entityID: id\n        ),\n        id: id\n      )\n    }\n    \n    return result\n    \n  }\n  \n  public func derived(\n    insertionResults: some Sequence<InsertionResult<Entity>>\n  ) -> DerivedResult<Entity, Derived<EntityWrapper<Entity>>> {\n    \n    derived(entityIDs: insertionResults.map { $0.entityID })\n  }\n  \n  // MARK: - NonNull\n  \n  /// Returns a derived object that provides a concrete entity according to the updating source state\n  /// It uses the last value if the entity has been removed source.\n  /// You can get a flag that indicates whether the entity is live or removed which from `NonNullEntityWrapper<T>`\n  ///\n  /// If you call this method in many time, it's not so big issue.\n  /// Because, the backing derived-object to construct itself would be cached.\n  /// A pointer of the result derived object will be different from each other, but the backing source will be shared.\n  ///\n  public func derivedNonNull(\n    entity: consuming Entity\n  ) -> Derived<NonNullEntityWrapper<Entity>> {\n    \n    return store.derivedEntityNonNull(\n      selector: .init(storage: storageSelector, table: tableSelector),\n      entity: entity\n    )\n    \n  }\n  \n  /// Returns a derived object that provides a concrete entity according to the updating source state\n  /// It uses the last value if the entity has been removed source.\n  /// You can get a flag that indicates whether the entity is live or removed which from `NonNullEntityWrapper<T>`\n  ///\n  /// If you call this method in many time, it's not so big issue.\n  /// Because, the backing derived-object to construct itself would be cached.\n  /// A pointer of the result derived object will be different from each other, but the backing source will be shared.\n  ///\n  public func derivedNonNull(\n    entityID: consuming Entity.TypedID\n  ) throws -> Derived<NonNullEntityWrapper<Entity>> {\n    \n    let _initialValue = storageSelector\n      .appending(tableSelector)\n      .table(source: store.store.state.primitive)\n      .find(by: entityID)\n    \n    guard let initalValue = _initialValue else {\n      throw NormalizedStorageError.notFoundEntityToMakeDerived\n    }\n    \n    return store.derivedEntityNonNull(\n      selector: .init(storage: storageSelector, table: tableSelector),\n      entity: initalValue\n    )\n    \n  }\n  \n  public func derivedNonNull(\n    entities: consuming some Sequence<Entity>\n  ) -> NonNullDerivedResult<Entity> {\n    \n    var result = NonNullDerivedResult<Entity>()\n    \n    for entity in entities {\n      result.append(\n        derived: self.derivedNonNull(entity: entity),\n        id: entity.typedID\n      )\n    }\n    \n    return result\n    \n  }\n  \n  /// Returns a derived object that provides a concrete entity according to the updating source state\n  /// It uses the last value if the entity has been removed source.\n  /// You can get a flag that indicates whether the entity is live or removed which from `NonNullEntityWrapper<T>`\n  ///\n  /// If you call this method in many time, it's not so big issue.\n  /// Because, the backing derived-object to construct itself would be cached.\n  /// A pointer of the result derived object will be different from each other, but the backing source will be shared.\n  ///\n  public func derivedNonNull(\n    entityIDs: consuming some Sequence<Entity.TypedID>\n  ) -> NonNullDerivedResult<Entity> {\n    \n    var result = NonNullDerivedResult<Entity>()\n    \n    for id in entityIDs {\n      do {\n        result.append(\n          derived: try self.derivedNonNull(entityID: id),\n          id: id\n        )\n      } catch {\n        // FIXME:\n      }\n    }\n    \n    return result\n  }\n  \n  /// Returns a derived object that provides a concrete entity according to the updating source state\n  /// It uses the last value if the entity has been removed source.\n  /// You can get a flag that indicates whether the entity is live or removed which from `NonNullEntityWrapper<T>`\n  ///\n  /// If you call this method in many time, it's not so big issue.\n  /// Because, the backing derived-object to construct itself would be cached.\n  /// A pointer of the result derived object will be different from each other, but the backing source will be shared.\n  ///\n  public func derivedNonNull(\n    entityIDs: consuming Set<Entity.TypedID>\n  ) -> NonNullDerivedResult<Entity> {\n    \n    var result = NonNullDerivedResult<Entity>()\n    \n    for id in entityIDs {\n      do {\n        result.append(\n          derived: try self.derivedNonNull(entityID: id),\n          id: id\n        )\n      } catch {\n        // FIXME:\n      }\n    }\n    \n    return result\n  }\n  \n  /// Returns a derived object that provides a concrete entity according to the updating source state\n  /// It uses the last value if the entity has been removed source.\n  /// You can get a flag that indicates whether the entity is live or removed which from `NonNullEntityWrapper<T>`\n  ///\n  /// If you call this method in many time, it's not so big issue.\n  /// Because, the backing derived-object to construct itself would be cached.\n  /// A pointer of the result derived object will be different from each other, but the backing source will be shared.\n  ///\n  public func derivedNonNull(\n    insertionResult: InsertionResult<Entity>\n  ) -> Entity.NonNullDerived {\n    derivedNonNull(entity: insertionResult.entity)\n  }\n  \n  /// Returns a derived object that provides a concrete entity according to the updating source state\n  /// It uses the last value if the entity has been removed source.\n  /// You can get a flag that indicates whether the entity is live or removed which from `NonNullEntityWrapper<T>`\n  ///\n  /// If you call this method in many time, it's not so big issue.\n  /// Because, the backing derived-object to construct itself would be cached.\n  /// A pointer of the result derived object will be different from each other, but the backing source will be shared.\n  ///\n  @inline(__always)\n  public func derivedNonNull(\n    insertionResults: some Sequence<InsertionResult<Entity>>\n  ) -> NonNullDerivedResult<Entity> {\n    derivedNonNull(entities: insertionResults.map { $0.entity })\n  }\n}\n"
  },
  {
    "path": "Sources/VergeNormalizationDerived/DerivedResult.swift",
    "content": "import Verge\n\n/// A result instance that contains created Derived object\n/// While creating non-null derived from entity id, some entity may be not founded.\n/// Created derived object are stored in hashed storage to the consumer can check if the entity was not found by the id.\npublic struct DerivedResult<Entity: EntityType, Derived: DerivedType> {\n\n  /// A dictionary of Derived that stored by id\n  /// It's faster than filtering values array to use this dictionary to find missing id or created id.\n  public private(set) var storage: [Entity.TypedID : Derived] = [:]\n\n  /// An array of Derived that orderd by specified the order of id.\n  public private(set) var values: [Derived]\n\n  public init() {\n    self.storage = [:]\n    self.values = []\n  }\n\n  public mutating func append(derived: Derived, id: Entity.TypedID) {\n    storage[id] = derived\n    values.append(derived)\n  }\n\n}\n\npublic typealias NonNullDerivedResult<Entity: EntityType> = DerivedResult<Entity, Entity.NonNullDerived>\n"
  },
  {
    "path": "Sources/VergeNormalizationDerived/EntityType+Typealias.swift",
    "content": "extension EntityType {\n\n  public typealias Derived = Verge.Derived<EntityWrapper<Self>>\n  public typealias NonNullDerived = Verge.Derived<NonNullEntityWrapper<Self>>\n\n}\n\nextension Derived where Value: NonNullEntityWrapperType {\n\n  public var entityID: Value.Entity.TypedID {\n    self.state.id\n  }\n}\n\nextension Derived where Value: EntityWrapperType {\n\n  public var entityID: Value.Entity.TypedID? {\n    self.state.id\n  }\n\n}\n"
  },
  {
    "path": "Sources/VergeNormalizationDerived/EntityWrapper.swift",
    "content": "import Normalization\nimport StateStruct\n\npublic protocol EntityWrapperType: TrackingObject {\n  associatedtype Entity: EntityType\n  \n  var id: Entity.TypedID { get }\n}\n\n/// A value that wraps an entity and results of fetching.\n@Tracking\npublic struct EntityWrapper<Entity: EntityType>: Sendable, EntityWrapperType {\n\n  public let wrapped: Entity?\n  \n  public let id: Entity.TypedID\n\n  public init(id: Entity.TypedID, entity: Entity?) {\n    self.id = id\n    self.wrapped = entity\n  }\n\n}\n\nextension EntityWrapper: Equatable where Entity: Equatable {\n\n}\n\nextension EntityWrapper: Hashable where Entity: Hashable {\n\n}\n\n"
  },
  {
    "path": "Sources/VergeNormalizationDerived/NonNullEntityWrapper.swift",
    "content": "import Normalization\nimport StateStruct\n\npublic protocol NonNullEntityWrapperType: TrackingObject {\n  associatedtype Entity: EntityType  \n  \n  var id: Entity.TypedID { get }\n}\n\n/// A value that wraps an entity and results of fetching.\n@dynamicMemberLookup\n@Tracking\npublic struct NonNullEntityWrapper<Entity: EntityType>: Sendable, NonNullEntityWrapperType {\n\n  /// An entity value\n  public let wrapped: Entity\n\n  /// An identifier\n  public let id: Entity.TypedID\n\n  @available(*, deprecated, renamed: \"isFallBack\")\n  public var isUsingFallback: Bool {\n    isFallBack\n  }\n\n  /// A boolean value that indicates whether the wrapped entity is last value and has been removed from source store.\n  public let isFallBack: Bool\n\n  public init(entity: Entity, isFallBack: Bool) {\n    self.id = entity.entityID\n    self.wrapped = entity\n    self.isFallBack = isFallBack\n  }\n\n  public subscript<Property>(dynamicMember keyPath: KeyPath<Entity, Property>) -> Property {\n    wrapped[keyPath: keyPath]\n  }\n\n}\n\nextension NonNullEntityWrapper: Equatable where Entity: Equatable {}\n\nextension NonNullEntityWrapper: Hashable where Entity: Hashable {}\n\n"
  },
  {
    "path": "Sources/VergeNormalizationDerived/Pipelines.swift",
    "content": "import Normalization\nimport Verge\n\nstruct SingleEntityPipeline<\n  _StorageSelector: StorageSelector,\n  _TableSelector: TableSelector\n>: PipelineType\nwhere _StorageSelector.Storage == _TableSelector.Storage {\n  \n  struct Storage {\n    var tableVersion: UInt64\n    var entity: Entity?\n  }\n  \n  typealias Entity = _TableSelector.Table.Entity\n  typealias Input = _StorageSelector.Source\n  typealias EntityStorage = _StorageSelector.Storage\n  typealias Output = EntityWrapper<Entity>\n  \n  private let selector: AbsoluteTableSelector<_StorageSelector, _TableSelector>\n  private let entityID: Entity.TypedID\n  \n  init(\n    targetIdentifier: Entity.TypedID,\n    selector: consuming AbsoluteTableSelector<_StorageSelector, _TableSelector>\n  ) {\n    self.entityID = targetIdentifier\n    self.selector = selector\n  }\n  \n  func makeStorage() -> Storage {\n    return .init(tableVersion: 0)\n  }\n  \n  func yield(_ input: consuming Input, storage: inout Storage) -> Output {\n    \n    let table = selector.table(source: input)\n    storage.tableVersion = table.updatedMarker.value\n    \n    let result = table.find(by: entityID)\n    storage.entity = result\n    \n    return .init(id: entityID, entity: consume result)\n    \n  }\n  \n  func yieldContinuously(_ input: Input, storage: inout Storage) -> Verge.ContinuousResult<Output> {\n    \n    let table = selector.table(source: input)\n    \n    guard storage.tableVersion != table.updatedMarker.value else {\n      return .noUpdates\n    }\n    \n    storage.tableVersion = table.updatedMarker.value\n    \n    let result = table.find(by: entityID)\n    \n    guard storage.entity != result else {\n      return .noUpdates\n    }\n    \n    storage.entity = result\n    \n    return .new(.init(id: entityID, entity: consume result))\n    \n  }\n  \n}\n\nstruct NonNullSingleEntityPipeline<\n  _StorageSelector: StorageSelector,\n  _TableSelector: TableSelector\n>: PipelineType\nwhere _StorageSelector.Storage == _TableSelector.Storage {\n  \n  struct Storage {\n    var tableVersion: UInt64\n    var entity: Entity?\n  }\n  \n  typealias Entity = _TableSelector.Table.Entity\n  typealias Input = _StorageSelector.Source\n  typealias EntityStorage = _StorageSelector.Storage\n  typealias Output = NonNullEntityWrapper<Entity>\n  \n  private let selector: AbsoluteTableSelector<_StorageSelector, _TableSelector>\n  private let entityID: Entity.TypedID\n  \n  private let latestValue: Entity\n  \n  init(\n    initialEntity: Entity,\n    selector: consuming AbsoluteTableSelector<_StorageSelector, _TableSelector>\n  ) {\n    \n    self.entityID = initialEntity.typedID\n    self.latestValue = initialEntity\n    self.selector = selector\n    \n  }\n  \n  func makeStorage() -> Storage {\n    return .init(tableVersion: 0)\n  }\n  \n  func yield(_ input: consuming Input, storage: inout Storage) -> Output {\n    \n    let table = selector.table(source: input)\n    storage.tableVersion = table.updatedMarker.value\n    \n    let result = table\n      .find(by: entityID)\n    \n    storage.entity = result\n    \n    if let result {\n      return .init(entity: result, isFallBack: false)\n    } else {\n      return .init(entity: latestValue, isFallBack: true)\n    }\n    \n  }\n  \n  func yieldContinuously(_ input: Input, storage: inout Storage) -> Verge.ContinuousResult<Output> {\n    \n    let table = selector.table(source: input)\n    \n    guard storage.tableVersion != table.updatedMarker.value else {\n      return .noUpdates\n    }\n    \n    storage.tableVersion = table.updatedMarker.value\n    \n    let result = table\n      .find(by: entityID)\n    \n    guard storage.entity != result else {\n      return .noUpdates\n    }\n    \n    storage.entity = result\n\n    if let result {\n      return .new(.init(entity: result, isFallBack: false))\n    } else {\n      return .new(.init(entity: latestValue, isFallBack: true))\n    }\n    \n  }\n  \n}\n\nstruct QueryPipeline<\n  _StorageSelector: StorageSelector,\n  Output\n>: PipelineType, Sendable {\n  \n  struct Storage {\n    var storageVersion: UInt64\n  }\n  \n  typealias Input = _StorageSelector.Source\n  typealias EntityStorage = _StorageSelector.Storage\n    \n  private let storageSelector: _StorageSelector\n  private let query: @Sendable (EntityStorage) -> Output\n  \n  init(\n    storageSelector: consuming _StorageSelector,\n    query: @escaping @Sendable (EntityStorage) -> Output\n  ) {\n    self.storageSelector = storageSelector\n    self.query = query\n  }\n  \n  func makeStorage() -> Storage {\n    .init(storageVersion: 0)\n  }\n  \n  func yield(_ input: consuming Input, storage: inout Storage) -> Output {\n    \n    let entityStorage = storageSelector.select(source: input)\n    \n    storage.storageVersion = entityStorage.version\n      \n    let output = query(entityStorage)\n    \n    return output\n    \n  }\n  \n  func yieldContinuously(_ input: Input, storage: inout Storage) -> Verge.ContinuousResult<Output> {\n    \n    let entityStorage = storageSelector.select(source: input)\n    \n    guard entityStorage.version != storage.storageVersion else {\n      return .noUpdates\n    }\n    \n    storage.storageVersion = entityStorage.version\n    \n    let output = query(entityStorage)\n    \n    return .new(output)\n    \n  }\n  \n}\n"
  },
  {
    "path": "Sources/VergeNormalizationDerived/StoreType+.swift",
    "content": "import Verge\nimport Normalization\n\nextension StoreType {\n  \n  public func normalizedStorage<Selector: StorageSelector>(_ selector: Selector) -> NormalizedStoragePath<Self, Selector> {\n    .init(store: self, storageSelector: selector)\n  }\n  \n}\n"
  },
  {
    "path": "Sources/VergeNormalizationDerived/VergeNormalizationDerived.swift",
    "content": "@_exported import Verge\n@_exported import Normalization\n"
  },
  {
    "path": "Sources/VergeRx/Extensions.swift",
    "content": "//\n// Copyright (c) 2020 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#if !COCOAPODS\nimport Verge\nimport Combine\n#endif\n\nimport RxSwift\n\nextension VergeAnyCancellable: RxSwift.Disposable {\n  public func dispose() {\n    cancel()\n  }\n}\n\nextension Publisher {\n  /// Returns an Observable<Output> representing the underlying\n  /// Publisher. Upon subscription, the Publisher's sink pushes\n  /// events into the Observable. Upon disposing of the subscription,\n  /// the sink is cancelled.\n  ///\n  /// - returns: Observable<Output>\n  func asObservable() -> Observable<Output> {\n    Observable<Output>.create { observer in\n      let cancellable = self.sink(\n        receiveCompletion: { completion in\n          switch completion {\n          case .finished:\n            observer.onCompleted()\n          case .failure(let error):\n            observer.onError(error)\n          }\n        },\n        receiveValue: { value in\n          observer.onNext(value)\n        })\n      \n      return Disposables.create { cancellable.cancel() }\n    }\n  }\n}\n"
  },
  {
    "path": "Sources/VergeRx/Store+Rx.swift",
    "content": "\nimport Foundation\n\n#if !COCOAPODS\n@_spi(Package) import Verge\n@_spi(EventEmitter) import Verge\n#endif\n\nimport RxSwift\nimport RxCocoa\n\n\nextension Store: ReactiveCompatible {}\n\nextension Reactive where Base : StoreDriverType {\n    \n  /// An observable that repeatedly emits the changes when state updated\n  ///\n  /// Guarantees to emit the first event on started subscribing.\n  ///\n  /// - Parameter startsFromInitial: Make the first changes object's hasChanges always return true.\n  /// - Returns:\n  public func stateObservable() -> Observable<Changes<Base.TargetStore.State>> {\n    base.store.asStore()._statePublisher().asObservable()\n  }\n\n  public func activitySignal() -> Signal<Base.TargetStore.Activity> {\n    base.store.asStore()._activityPublisher().asObservable().asSignal(onErrorRecover: { _ in Signal.empty() })\n  }\n  \n}\n\nextension StoreDriverType {\n\n  @_disfavoredOverload\n  public var rx: Reactive<Self> {\n    return .init(self)\n  }\n\n}\n\nextension ObservableType where Element : ChangesType, Element.Value : Equatable {\n  \n  /// Returns an observable sequence that contains only changed elements according to the `comparer`.\n  ///\n  /// Using Changes under\n  ///\n  /// - Parameters:\n  ///   - selector:\n  ///   - compare:\n  /// - Returns: Returns an observable sequence that contains only changed elements according to the `comparer`.\n  public func changed() -> Observable<Element.Value> {\n    changed({ $0 })\n  }\n\n}\n\nextension ObservableType where Element : ChangesType {\n      \n  /// Returns an observable sequence that contains only changed elements according to the `comparer`.\n  ///\n  /// Using Changes under\n  ///\n  /// - Parameters:\n  ///   - selector:\n  ///   - compare:\n  /// - Returns: Returns an observable sequence that contains only changed elements according to the `comparer`.\n  public func changed<S>(_ selector: @escaping (Element.Value) -> S, _ comparer: some TypedComparator<S>) -> Observable<S> {\n\n    return flatMap { changes -> Observable<S> in\n      let _r = changes.asChanges().ifChanged(selector, comparer) { value in\n        return value\n      }\n      return _r.map { .just($0) } ?? .empty()\n    }\n  }\n  \n  /// Returns an observable sequence that contains only changed elements according to the `comparer`.\n  ///\n  /// Using Changes under\n  ///\n  /// - Parameters:\n  ///   - selector:\n  ///   - comparer:\n  /// - Returns: Returns an observable sequence that contains only changed elements according to the `comparer`.\n  public func changed<S : Equatable>(_ selector: @escaping (Element.Value) -> S) -> Observable<S> {\n    return changed(selector, EqualityComparator())\n  }\n\n}\n"
  },
  {
    "path": "Sources/VergeTiny/Source.swift",
    "content": "//\n// Copyright (c) 2021 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Foundation\n\npublic struct DynamicProperty<T> {\n\n  public var value: T? {\n    get {\n\n      storage.lock.lock()\n\n      // Do not directly cast using `as?`.\n      guard let value = storage.synchronized_value(for: key) else {\n        storage.lock.unlock()\n        return nil\n      }\n\n      storage.lock.unlock()\n\n      return value as? T\n    }\n    nonmutating set {\n      storage.lock.lock()\n      storage.synchronized_setValue(newValue as Any, for: key)\n      storage.lock.unlock()\n    }\n  }\n\n  public let key: String\n  private let storage: DynamicPropertyStorage.Storage<Any>\n\n  init(key: String, storage: DynamicPropertyStorage.Storage<Any>) {\n    self.key = key\n    self.storage = storage\n  }\n\n  private func _doIfChanged(\n    value: T,\n    compare: (T, T) -> Bool,\n    perform: (T) -> Void\n  ) {\n\n    storage.lock.lock()\n\n    // Do not directly cast using `as?`.\n    // To detect storage does not have value for key when T is optinal type.\n    guard let cachedRawValue = storage.synchronized_value(for: key) else {\n      storage.synchronized_setValue(value, for: key)\n      storage.lock.unlock()\n      perform(value)\n      return\n    }\n\n    let cachedValue = cachedRawValue as! T\n\n    guard compare(cachedValue, value) == false else {\n      storage.lock.unlock()\n      return\n    }\n\n    storage.synchronized_setValue(value, for: key)\n\n    storage.lock.unlock()\n\n    perform(value)\n\n  }\n\n  /// [Experimental]\n  /// should be renamed\n  public func doIfChanged(\n    _ value: T,\n    _ compare: (T, T) -> Bool,\n    _ perform: (T) -> Void\n  ) {\n\n    _doIfChanged(\n      value: value,\n      compare: compare,\n      perform: perform\n    )\n\n  }\n\n  /// [Experimental]\n  /// should be renamed\n  public func doIfChanged(\n    _ value: T,\n    _ perform: (T) -> Void\n  ) where T : Equatable {\n\n    _doIfChanged(\n      value: value,\n      compare: ==,\n      perform: perform\n    )\n\n  }\n\n}\n\npublic final class DynamicPropertyStorage {\n\n  final class Storage<T> {\n\n    let lock = NSLock()\n\n    var rawStorage: [String : T] = [:]\n\n    func synchronized_value(for key: String) -> T? {\n\n      guard let value = rawStorage[key] else {\n        return nil\n      }\n\n      return value\n    }\n\n    func synchronized_setValue(_ value: T, for key: String) {\n      rawStorage[key] = value\n    }\n\n    func synchronized_removeValue(for key: String) {\n      rawStorage.removeValue(forKey: key)\n    }\n  }\n\n  struct CodeLocation: Hashable {\n    let file: String\n    let line: UInt\n    let column: UInt\n\n    func makeKey() -> String {\n      \"\\(file).\\(line).\\(column)\"\n    }\n  }\n\n  private let _anyStorage: Storage<Any> = .init()\n\n  public init() {\n    \n  }\n\n  public func defineProperty<T>(\n    file: StaticString = #file,\n    line: UInt = #line,\n    column: UInt = #column,\n    _ type: T.Type\n  ) -> DynamicProperty<T> {\n\n    let codeLocation = CodeLocation(file: file.description, line: line, column: column)\n\n    return .init(key: codeLocation.makeKey(), storage: _anyStorage)\n\n  }\n\n  /// [Experimental]\n  /// should be renamed\n  public func doIfChanged<T>(\n    file: StaticString = #file,\n    line: UInt = #line,\n    column: UInt = #column,\n    _ value: T,\n    _ compare: (T, T) -> Bool,\n    _ perform: (T) -> Void\n  ) {\n\n    let property = defineProperty(file: file, line: line, column: column, T.self)\n\n    property.doIfChanged(\n      value,\n      compare,\n      perform\n    )\n\n  }\n\n  /// [Experimental]\n  /// should be renamed\n  public func doIfChanged<T>(\n    file: StaticString = #file,\n    line: UInt = #line,\n    column: UInt = #column,\n    _ value: T,\n    _ perform: (T) -> Void\n  ) where T : Equatable {\n\n    let property = defineProperty(file: file, line: line, column: column, T.self)\n\n    property.doIfChanged(\n      value,\n      perform\n    )\n\n  }\n\n}\n\nnonisolated(unsafe) private var _storageKey: Void?\n\nextension NSObject {\n\n  public var associatedProperties: DynamicPropertyStorage {\n\n    objc_sync_enter(self)\n    defer {\n      objc_sync_exit(self)\n    }\n\n    if let associated = objc_getAssociatedObject(self, &_storageKey)\n        as? DynamicPropertyStorage\n    {\n      return associated\n    } else {\n      let associated = DynamicPropertyStorage()\n      objc_setAssociatedObject(self, &_storageKey, associated, .OBJC_ASSOCIATION_RETAIN)\n      return associated\n    }\n\n  }\n\n}\n\n\n"
  },
  {
    "path": "StoreReaderDemo/StoreReaderDemo/Assets.xcassets/AccentColor.colorset/Contents.json",
    "content": "{\n  \"colors\" : [\n    {\n      \"idiom\" : \"universal\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "StoreReaderDemo/StoreReaderDemo/Assets.xcassets/AppIcon.appiconset/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"idiom\" : \"universal\",\n      \"platform\" : \"ios\",\n      \"size\" : \"1024x1024\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "StoreReaderDemo/StoreReaderDemo/Assets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "StoreReaderDemo/StoreReaderDemo/ContentView.swift",
    "content": "//\n//  ContentView.swift\n//  StoreReaderDemo\n//\n//  Created by Muukii on 2023/05/11.\n//\n\nimport SwiftUI\nimport SwiftUIHosting\nimport Verge\n\nstruct ContentView: View {\n  var body: some View {\n    VStack {\n      Image(systemName: \"globe\")\n        .imageScale(.large)\n        .foregroundColor(.accentColor)\n      Text(\"Hello, world!\")\n    }\n    .padding()\n  }\n}\n\nstruct ContentView_Previews: PreviewProvider {\n  static var previews: some View {\n    ContentView()\n  }\n}\n\nenum Preview_StoreReader: PreviewProvider {\n\n  static var previews: some View {\n\n    Group {\n\n      ViewHosting().previewDisplayName(\"ViewHosting\")\n\n    }\n\n  }\n\n  struct ViewHosting: UIViewRepresentable {\n\n    func makeUIView(context: Context) -> UIView {\n      _View()\n    }\n\n    func updateUIView(_ uiView: UIView, context: Context) {\n\n    }\n  }\n\n  struct BindingView: View {\n\n    @Binding var value: String\n\n    init(value: Binding<String>) {\n      self._value = value\n    }\n\n    var body: some View {\n      VStack {\n        Text(value)\n        Button(\"Up\") {\n          value += \"A\"\n        }\n      }\n    }\n  }\n\n  final class _View: UIView {\n\n    init() {\n      super.init(frame: .null)\n\n      @UIState var value: String = \"BBB\"\n\n      let view = SwiftUIHostingView {\n        StoreReader($value) { valueProxy in\n          BindingView(\n            value: valueProxy.binding(\\.self)\n          )\n        }\n      }\n\n      addSubview(view)\n      view.frame = bounds\n      view.autoresizingMask = [.flexibleWidth, .flexibleHeight]\n\n    }\n\n    required init?(coder: NSCoder) {\n      fatalError(\"init(coder:) has not been implemented\")\n    }\n\n  }\n}\n"
  },
  {
    "path": "StoreReaderDemo/StoreReaderDemo/Preview Content/Preview Assets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "StoreReaderDemo/StoreReaderDemo/StoreReaderDemoApp.swift",
    "content": "//\n//  StoreReaderDemoApp.swift\n//  StoreReaderDemo\n//\n//  Created by Muukii on 2023/05/11.\n//\n\nimport SwiftUI\n\n@main\nstruct StoreReaderDemoApp: App {\n    var body: some Scene {\n        WindowGroup {\n            ContentView()\n        }\n    }\n}\n"
  },
  {
    "path": "TaskManagerPlayground/TaskManagerPlayground/Assets.xcassets/AccentColor.colorset/Contents.json",
    "content": "{\n  \"colors\" : [\n    {\n      \"idiom\" : \"universal\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "TaskManagerPlayground/TaskManagerPlayground/Assets.xcassets/AppIcon.appiconset/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"idiom\" : \"universal\",\n      \"platform\" : \"ios\",\n      \"size\" : \"1024x1024\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "TaskManagerPlayground/TaskManagerPlayground/Assets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "TaskManagerPlayground/TaskManagerPlayground/Book.swift",
    "content": "import SwiftUI\nimport Verge\n\nstruct BookVergeTaskManager: View, PreviewProvider {\n  var body: some View {\n    Content()\n  }\n\n  static var previews: some View {\n    Self()\n  }\n\n  private struct Content: View {\n\n    @StateObject var viewModel: ViewModel = .init()\n    @State var count = 0\n\n    var body: some View {\n      VStack {\n\n        Button(\"Wait\") {\n          count += 1\n          viewModel.fetch(token: count.description)\n        }\n\n        Button(\"Override\") {\n          count += 1\n          viewModel.fetchOverride(token: count.description)\n        }\n\n        Button(\"Cancel All\") {\n          viewModel.cancelAll()\n        }\n\n      }\n    }\n  }\n\n  final class ViewModel: StoreComponentType, ObservableObject {\n\n    struct State: Equatable {\n\n    }\n\n    let store = Store<State, Never>(initialState: .init())\n\n    init() {\n\n    }\n\n    enum _Key: TaskKeyType {\n\n    }\n\n    func cancelAll() {\n      Task {\n        await store.taskManager.cancelAll()\n      }\n    }\n\n    func fetchOverride(token: String) {\n      Task {\n        let ref = await store.taskManager.task(\n          label: token,\n          key: .init(_Key.self),\n          mode: .dropCurrent\n        ) {\n          await networking(token: token)\n        }\n\n        let r = Resource(name: token)\n\n        Task {\n          print(\"-> Ref\", token)\n          let _ = try? await ref.value\n          print(\"<- Ref\", token)\n          withExtendedLifetime(r) {}\n        }\n      }\n    }\n\n    func fetch(token: String) {\n      Task {\n        let ref = await store.taskManager.task(\n          label: token,\n          key: .init(_Key.self),\n          mode: .waitInCurrent\n        ) {\n          await networking(token: token)\n        }\n\n        let r = Resource(name: token)\n\n        Task {\n          print(\"-> Ref\", token)\n          let _ = try? await ref.value\n          print(\"<- Ref\", token)\n          withExtendedLifetime(r) {}\n        }\n      }\n    }\n\n  }\n\n}\n\nprivate final class Resource {\n\n  private let name: String\n\n  init(name: String) {\n    self.name = name\n  }\n\n  deinit {\n    print(\"Deinit\", name)\n  }\n}\n\nprivate func networking(token: String) async {\n  print(\"✈️ Start\", token)\n  try? await Task.sleep(nanoseconds: 2_000_000_000)\n  if Task.isCancelled {\n    print(\"❌ Cancelled\", token)\n  } else {\n    print(\"✅ Done\", token)\n  }\n}\n"
  },
  {
    "path": "TaskManagerPlayground/TaskManagerPlayground/ContentView.swift",
    "content": "//\n//  ContentView.swift\n//  TaskManagerPlayground\n//\n//  Created by Muukii on 2023/04/07.\n//\n\nimport SwiftUI\n\nstruct ContentView: View {\n  var body: some View {\n    BookVergeTaskManager()\n  }\n}\n\nstruct ContentView_Previews: PreviewProvider {\n  static var previews: some View {\n    ContentView()\n  }\n}\n"
  },
  {
    "path": "TaskManagerPlayground/TaskManagerPlayground/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict/>\n</plist>\n"
  },
  {
    "path": "TaskManagerPlayground/TaskManagerPlayground/Preview Content/Preview Assets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "TaskManagerPlayground/TaskManagerPlayground/TaskManagerPlaygroundApp.swift",
    "content": "//\n//  TaskManagerPlaygroundApp.swift\n//  TaskManagerPlayground\n//\n//  Created by Muukii on 2023/04/07.\n//\n\nimport SwiftUI\n\n@main\nstruct TaskManagerPlaygroundApp: App {\n    var body: some Scene {\n        WindowGroup {\n            ContentView()\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/All.xctestplan",
    "content": "{\n  \"configurations\" : [\n    {\n      \"id\" : \"CED3C5CF-7541-4D76-8BD7-C398F4B5517C\",\n      \"name\" : \"Basic\",\n      \"options\" : {\n\n      }\n    },\n    {\n      \"id\" : \"C8A4A8E7-7082-47B7-8C0E-8D4DC5BF01E2\",\n      \"name\" : \"Thread Sanitization\",\n      \"options\" : {\n        \"threadSanitizerEnabled\" : true,\n        \"undefinedBehaviorSanitizerEnabled\" : true\n      }\n    },\n    {\n      \"id\" : \"1C451F14-8D88-40D3-949E-08EC2939DA3D\",\n      \"name\" : \"Address Sanitization\",\n      \"options\" : {\n        \"addressSanitizer\" : {\n          \"detectStackUseAfterReturn\" : true,\n          \"enabled\" : true\n        },\n        \"undefinedBehaviorSanitizerEnabled\" : true\n      }\n    }\n  ],\n  \"defaultOptions\" : {\n\n  },\n  \"testTargets\" : [\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:Verge.xcodeproj\",\n        \"identifier\" : \"4B475BC4239ADE1C008A03E1\",\n        \"name\" : \"VergeORMTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"skippedTests\" : [\n        \"ReproduceDeadlockTests\\/testReproduceDeadlock()\"\n      ],\n      \"target\" : {\n        \"containerPath\" : \"container:Verge.xcodeproj\",\n        \"identifier\" : \"4B1743A623C767670074C457\",\n        \"name\" : \"VergeRxTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"skippedTests\" : [\n        \"GetterTests\\/testChain()\",\n        \"VergeStoreTests\\/testOrderOfEvents()\"\n      ],\n      \"target\" : {\n        \"containerPath\" : \"container:Verge.xcodeproj\",\n        \"identifier\" : \"4B68394323705ACD002FFC5A\",\n        \"name\" : \"VergeTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:Verge.xcodeproj\",\n        \"identifier\" : \"4B65F8EB1FB4C0DC00A90A67\",\n        \"name\" : \"VergeClassicTests\"\n      }\n    }\n  ],\n  \"version\" : 1\n}\n"
  },
  {
    "path": "Tests/DemoState.swift",
    "content": "//\n//  DemoState.swift\n//  VergeStoreTests\n//\n//  Created by muukii on 2020/04/21.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\nimport Verge\nimport XCTest\nimport Observation\n\nstruct NonEquatable: Sendable {\n  let id = UUID()\n}\nstruct OnEquatable: Equatable, Sendable {\n  let id = UUID()\n}\n\nstruct DemoState: StateType, Sendable {\n\n  struct Inner: Equatable {\n    var name: String = \"\"\n  }\n\n  var name: String = \"\"\n  var count: Int = 0\n  var items: [Int] = []\n  var inner: Inner = .init()\n\n  @Edge var nonEquatable: NonEquatable = .init()\n\n  @Edge var onEquatable: OnEquatable = .init()\n\n  mutating func updateFromItself() {\n    count += 1\n  }\n\n}\n\nenum DemoActivity {\n  case something\n}\n\n#if canImport(Verge)\n\nimport Verge\n\nfinal class DemoStore: Verge.Store<DemoState, DemoActivity> {\n\n  init() {\n    super.init(initialState: .init(), logger: nil)\n  }\n\n  func increment() {\n    commit {\n      $0.count += 1\n    }\n  }\n\n  func empty() {\n    commit { _ in\n    }\n  }\n\n}\n\n#endif\n"
  },
  {
    "path": "Tests/VergeMacrosTests/KeyPathMapTests.swift",
    "content": "import SwiftSyntaxMacros\nimport SwiftSyntaxMacrosTestSupport\nimport XCTest\n\n#if canImport(VergeMacrosPlugin)\nimport VergeMacrosPlugin\n\nfinal class KeyPathMapTests: XCTestCase {\n\n  func test_() {\n\n    assertMacroExpansion(\n      #\"\"\"\n      #keyPathMap(\\.foo)\n      \"\"\"#,\n      expandedSource: #\"\"\"\n        {\n            ($0.foo)\n        }\n        \"\"\"#,\n      macros: [\"keyPathMap\": KeyPathMap.self]\n    )\n\n    assertMacroExpansion(\n      #\"\"\"\n      #keyPathMap(\\.foo, \\.aaa)\n      \"\"\"#,\n      expandedSource: #\"\"\"\n        {\n            ($0.foo, $0.aaa)\n        }\n        \"\"\"#,\n      macros: [\"keyPathMap\": KeyPathMap.self]\n    )\n\n    assertMacroExpansion(\n      #\"\"\"\n      #keyPathMap(\\State.foo, \\.aaa)\n      \"\"\"#,\n      expandedSource: #\"\"\"\n        {\n            ($0.foo, $0.aaa)\n        }\n        \"\"\"#,\n      macros: [\"keyPathMap\": KeyPathMap.self]\n    )\n  }\n\n}\n\n#endif\n"
  },
  {
    "path": "Tests/VergeNormalizationDerivedTests/CombiningTests.swift",
    "content": "import XCTest\nimport VergeNormalizationDerived\n\nfinal class CombiningTests: XCTestCase {\n\n  func test_combine() {\n\n    let store = Store<DemoState, Never>(\n      initialState: .init()\n    )\n\n    struct View: Equatable {\n      var book: Book?\n      var author: Author?\n    }\n\n    let derived = store.normalizedStorage(.keyPath(\\.db)).derived { storage in\n      View(\n        book: storage.book.find(by: .init(\"1\")),\n        author: storage.author.find(by: .init(\"1\"))\n      )\n    }\n\n    let exp = expectation(description: \"call\")\n    exp.expectedFulfillmentCount = 3\n\n    let sub = derived.sinkState { view in\n      exp.fulfill()\n    }\n\n    store.commit {\n      $0.db.performBatchUpdates { t in\n        t.modifying.book.insert(Book(rawID: \"1\", authorID: .init(\"1\")))\n        t.modifying.author.insert(Author(rawID: \"1\", name: \"Hiroshi\"))\n      }\n    }\n\n    // no affects\n    store.commit {\n      $0.count += 1\n    }\n\n    _ = store.commit {\n      $0.db.performBatchUpdates { t in\n        t.modifying.author.insert(Author(rawID: \"1\", name: \"Hiroshi Kimura\"))\n      }\n    }\n\n    wait(for: [exp], timeout: 10)\n\n    XCTAssertEqual(derived.state.author?.name, \"Hiroshi Kimura\")\n\n    _ = sub\n  }\n}\n\n"
  },
  {
    "path": "Tests/VergeNormalizationDerivedTests/DemoState.swift",
    "content": "import VergeNormalizationDerived\n\n@Tracking\nstruct DemoState {\n\n  var count: Int = 0\n\n  var db: Database = .init()\n\n  struct DatabaseSelector: StorageSelector {\n    typealias Source = DemoState\n    typealias Storage = Database\n\n    func select(source: consuming DemoState) -> Database {\n      source.db\n    }\n  }\n}\n\nextension StorageSelector where Self == DemoState.DatabaseSelector {\n  static var db: Self {\n    DemoState.DatabaseSelector()\n  }\n}\n\n@NormalizedStorage\nstruct Database {\n\n  @Table\n  var book: Tables.Hash<Book> = .init()\n\n  @Table\n  var book2: Tables.Hash<Book> = .init()\n\n  @Table\n  var author: Tables.Hash<Author> = .init()\n\n}\n\nextension Database {\n\n}\n\nstruct Book: EntityType, Hashable {\n\n  typealias TypedIdentifierRawValue = String\n\n  var typedID: TypedID {\n    .init(rawID)\n  }\n\n  let rawID: String\n  let authorID: Author.TypedID\n  var name: String = \"initial\"\n}\n\nstruct Author: EntityType {\n\n  typealias TypedIdentifierRawValue = String\n    \n  var typedID: TypedID {\n    .init(rawID)\n  }\n\n  let rawID: String\n  var name: String = \"\"\n\n  static let anonymous: Author = .init(rawID: \"anonymous\")\n}\n"
  },
  {
    "path": "Tests/VergeNormalizationDerivedTests/VergeNormalizationDerivedTests.swift",
    "content": "import VergeNormalizationDerived\nimport XCTest\nimport os.lock\n\nextension Store where State == DemoState {\n\n  var database: NormalizedStoragePath<Store, DemoState.DatabaseSelector> {\n    return .init(store: self, storageSelector: .init())\n  }\n\n}\n\nfinal class VergeNormalizationDerivedTests: XCTestCase {\n\n  func test_subscribe() {\n\n    let exp = expectation(description: \"wait\")\n\n    let store = Store<DemoState, Never>(\n      initialState: .init()\n    )\n\n    let derived = store\n      .normalizedStorage(.keyPath(\\.db))\n      .table(.keyPath(\\.book))\n      .derived(from: Book.TypedID.init(\"1\"))\n\n    let received: OSAllocatedUnfairLock<[Book?]> = .init(initialState: [])\n\n    derived.sinkState { value in\n      received.withLock {\n        $0.append(value.primitive.wrapped)\n      }\n      if value.primitive.wrapped != nil {\n        exp.fulfill()\n      }\n    }\n    .storeWhileSourceActive()\n\n    _ = store.commit {\n      $0.db.performBatchUpdates { t in\n        t.modifying.book.insert(.init(rawID: \"1\", authorID: .init(\"muukii\")))\n      }\n    }\n\n    wait(for: [exp])\n\n    XCTAssertEqual(received.withLock { $0 }, [nil, .init(rawID: \"1\", authorID: .init(\"muukii\"))])\n\n    withExtendedLifetime(derived, {})\n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeRxTests/ChangedOperatorTests.swift",
    "content": "//\n//  ChangedOperatorTests.swift\n//  VergeRxTests\n//\n//  Created by muukii on 2020/05/01.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\n\nimport Foundation\n\nimport XCTest\n\nimport VergeRx\nimport Verge\n\nclass ChangedOperatorTests: XCTestCase {\n  \n  let store = Store<DemoState, Never>.init(initialState: .init(), logger: nil)\n  \n  func testChanged() {\n    \n\n    let count = store.derived(.map(\\.count))\n    \n    let exp = expectation(description: \"\")\n    exp.assertForOverFulfill = true\n    exp.expectedFulfillmentCount = 3\n    \n    _ = count.rx.stateObservable()\n      .changed({ $0.description })\n      .subscribe(onNext: { _ in\n        exp.fulfill()\n      })\n    \n    store.commit {\n      $0.count += 1\n    }\n    store.commit {\n      $0.count += 1\n    }\n    store.commit { _ in\n     \n    }\n    wait(for: [exp], timeout: 2)\n  }\n}\n"
  },
  {
    "path": "Tests/VergeRxTests/DemoState.swift",
    "content": "//\n//  DemoState.swift\n//  VergeStoreTests\n//\n//  Created by muukii on 2020/04/21.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\nimport Verge\nimport XCTest\nimport Observation\n\nstruct NonEquatable: Sendable {\n  let id = UUID()\n}\nstruct OnEquatable: Equatable, Sendable {\n  let id = UUID()\n}\n\n@Tracking\nstruct DemoState: Sendable {\n\n  struct Inner: Equatable {\n    var name: String = \"\"\n  }\n\n  var name: String = \"\"\n  var count: Int = 0\n  var items: [Int] = []\n  var inner: Inner = .init()\n\n  var nonEquatable: NonEquatable = .init()\n\n  var onEquatable: OnEquatable = .init()\n\n  mutating func updateFromItself() {\n    count += 1\n  }\n\n}\n\nenum DemoActivity {\n  case something\n}\n\n#if canImport(Verge)\n\nimport Verge\n\nfinal class DemoStore: Verge.Store<DemoState, DemoActivity> {\n\n  init() {\n    super.init(initialState: .init(), logger: nil)\n  }\n\n  func increment() {\n    commit {\n      $0.count += 1\n    }\n  }\n\n  func empty() {\n    commit { _ in\n    }\n  }\n\n}\n\n#endif\n"
  },
  {
    "path": "Tests/VergeRxTests/ReproduceDeadlockTests.swift",
    "content": "//\n//  ReproduceDeadlockTests.swift\n//  VergeStoreTests\n//\n//  Created by muukii on 2020/04/20.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\n\nimport XCTest\nimport Verge\nimport VergeRx\n\nclass ReproduceDeadlockTests: XCTestCase {\n  \n  final class StoreWrapper: StoreDriverType, Sendable {\n\n    struct State: Equatable {\n      var count = 0\n    }\n        \n    let store = Store<State, Never>.init(initialState: .init(), logger: nil)\n\n    init() {\n    }\n  }\n  \n  func testReproduceDeadlock() {\n    \n    let store = StoreWrapper()\n        \n    _ = store.rx.stateObservable().bind { state in\n      if state.count == 1 {\n        let group = DispatchGroup()\n        group.enter()\n        DispatchQueue.global().async {\n          store.commit { $0.count += 1 }\n          group.leave()\n        }\n        group.wait()\n      }\n    }\n        \n    store.commit {\n      $0.count += 1\n    }\n              \n  }\n}\n"
  },
  {
    "path": "Tests/VergeRxTests/SubjectCompletionTests.swift",
    "content": "//\n//  SubjectCompletionTests.swift\n//  VergeRxTests\n//\n//  Created by Muukii on 2021/04/06.\n//  Copyright © 2021 muukii. All rights reserved.\n//\n\nimport Foundation\nimport RxSwift\nimport Verge\nimport VergeRx\nimport XCTest\n\nfinal class SubjectCompletionTests: XCTestCase {\n\n  func testStateObsevableCompletion() {\n\n    var subscription: Disposable?\n\n    var store: DemoStore? = DemoStore()\n    weak var weakStore: DemoStore? = store\n\n    subscription = store?.rx.stateObservable()\n      .subscribe()\n\n    XCTAssertNotNil(weakStore)\n\n    store = nil\n\n    subscription?.dispose()\n\n    XCTAssertNil(weakStore)\n  }\n\n  func testActivityObservableCompletion() {\n\n    var subscription: Disposable?\n\n    var store: DemoStore? = DemoStore()\n    weak var weakStore: DemoStore? = store\n\n    subscription = store?.rx.activitySignal()\n      .emit()\n\n    XCTAssertNotNil(weakStore)\n\n    store = nil\n\n    subscription?.dispose()\n\n    XCTAssertNil(weakStore)\n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeRxTests/VergeRxTests.swift",
    "content": "//\n//  VergeRxTests.swift\n//  VergeRxTests\n//\n//  Created by muukii on 2020/01/09.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport XCTest\n\nimport VergeRx\n\nclass VergeRxTests: XCTestCase {\n  \n  @MainActor\n  func testChangesObbservable() {\n    \n    let store = DemoStore()\n    \n    XCTContext.runActivity(named: \"\") { (activity) in\n      \n      let exp1 = expectation(description: \"\")\n      \n      _ = store.rx.stateObservable()\n        .subscribe(onNext: { changes in\n          exp1.fulfill()\n          XCTAssertEqual(changes.hasChanges(\\.count), true)\n        })\n      \n      XCTAssertEqual(exp1.expectedFulfillmentCount, 1)\n      \n      wait(for: [exp1], timeout: 1)\n      \n    }\n\n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/AccumulationTests.swift",
    "content": "import Verge\nimport XCTest\n\nfinal class AccumulationTests: XCTestCase {\n  \n  @MainActor\n  func test_tracking() {\n        \n    let store = DemoStore()\n    \n    let expForSelect = expectation(description: \"select\")\n    expForSelect.assertForOverFulfill = true\n    expForSelect.expectedFulfillmentCount = 4\n    \n    let expForDo = expectation(description: \"do\")\n    expForDo.expectedFulfillmentCount = 3\n    \n    let sub = store.accumulate(queue: .mainIsolated()) { \n      $0.ifChanged {        \n        expForSelect.fulfill()\n        return \"\\($0.count) \\($0.name)\"\n      }\n      .do { (value: String) in\n        expForDo.fulfill()\n        print(value)\n      }\n    }\n    \n    store.commit {\n      $0.items.append(1)\n    }\n    \n    store.commit {\n      $0.items.append(1)\n    }\n    \n    store.commit {\n      $0.items.append(1)\n    }\n        \n    store.commit {\n      $0.count += 1\n    }\n    \n    store.commit {\n      $0.name = \"name\"\n    }  \n    \n    store.commit {\n      $0.name = \"name\"\n    }  \n    \n    wait(for: [expForSelect, expForDo])\n    \n    let _ = sub\n    \n  }\n\n  func test_main() {\n\n    let store = DemoStore()\n\n    let expForCount = expectation(description: \"count\")\n    expForCount.expectedFulfillmentCount = 2\n\n    let expForName = expectation(description: \"name\")\n    expForName.expectedFulfillmentCount = 2\n\n    weak var weakStore: DemoStore? = store\n    \n    let sub = store.accumulate(queue: .mainIsolated()) { [weakStore] in\n\n      $0.ifChanged(\\.count).do { value in\n        expForCount.fulfill()\n        runMain()\n      }\n\n      $0.ifChanged(\\.name).do { value in\n        expForName.fulfill()\n      }\n\n      // checks for result builders\n      if let _ = weakStore {\n        $0.ifChanged(\\.name).do { value in\n          runMain()\n        }\n      }\n\n      // checks for result builders\n      if true {\n        $0.ifChanged(\\.name).do { value in\n          runMain()\n        }\n      } else {\n        $0.ifChanged(\\.name).do { value in\n          runMain()\n        }\n      }\n\n      // checks for result builders\n      if true {\n        $0.ifChanged(\\.name).do { value in\n          runMain()\n        }\n      }\n\n    }\n\n    store.commit {\n      $0.count += 1\n    }\n\n    store.commit {\n      $0.name = \"name\"\n    }\n\n    wait(for: [expForCount, expForName], timeout: 1)\n\n    let _ = sub\n  }\n\n  func test_drop() {\n\n    let store = DemoStore()\n\n    let expForCount = expectation(description: \"count\")\n    expForCount.expectedFulfillmentCount = 1\n\n    let sub = store.accumulate(queue: .mainIsolated()) { \n\n      $0.ifChanged(\\.count)\n        .dropFirst(2)\n        .do { value in\n          expForCount.fulfill()\n        }\n\n    }\n\n    store.commit {\n      $0.count += 1\n    }\n\n    store.commit {\n      $0.count += 1\n    }\n\n    wait(for: [expForCount], timeout: 1)\n\n    let _ = sub\n  }\n\n  func test_background() {\n\n    let store = DemoStore()\n\n    let expForCount = expectation(description: \"count\")\n    expForCount.expectedFulfillmentCount = 2\n\n    let expForName = expectation(description: \"name\")\n    expForName.expectedFulfillmentCount = 2\n    \n    weak var weakStore: DemoStore? = store\n\n    let sub = store.accumulate(queue: .passthrough) { [weakStore] in\n\n      $0.ifChanged(\\.count).do { value in\n        expForCount.fulfill()\n      }\n\n      $0.ifChanged(\\.name).do { value in\n        expForName.fulfill()\n      }\n\n      // checks for result builders\n      if let _ = weakStore {\n        $0.ifChanged(\\.name).do { value in\n        }\n      }\n\n      // checks for result builders\n      if true {\n        $0.ifChanged(\\.name).do { value in\n        }\n      } else {\n        $0.ifChanged(\\.name).do { value in\n        }\n      }\n\n      // checks for result builders\n      if true {\n        $0.ifChanged(\\.name).do { value in\n        }\n      }\n\n    }\n\n    store.commit {\n      $0.count += 1\n    }\n\n    store.commit {\n      $0.name = \"name\"\n    }\n\n    wait(for: [expForCount, expForName], timeout: 1)\n\n    let _ = sub\n  }\n}\n\n@MainActor\nprivate func runMain() {\n\n}\n"
  },
  {
    "path": "Tests/VergeTests/ActivityTests.swift",
    "content": "//\n//  ActivityTests.swift\n//  VergeStoreTests\n//\n//  Created by muukii on 2019/12/24.\n//  Copyright © 2019 muukii. All rights reserved.\n//\n\nimport Foundation\n\nimport XCTest\nimport Verge\n\n#if canImport(Combine)\n\nimport Combine\n\n@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)\nclass ActivityTests: XCTestCase {\n  \n  struct Value: Equatable {\n    \n  }\n  \n  enum Activity {\n    case didSendMessage\n  }\n  \n  final class Store: Verge.Store<Value, Activity>, @unchecked Sendable {\n        \n    init() {\n      super.init(initialState: .init(), logger: DefaultStoreLogger.default)\n    }\n    \n    func sendMessage() {\n      send(.didSendMessage)\n    }\n  }\n  \n  private var subscriptions = Set<AnyCancellable>()\n  \n  func testSend() {\n    \n    let store = Store()\n    \n    let waiter = XCTestExpectation()\n    waiter.expectedFulfillmentCount = 1\n\n    store\n      .activityPublisher()\n      .sink { event in\n        XCTAssertEqual(event, .didSendMessage)\n        waiter.fulfill()\n    }\n    .store(in: &subscriptions)\n    \n    store.sendMessage()\n    \n    wait(for: [waiter], timeout: 10)\n        \n  }\n}\n\n#endif\n"
  },
  {
    "path": "Tests/VergeTests/BindingDerivedTests.swift",
    "content": "import XCTest\nimport Verge\n\nfinal class BindingDerivedTests: XCTestCase {\n\n  func testBinding() {\n\n    let source = DemoStore()\n\n    let binding = source.bindingDerived(\n      get: .select(\\.count),\n      set: { source, new in\n        source.count = new\n      })\n\n    XCTAssertEqual(binding.state.previous?.primitive, nil)\n    XCTAssertEqual(binding.state.primitive, 0)\n    \n    binding.wrappedValue = 2\n\n    XCTAssertEqual(binding.state.previous?.primitive, 0)\n    XCTAssertEqual(binding.state.primitive, 2)\n    XCTAssertEqual(source.state.primitive.count, 2)\n\n  }\n\n  func testBinding_abstract() {\n\n    let source = DemoStore()\n\n    let binding: some StoreDriverType<Int> = source.bindingDerived(\n      get: .select(\\.count),\n      set: { source, new in\n        source.count = new\n      })\n\n    XCTAssertEqual(binding.state.previous?.primitive, nil)\n    XCTAssertEqual(binding.state.primitive, 0)\n\n    binding.commit {\n      $0 = 2\n    }\n\n    XCTAssertEqual(binding.state.previous?.primitive, 0)\n    XCTAssertEqual(binding.state.primitive, 2)\n\n    XCTAssertEqual(source.state.primitive.count, 2)\n\n    source.commit {\n      $0.count += 1\n    }\n\n    XCTAssertEqual(binding.state.previous?.primitive, 2)\n    XCTAssertEqual(binding.state.primitive, 3)\n\n  }\n\n  func testBinding_upstreamChanged() {\n    let source = DemoStore()\n\n    let binding = source.bindingDerived(\n      get: .select(\\.count),\n      set: { source, new in\n        source.count = new\n      })\n\n    source.commit {\n      $0.count += 1\n    }\n\n    XCTAssertEqual(source.state.count, 1)\n    XCTAssertEqual(source.state.previous?.count, 0)\n\n    XCTAssertEqual(binding.state.previous?.primitive, 0)\n    XCTAssertEqual(binding.state.primitive, 1)\n\n\n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeTests/CachedMapTests.swift",
    "content": "//\n//  CachedMapTests.swift\n//  VergeStoreTests\n//\n//  Created by muukii on 2020/07/25.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\n\nimport XCTest\nimport Verge\n\nfinal class CachedMapTests: XCTestCase {\n\n  struct Entity {\n    let id: String\n  }\n    \n  final class ViewModel: Equatable {\n\n    static func == (lhs: ViewModel, rhs: ViewModel) -> Bool {\n      lhs === rhs\n    }\n\n    init(entity: Entity) {\n    }\n  }\n    \n  func testCacheAvailability() {    \n    \n    let storage = InstancePool<Entity, ViewModel>.init(keySelector: \\.id)\n\n    let fetchedEntities: [Entity] = (0..<100).map { Entity(id: $0.description) }\n\n    let resultA = fetchedEntities.cachedMap(using: storage, sweepsUnused: true, makeNew: {\n      ViewModel(entity: $0)\n    })\n\n    let resultB = fetchedEntities.cachedMap(using: storage, sweepsUnused: true, makeNew: {\n      XCTFail()\n      return ViewModel(entity: $0)\n    })\n\n    XCTAssertEqual(resultA, resultB)\n  }\n \n}\n"
  },
  {
    "path": "Tests/VergeTests/ChangesTests.swift",
    "content": "import XCTest\nimport Verge\nimport VergeMacros\n\nfinal class ChangesTests: XCTestCase {\n\n  func test_performance_keypath() {\n\n    let changes = Changes<DemoState>.init(old: nil, new: .init())\n\n    measure {\n      for _ in 0..<1000 {\n        changes.ifChanged(\\.name).do { _ in\n\n        }\n      }\n    }\n\n  }\n\n  func test_performance_macro() {\n\n    let changes = Changes<DemoState>.init(old: nil, new: .init())\n\n    measure {\n      for _ in 0..<1000 {\n        _ = changes.ifChanged(#keyPathMap(\\.name))\n      }\n    }\n\n  }\n\n  func test_performance_closure() {\n\n    let changes = Changes<DemoState>.init(old: nil, new: .init())\n\n    measure {\n      for _ in 0..<1000 {\n        _ = changes.ifChanged({ $0.name })\n      }\n    }\n\n  }\n\n  func test_same() {\n\n    let changes = Changes<DemoState>.init(old: .init(), new: .init())\n\n    changes\n      .ifChanged(#keyPathMap(\\.name))\n      .do { arg in\n        XCTFail()\n    }\n\n    changes\n      .ifChanged(#keyPathMap(\\.name, \\.count))\n      .do { arg in\n        XCTFail()\n    }\n\n    changes\n      .ifChanged({ $0.name })\n      .do { arg in\n        XCTFail()\n      }\n\n    changes\n      .ifChanged({ ($0.name, $0.count) })\n      .do { arg in\n        XCTFail()\n      }\n\n  }\n\n  func test_diff() {\n\n    let changes = Changes<DemoState>.init(\n      old: .init(name: \"---\"),\n      new: .init()\n    )\n\n    var hit = false\n\n    changes\n      .ifChanged({ ($0.name, $0.count) })\n      .do { arg in\n        hit = true\n      }\n\n    XCTAssertTrue(hit)\n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/ComparerTests.swift",
    "content": "//\n//  ComparerTests.swift\n//  VergeTests\n//\n//  Created by Muukii on 2022/05/11.\n//  Copyright © 2022 muukii. All rights reserved.\n//\n\nimport Foundation\nimport Verge\nimport XCTest\n\n@available(iOS 13, *)\nfinal class ComparerTests: XCTestCase {\n  \n  func testPerfomance_old() {\n    \n    let base = Comparer<String> { $0 == $1 }\n    \n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric()]) {\n      for _ in 0..<10000 {\n        _ = base.equals(\"A\", \"B\")\n      }\n    }\n  }\n\n  func testPerfomance_new() {\n\n    let base = EqualityComparator<String>()\n\n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric()]) {\n      for _ in 0..<10000 {\n        _ = base(\"A\", \"B\")\n      }\n    }\n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeTests/ConcurrencyTests.swift",
    "content": "//\n//  ConcurrencyTests.swift\n//  VergeTests\n//\n//  Created by Muukii on 2021/03/16.\n//  Copyright © 2021 muukii. All rights reserved.\n//\n\nimport Combine\nimport Foundation\nimport Verge\nimport XCTest\nimport os.lock\n\n@available(iOS 13, *)\nfinal class ConcurrencyTests: XCTestCase {\n\n  func testOrderOfEvents() {\n    RuntimeSanitizer.global.isSanitizerStateReceivingByCorrectOrder = true\n    RuntimeSanitizer.global.onDidFindRuntimeError = { error in\n      print(error)\n    }\n\n    // Currently, it's collapsed because Storage emits event without locking.\n\n    let store = Verge.Store<DemoState, Never>(initialState: .init(), logger: nil)\n\n    let exp = expectation(description: \"\")\n    let counter = expectation(description: \"update count\")\n    counter.assertForOverFulfill = true\n    counter.expectedFulfillmentCount = 101\n\n    let results: VergeConcurrency.RecursiveLockAtomic<[Int]> = .init([])\n    var version: UInt64 = 0\n\n    let sub = store.sinkState(dropsFirst: false) { changes in\n      results.modify {\n        $0.append(changes.count)\n        print(\"<-\", changes.count)\n      }\n      print(\"Received version\", changes.version)\n      XCTAssert(version < changes.version || version == 0)\n      version = changes.version\n      counter.fulfill()\n    }\n\n    let dispatched = VergeConcurrency.UnfairLockAtomic<[Int]>([])\n\n    DispatchQueue.global().async {\n      DispatchQueue.concurrentPerform(iterations: 100) { i in\n\n        Task {\n          await store.backgroundCommit {\n            $0.count = i\n            dispatched.modify {\n              $0.append(i)\n            }\n          }\n        }\n      }\n\n      exp.fulfill()\n    }\n\n    wait(for: [exp, counter], timeout: 10)\n    //    print(dispatched, results)\n    let _dispatched = dispatched.value\n    XCTAssertEqual(\n      [0] + _dispatched, results.value, \"\\(([0] + _dispatched).difference(from: results.value))\")\n    withExtendedLifetime(sub) {}\n  }\n\n  func testTargetQueue() {\n    let store1 = DemoStore()\n\n    let exp = expectation(description: \"11\")\n\n    let count = VergeConcurrency.UnfairLockAtomic<Int>.init(0)\n\n    DispatchQueue.global().async {\n      let cancellable = store1.sinkState(queue: .startsFromCurrentThread(andUse: .mainIsolated())) {\n        state in\n\n        defer {\n          count.modify { $0 += 1 }\n        }\n\n        if count.modify({ $0 == 0 }) {\n          XCTAssertEqual(Thread.isMainThread, false)\n        } else {\n          XCTAssertEqual(Thread.isMainThread, true)\n          exp.fulfill()\n        }\n      }\n\n      store1.commit {\n        $0.count = 10\n      }\n\n      withExtendedLifetime(cancellable) {}\n    }\n\n    wait(for: [exp], timeout: 1)\n  }\n\n  func testEventOrder() {\n    let store = DemoStore()\n\n    var bag = Set<AnyCancellable>()\n\n    for i in 0..<100 {\n      do {\n        let version = VergeConcurrency.UnfairLockAtomic<UInt64>.init(0)\n        store.sinkState(queue: .passthrough) { s in\n          if version.modify({ $0 > s.version }) {\n            XCTFail()\n          }\n          version.modify { $0 = s.version }\n          print(\"\\(i)\", s.version)\n        }\n        .store(in: &bag)\n      }\n    }\n\n    do {\n      let version = VergeConcurrency.UnfairLockAtomic<UInt64>.init(0)\n      store.sinkState(queue: .passthrough) { s in\n        if version.modify({ $0 > s.version }) {\n          XCTFail()\n        }\n        version.modify { $0 = s.version }\n        print(\"x\", s.version)\n        store.commit {\n          if s.count == 1 {\n            $0.count += 1\n          }\n        }\n      }\n      .store(in: &bag)\n    }\n\n    store.commit { s in\n      s.count += 1\n    }\n\n    withExtendedLifetime(bag) {}\n  }\n\n  func testRecursiveCommit() {\n    let store1 = DemoStore()\n\n    let exp = expectation(description: \"11\")\n\n    let cancellable = store1.sinkState { [weak store1] state in\n\n      state.ifChanged(\\.count).do { value in\n        if value == 10 {\n          store1?.commit {\n            $0.count = 11\n          }\n        }\n        if value == 11 {\n          exp.fulfill()\n        }\n      }\n    }\n\n    store1.commit {\n      $0.count = 10\n    }\n\n    wait(for: [exp], timeout: 10)\n    withExtendedLifetime(cancellable) {}\n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/CopyPerformance.swift",
    "content": "//\n//  CopyPerformance.swift\n//  VergeCore\n//\n//  Created by muukii on 2020/01/08.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\n\nimport XCTest\n\nfinal class CopyPerformance: XCTestCase {\n  \n  private let source = Huge()\n  \n  func testCopy() {\n    \n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric(), XCTClockMetric()]) {\n      run(with: source)\n    }\n  }\n  \n  func testCopyWithShared() {\n    \n    let huge = Shared(source)\n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric(), XCTClockMetric()]) {\n      run(with: huge)\n    }\n  }\n  \n  func testAny() {\n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric(), XCTClockMetric()]) {\n      run(any: source)\n    }\n  }\n  \n  func testAnyWithShared() {\n    let huge = Shared(source)\n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric(), XCTClockMetric()]) {\n      run(anyObject: huge)\n    }\n  }\n  \n  private func run(anyObject: AnyObject) {\n    let value = anyObject as! Shared<Huge>\n    _ = value.value.value_0\n  }\n  \n  private func run(any: Any) {\n  }\n  \n  private func run(with huge: Huge) {\n    let _ = huge.value_0\n  }\n  \n  private func run(with huge: Shared<Huge>) {\n    let _ = huge.value.value_0\n  }\n  \n  final class Shared<V> {\n    let value: V\n    init(_ value: V) {\n      self.value = value\n    }\n  }\n  \n  struct Huge {\n    var value_0: Int = 1\n    var value_1: Int = 1\n    var value_2: Int = 1\n    var value_3: Int = 1\n    var value_4: Int = 1\n    var value_5: Int = 1\n    var value_6: Int = 1\n    var value_7: Int = 1\n    var value_8: Int = 1\n    var value_9: Int = 1\n    var value_10: Int = 1\n    var value_11: Int = 1\n    var value_12: Int = 1\n    var value_13: Int = 1\n    var value_14: Int = 1\n    var value_15: Int = 1\n    var value_16: Int = 1\n    var value_17: Int = 1\n    var value_18: Int = 1\n    var value_19: Int = 1\n    var value_20: Int = 1\n    var value_21: Int = 1\n    var value_22: Int = 1\n    var value_23: Int = 1\n    var value_24: Int = 1\n    var value_25: Int = 1\n    var value_26: Int = 1\n    var value_27: Int = 1\n    var value_28: Int = 1\n    var value_29: Int = 1\n    var value_30: Int = 1\n    var value_31: Int = 1\n    var value_32: Int = 1\n    var value_33: Int = 1\n    var value_34: Int = 1\n    var value_35: Int = 1\n    var value_36: Int = 1\n    var value_37: Int = 1\n    var value_38: Int = 1\n    var value_39: Int = 1\n    var value_40: Int = 1\n    var value_41: Int = 1\n    var value_42: Int = 1\n    var value_43: Int = 1\n    var value_44: Int = 1\n    var value_45: Int = 1\n    var value_46: Int = 1\n    var value_47: Int = 1\n    var value_48: Int = 1\n    var value_49: Int = 1\n    var value_50: Int = 1\n    var value_51: Int = 1\n    var value_52: Int = 1\n    var value_53: Int = 1\n    var value_54: Int = 1\n    var value_55: Int = 1\n    var value_56: Int = 1\n    var value_57: Int = 1\n    var value_58: Int = 1\n    var value_59: Int = 1\n    var value_60: Int = 1\n    var value_61: Int = 1\n    var value_62: Int = 1\n    var value_63: Int = 1\n    var value_64: Int = 1\n    var value_65: Int = 1\n    var value_66: Int = 1\n    var value_67: Int = 1\n    var value_68: Int = 1\n    var value_69: Int = 1\n    var value_70: Int = 1\n    var value_71: Int = 1\n    var value_72: Int = 1\n    var value_73: Int = 1\n    var value_74: Int = 1\n    var value_75: Int = 1\n    var value_76: Int = 1\n    var value_77: Int = 1\n    var value_78: Int = 1\n    var value_79: Int = 1\n    var value_80: Int = 1\n    var value_81: Int = 1\n    var value_82: Int = 1\n    var value_83: Int = 1\n    var value_84: Int = 1\n    var value_85: Int = 1\n    var value_86: Int = 1\n    var value_87: Int = 1\n    var value_88: Int = 1\n    var value_89: Int = 1\n    var value_90: Int = 1\n    var value_91: Int = 1\n    var value_92: Int = 1\n    var value_93: Int = 1\n    var value_94: Int = 1\n    var value_95: Int = 1\n    var value_96: Int = 1\n    var value_97: Int = 1\n    var value_98: Int = 1\n    var value_99: Int = 1\n    var value_100: Int = 1\n    var value_101: Int = 1\n    var value_102: Int = 1\n    var value_103: Int = 1\n    var value_104: Int = 1\n    var value_105: Int = 1\n    var value_106: Int = 1\n    var value_107: Int = 1\n    var value_108: Int = 1\n    var value_109: Int = 1\n    var value_110: Int = 1\n    var value_111: Int = 1\n    var value_112: Int = 1\n    var value_113: Int = 1\n    var value_114: Int = 1\n    var value_115: Int = 1\n    var value_116: Int = 1\n    var value_117: Int = 1\n    var value_118: Int = 1\n    var value_119: Int = 1\n    var value_120: Int = 1\n    var value_121: Int = 1\n    var value_122: Int = 1\n    var value_123: Int = 1\n    var value_124: Int = 1\n    var value_125: Int = 1\n    var value_126: Int = 1\n    var value_127: Int = 1\n    var value_128: Int = 1\n    var value_129: Int = 1\n    var value_130: Int = 1\n    var value_131: Int = 1\n    var value_132: Int = 1\n    var value_133: Int = 1\n    var value_134: Int = 1\n    var value_135: Int = 1\n    var value_136: Int = 1\n    var value_137: Int = 1\n    var value_138: Int = 1\n    var value_139: Int = 1\n    var value_140: Int = 1\n    var value_141: Int = 1\n    var value_142: Int = 1\n    var value_143: Int = 1\n    var value_144: Int = 1\n    var value_145: Int = 1\n    var value_146: Int = 1\n    var value_147: Int = 1\n    var value_148: Int = 1\n    var value_149: Int = 1\n    var value_150: Int = 1\n    var value_151: Int = 1\n    var value_152: Int = 1\n    var value_153: Int = 1\n    var value_154: Int = 1\n    var value_155: Int = 1\n    var value_156: Int = 1\n    var value_157: Int = 1\n    var value_158: Int = 1\n    var value_159: Int = 1\n    var value_160: Int = 1\n    var value_161: Int = 1\n    var value_162: Int = 1\n    var value_163: Int = 1\n    var value_164: Int = 1\n    var value_165: Int = 1\n    var value_166: Int = 1\n    var value_167: Int = 1\n    var value_168: Int = 1\n    var value_169: Int = 1\n    var value_170: Int = 1\n    var value_171: Int = 1\n    var value_172: Int = 1\n    var value_173: Int = 1\n    var value_174: Int = 1\n    var value_175: Int = 1\n    var value_176: Int = 1\n    var value_177: Int = 1\n    var value_178: Int = 1\n    var value_179: Int = 1\n    var value_180: Int = 1\n    var value_181: Int = 1\n    var value_182: Int = 1\n    var value_183: Int = 1\n    var value_184: Int = 1\n    var value_185: Int = 1\n    var value_186: Int = 1\n    var value_187: Int = 1\n    var value_188: Int = 1\n    var value_189: Int = 1\n    var value_190: Int = 1\n    var value_191: Int = 1\n    var value_192: Int = 1\n    var value_193: Int = 1\n    var value_194: Int = 1\n    var value_195: Int = 1\n    var value_196: Int = 1\n    var value_197: Int = 1\n    var value_198: Int = 1\n    var value_199: Int = 1\n    var value_200: Int = 1\n    var value_201: Int = 1\n    var value_202: Int = 1\n    var value_203: Int = 1\n    var value_204: Int = 1\n    var value_205: Int = 1\n    var value_206: Int = 1\n    var value_207: Int = 1\n    var value_208: Int = 1\n    var value_209: Int = 1\n    var value_210: Int = 1\n    var value_211: Int = 1\n    var value_212: Int = 1\n    var value_213: Int = 1\n    var value_214: Int = 1\n    var value_215: Int = 1\n    var value_216: Int = 1\n    var value_217: Int = 1\n    var value_218: Int = 1\n    var value_219: Int = 1\n    var value_220: Int = 1\n    var value_221: Int = 1\n    var value_222: Int = 1\n    var value_223: Int = 1\n    var value_224: Int = 1\n    var value_225: Int = 1\n    var value_226: Int = 1\n    var value_227: Int = 1\n    var value_228: Int = 1\n    var value_229: Int = 1\n    var value_230: Int = 1\n    var value_231: Int = 1\n    var value_232: Int = 1\n    var value_233: Int = 1\n    var value_234: Int = 1\n    var value_235: Int = 1\n    var value_236: Int = 1\n    var value_237: Int = 1\n    var value_238: Int = 1\n    var value_239: Int = 1\n    var value_240: Int = 1\n    var value_241: Int = 1\n    var value_242: Int = 1\n    var value_243: Int = 1\n    var value_244: Int = 1\n    var value_245: Int = 1\n    var value_246: Int = 1\n    var value_247: Int = 1\n    var value_248: Int = 1\n    var value_249: Int = 1\n    var value_250: Int = 1\n    var value_251: Int = 1\n    var value_252: Int = 1\n    var value_253: Int = 1\n    var value_254: Int = 1\n    var value_255: Int = 1\n    var value_256: Int = 1\n    var value_257: Int = 1\n    var value_258: Int = 1\n    var value_259: Int = 1\n    var value_260: Int = 1\n    var value_261: Int = 1\n    var value_262: Int = 1\n    var value_263: Int = 1\n    var value_264: Int = 1\n    var value_265: Int = 1\n    var value_266: Int = 1\n    var value_267: Int = 1\n    var value_268: Int = 1\n    var value_269: Int = 1\n    var value_270: Int = 1\n    var value_271: Int = 1\n    var value_272: Int = 1\n    var value_273: Int = 1\n    var value_274: Int = 1\n    var value_275: Int = 1\n    var value_276: Int = 1\n    var value_277: Int = 1\n    var value_278: Int = 1\n    var value_279: Int = 1\n    var value_280: Int = 1\n    var value_281: Int = 1\n    var value_282: Int = 1\n    var value_283: Int = 1\n    var value_284: Int = 1\n    var value_285: Int = 1\n    var value_286: Int = 1\n    var value_287: Int = 1\n    var value_288: Int = 1\n    var value_289: Int = 1\n    var value_290: Int = 1\n    var value_291: Int = 1\n    var value_292: Int = 1\n    var value_293: Int = 1\n    var value_294: Int = 1\n    var value_295: Int = 1\n    var value_296: Int = 1\n    var value_297: Int = 1\n    var value_298: Int = 1\n    var value_299: Int = 1\n    var value_300: Int = 1\n    var value_301: Int = 1\n    var value_302: Int = 1\n    var value_303: Int = 1\n    var value_304: Int = 1\n    var value_305: Int = 1\n    var value_306: Int = 1\n    var value_307: Int = 1\n    var value_308: Int = 1\n    var value_309: Int = 1\n    var value_310: Int = 1\n    var value_311: Int = 1\n    var value_312: Int = 1\n    var value_313: Int = 1\n    var value_314: Int = 1\n    var value_315: Int = 1\n    var value_316: Int = 1\n    var value_317: Int = 1\n    var value_318: Int = 1\n    var value_319: Int = 1\n    var value_320: Int = 1\n    var value_321: Int = 1\n    var value_322: Int = 1\n    var value_323: Int = 1\n    var value_324: Int = 1\n    var value_325: Int = 1\n    var value_326: Int = 1\n    var value_327: Int = 1\n    var value_328: Int = 1\n    var value_329: Int = 1\n    var value_330: Int = 1\n    var value_331: Int = 1\n    var value_332: Int = 1\n    var value_333: Int = 1\n    var value_334: Int = 1\n    var value_335: Int = 1\n    var value_336: Int = 1\n    var value_337: Int = 1\n    var value_338: Int = 1\n    var value_339: Int = 1\n    var value_340: Int = 1\n    var value_341: Int = 1\n    var value_342: Int = 1\n    var value_343: Int = 1\n    var value_344: Int = 1\n    var value_345: Int = 1\n    var value_346: Int = 1\n    var value_347: Int = 1\n    var value_348: Int = 1\n    var value_349: Int = 1\n    var value_350: Int = 1\n    var value_351: Int = 1\n    var value_352: Int = 1\n    var value_353: Int = 1\n    var value_354: Int = 1\n    var value_355: Int = 1\n    var value_356: Int = 1\n    var value_357: Int = 1\n    var value_358: Int = 1\n    var value_359: Int = 1\n    var value_360: Int = 1\n    var value_361: Int = 1\n    var value_362: Int = 1\n    var value_363: Int = 1\n    var value_364: Int = 1\n    var value_365: Int = 1\n    var value_366: Int = 1\n    var value_367: Int = 1\n    var value_368: Int = 1\n    var value_369: Int = 1\n    var value_370: Int = 1\n    var value_371: Int = 1\n    var value_372: Int = 1\n    var value_373: Int = 1\n    var value_374: Int = 1\n    var value_375: Int = 1\n    var value_376: Int = 1\n    var value_377: Int = 1\n    var value_378: Int = 1\n    var value_379: Int = 1\n    var value_380: Int = 1\n    var value_381: Int = 1\n    var value_382: Int = 1\n    var value_383: Int = 1\n    var value_384: Int = 1\n    var value_385: Int = 1\n    var value_386: Int = 1\n    var value_387: Int = 1\n    var value_388: Int = 1\n    var value_389: Int = 1\n    var value_390: Int = 1\n    var value_391: Int = 1\n    var value_392: Int = 1\n    var value_393: Int = 1\n    var value_394: Int = 1\n    var value_395: Int = 1\n    var value_396: Int = 1\n    var value_397: Int = 1\n    var value_398: Int = 1\n    var value_399: Int = 1\n    var value_400: Int = 1\n    var value_401: Int = 1\n    var value_402: Int = 1\n    var value_403: Int = 1\n    var value_404: Int = 1\n    var value_405: Int = 1\n    var value_406: Int = 1\n    var value_407: Int = 1\n    var value_408: Int = 1\n    var value_409: Int = 1\n    var value_410: Int = 1\n    var value_411: Int = 1\n    var value_412: Int = 1\n    var value_413: Int = 1\n    var value_414: Int = 1\n    var value_415: Int = 1\n    var value_416: Int = 1\n    var value_417: Int = 1\n    var value_418: Int = 1\n    var value_419: Int = 1\n    var value_420: Int = 1\n    var value_421: Int = 1\n    var value_422: Int = 1\n    var value_423: Int = 1\n    var value_424: Int = 1\n    var value_425: Int = 1\n    var value_426: Int = 1\n    var value_427: Int = 1\n    var value_428: Int = 1\n    var value_429: Int = 1\n    var value_430: Int = 1\n    var value_431: Int = 1\n    var value_432: Int = 1\n    var value_433: Int = 1\n    var value_434: Int = 1\n    var value_435: Int = 1\n    var value_436: Int = 1\n    var value_437: Int = 1\n    var value_438: Int = 1\n    var value_439: Int = 1\n    var value_440: Int = 1\n    var value_441: Int = 1\n    var value_442: Int = 1\n    var value_443: Int = 1\n    var value_444: Int = 1\n    var value_445: Int = 1\n    var value_446: Int = 1\n    var value_447: Int = 1\n    var value_448: Int = 1\n    var value_449: Int = 1\n    var value_450: Int = 1\n    var value_451: Int = 1\n    var value_452: Int = 1\n    var value_453: Int = 1\n    var value_454: Int = 1\n    var value_455: Int = 1\n    var value_456: Int = 1\n    var value_457: Int = 1\n    var value_458: Int = 1\n    var value_459: Int = 1\n    var value_460: Int = 1\n    var value_461: Int = 1\n    var value_462: Int = 1\n    var value_463: Int = 1\n    var value_464: Int = 1\n    var value_465: Int = 1\n    var value_466: Int = 1\n    var value_467: Int = 1\n    var value_468: Int = 1\n    var value_469: Int = 1\n    var value_470: Int = 1\n    var value_471: Int = 1\n    var value_472: Int = 1\n    var value_473: Int = 1\n    var value_474: Int = 1\n    var value_475: Int = 1\n    var value_476: Int = 1\n    var value_477: Int = 1\n    var value_478: Int = 1\n    var value_479: Int = 1\n    var value_480: Int = 1\n    var value_481: Int = 1\n    var value_482: Int = 1\n    var value_483: Int = 1\n    var value_484: Int = 1\n    var value_485: Int = 1\n    var value_486: Int = 1\n    var value_487: Int = 1\n    var value_488: Int = 1\n    var value_489: Int = 1\n    var value_490: Int = 1\n    var value_491: Int = 1\n    var value_492: Int = 1\n    var value_493: Int = 1\n    var value_494: Int = 1\n    var value_495: Int = 1\n    var value_496: Int = 1\n    var value_497: Int = 1\n    var value_498: Int = 1\n    var value_499: Int = 1\n    var value_500: Int = 1\n    var value_501: Int = 1\n    var value_502: Int = 1\n    var value_503: Int = 1\n    var value_504: Int = 1\n    var value_505: Int = 1\n    var value_506: Int = 1\n    var value_507: Int = 1\n    var value_508: Int = 1\n    var value_509: Int = 1\n    var value_510: Int = 1\n    var value_511: Int = 1\n    var value_512: Int = 1\n    var value_513: Int = 1\n    var value_514: Int = 1\n    var value_515: Int = 1\n    var value_516: Int = 1\n    var value_517: Int = 1\n    var value_518: Int = 1\n    var value_519: Int = 1\n    var value_520: Int = 1\n    var value_521: Int = 1\n    var value_522: Int = 1\n    var value_523: Int = 1\n    var value_524: Int = 1\n    var value_525: Int = 1\n    var value_526: Int = 1\n    var value_527: Int = 1\n    var value_528: Int = 1\n    var value_529: Int = 1\n    var value_530: Int = 1\n    var value_531: Int = 1\n    var value_532: Int = 1\n    var value_533: Int = 1\n    var value_534: Int = 1\n    var value_535: Int = 1\n    var value_536: Int = 1\n    var value_537: Int = 1\n    var value_538: Int = 1\n    var value_539: Int = 1\n    var value_540: Int = 1\n    var value_541: Int = 1\n    var value_542: Int = 1\n    var value_543: Int = 1\n    var value_544: Int = 1\n    var value_545: Int = 1\n    var value_546: Int = 1\n    var value_547: Int = 1\n    var value_548: Int = 1\n    var value_549: Int = 1\n    var value_550: Int = 1\n    var value_551: Int = 1\n    var value_552: Int = 1\n    var value_553: Int = 1\n    var value_554: Int = 1\n    var value_555: Int = 1\n    var value_556: Int = 1\n    var value_557: Int = 1\n    var value_558: Int = 1\n    var value_559: Int = 1\n    var value_560: Int = 1\n    var value_561: Int = 1\n    var value_562: Int = 1\n    var value_563: Int = 1\n    var value_564: Int = 1\n    var value_565: Int = 1\n    var value_566: Int = 1\n    var value_567: Int = 1\n    var value_568: Int = 1\n    var value_569: Int = 1\n    var value_570: Int = 1\n    var value_571: Int = 1\n    var value_572: Int = 1\n    var value_573: Int = 1\n    var value_574: Int = 1\n    var value_575: Int = 1\n    var value_576: Int = 1\n    var value_577: Int = 1\n    var value_578: Int = 1\n    var value_579: Int = 1\n    var value_580: Int = 1\n    var value_581: Int = 1\n    var value_582: Int = 1\n    var value_583: Int = 1\n    var value_584: Int = 1\n    var value_585: Int = 1\n    var value_586: Int = 1\n    var value_587: Int = 1\n    var value_588: Int = 1\n    var value_589: Int = 1\n    var value_590: Int = 1\n    var value_591: Int = 1\n    var value_592: Int = 1\n    var value_593: Int = 1\n    var value_594: Int = 1\n    var value_595: Int = 1\n    var value_596: Int = 1\n    var value_597: Int = 1\n    var value_598: Int = 1\n    var value_599: Int = 1\n    var value_600: Int = 1\n    var value_601: Int = 1\n    var value_602: Int = 1\n    var value_603: Int = 1\n    var value_604: Int = 1\n    var value_605: Int = 1\n    var value_606: Int = 1\n    var value_607: Int = 1\n    var value_608: Int = 1\n    var value_609: Int = 1\n    var value_610: Int = 1\n    var value_611: Int = 1\n    var value_612: Int = 1\n    var value_613: Int = 1\n    var value_614: Int = 1\n    var value_615: Int = 1\n    var value_616: Int = 1\n    var value_617: Int = 1\n    var value_618: Int = 1\n    var value_619: Int = 1\n    var value_620: Int = 1\n    var value_621: Int = 1\n    var value_622: Int = 1\n    var value_623: Int = 1\n    var value_624: Int = 1\n    var value_625: Int = 1\n    var value_626: Int = 1\n    var value_627: Int = 1\n    var value_628: Int = 1\n    var value_629: Int = 1\n    var value_630: Int = 1\n    var value_631: Int = 1\n    var value_632: Int = 1\n    var value_633: Int = 1\n    var value_634: Int = 1\n    var value_635: Int = 1\n    var value_636: Int = 1\n    var value_637: Int = 1\n    var value_638: Int = 1\n    var value_639: Int = 1\n    var value_640: Int = 1\n    var value_641: Int = 1\n    var value_642: Int = 1\n    var value_643: Int = 1\n    var value_644: Int = 1\n    var value_645: Int = 1\n    var value_646: Int = 1\n    var value_647: Int = 1\n    var value_648: Int = 1\n    var value_649: Int = 1\n    var value_650: Int = 1\n    var value_651: Int = 1\n    var value_652: Int = 1\n    var value_653: Int = 1\n    var value_654: Int = 1\n    var value_655: Int = 1\n    var value_656: Int = 1\n    var value_657: Int = 1\n    var value_658: Int = 1\n    var value_659: Int = 1\n    var value_660: Int = 1\n    var value_661: Int = 1\n    var value_662: Int = 1\n    var value_663: Int = 1\n    var value_664: Int = 1\n    var value_665: Int = 1\n    var value_666: Int = 1\n    var value_667: Int = 1\n    var value_668: Int = 1\n    var value_669: Int = 1\n    var value_670: Int = 1\n    var value_671: Int = 1\n    var value_672: Int = 1\n    var value_673: Int = 1\n    var value_674: Int = 1\n    var value_675: Int = 1\n    var value_676: Int = 1\n    var value_677: Int = 1\n    var value_678: Int = 1\n    var value_679: Int = 1\n    var value_680: Int = 1\n    var value_681: Int = 1\n    var value_682: Int = 1\n    var value_683: Int = 1\n    var value_684: Int = 1\n    var value_685: Int = 1\n    var value_686: Int = 1\n    var value_687: Int = 1\n    var value_688: Int = 1\n    var value_689: Int = 1\n    var value_690: Int = 1\n    var value_691: Int = 1\n    var value_692: Int = 1\n    var value_693: Int = 1\n    var value_694: Int = 1\n    var value_695: Int = 1\n    var value_696: Int = 1\n    var value_697: Int = 1\n    var value_698: Int = 1\n    var value_699: Int = 1\n    var value_700: Int = 1\n    var value_701: Int = 1\n    var value_702: Int = 1\n    var value_703: Int = 1\n    var value_704: Int = 1\n    var value_705: Int = 1\n    var value_706: Int = 1\n    var value_707: Int = 1\n    var value_708: Int = 1\n    var value_709: Int = 1\n    var value_710: Int = 1\n    var value_711: Int = 1\n    var value_712: Int = 1\n    var value_713: Int = 1\n    var value_714: Int = 1\n    var value_715: Int = 1\n    var value_716: Int = 1\n    var value_717: Int = 1\n    var value_718: Int = 1\n    var value_719: Int = 1\n    var value_720: Int = 1\n    var value_721: Int = 1\n    var value_722: Int = 1\n    var value_723: Int = 1\n    var value_724: Int = 1\n    var value_725: Int = 1\n    var value_726: Int = 1\n    var value_727: Int = 1\n    var value_728: Int = 1\n    var value_729: Int = 1\n    var value_730: Int = 1\n    var value_731: Int = 1\n    var value_732: Int = 1\n    var value_733: Int = 1\n    var value_734: Int = 1\n    var value_735: Int = 1\n    var value_736: Int = 1\n    var value_737: Int = 1\n    var value_738: Int = 1\n    var value_739: Int = 1\n    var value_740: Int = 1\n    var value_741: Int = 1\n    var value_742: Int = 1\n    var value_743: Int = 1\n    var value_744: Int = 1\n    var value_745: Int = 1\n    var value_746: Int = 1\n    var value_747: Int = 1\n    var value_748: Int = 1\n    var value_749: Int = 1\n    var value_750: Int = 1\n    var value_751: Int = 1\n    var value_752: Int = 1\n    var value_753: Int = 1\n    var value_754: Int = 1\n    var value_755: Int = 1\n    var value_756: Int = 1\n    var value_757: Int = 1\n    var value_758: Int = 1\n    var value_759: Int = 1\n    var value_760: Int = 1\n    var value_761: Int = 1\n    var value_762: Int = 1\n    var value_763: Int = 1\n    var value_764: Int = 1\n    var value_765: Int = 1\n    var value_766: Int = 1\n    var value_767: Int = 1\n    var value_768: Int = 1\n    var value_769: Int = 1\n    var value_770: Int = 1\n    var value_771: Int = 1\n    var value_772: Int = 1\n    var value_773: Int = 1\n    var value_774: Int = 1\n    var value_775: Int = 1\n    var value_776: Int = 1\n    var value_777: Int = 1\n    var value_778: Int = 1\n    var value_779: Int = 1\n    var value_780: Int = 1\n    var value_781: Int = 1\n    var value_782: Int = 1\n    var value_783: Int = 1\n    var value_784: Int = 1\n    var value_785: Int = 1\n    var value_786: Int = 1\n    var value_787: Int = 1\n    var value_788: Int = 1\n    var value_789: Int = 1\n    var value_790: Int = 1\n    var value_791: Int = 1\n    var value_792: Int = 1\n    var value_793: Int = 1\n    var value_794: Int = 1\n    var value_795: Int = 1\n    var value_796: Int = 1\n    var value_797: Int = 1\n    var value_798: Int = 1\n    var value_799: Int = 1\n    var value_800: Int = 1\n    var value_801: Int = 1\n    var value_802: Int = 1\n    var value_803: Int = 1\n    var value_804: Int = 1\n    var value_805: Int = 1\n    var value_806: Int = 1\n    var value_807: Int = 1\n    var value_808: Int = 1\n    var value_809: Int = 1\n    var value_810: Int = 1\n    var value_811: Int = 1\n    var value_812: Int = 1\n    var value_813: Int = 1\n    var value_814: Int = 1\n    var value_815: Int = 1\n    var value_816: Int = 1\n    var value_817: Int = 1\n    var value_818: Int = 1\n    var value_819: Int = 1\n    var value_820: Int = 1\n    var value_821: Int = 1\n    var value_822: Int = 1\n    var value_823: Int = 1\n    var value_824: Int = 1\n    var value_825: Int = 1\n    var value_826: Int = 1\n    var value_827: Int = 1\n    var value_828: Int = 1\n    var value_829: Int = 1\n    var value_830: Int = 1\n    var value_831: Int = 1\n    var value_832: Int = 1\n    var value_833: Int = 1\n    var value_834: Int = 1\n    var value_835: Int = 1\n    var value_836: Int = 1\n    var value_837: Int = 1\n    var value_838: Int = 1\n    var value_839: Int = 1\n    var value_840: Int = 1\n    var value_841: Int = 1\n    var value_842: Int = 1\n    var value_843: Int = 1\n    var value_844: Int = 1\n    var value_845: Int = 1\n    var value_846: Int = 1\n    var value_847: Int = 1\n    var value_848: Int = 1\n    var value_849: Int = 1\n    var value_850: Int = 1\n    var value_851: Int = 1\n    var value_852: Int = 1\n    var value_853: Int = 1\n    var value_854: Int = 1\n    var value_855: Int = 1\n    var value_856: Int = 1\n    var value_857: Int = 1\n    var value_858: Int = 1\n    var value_859: Int = 1\n    var value_860: Int = 1\n    var value_861: Int = 1\n    var value_862: Int = 1\n    var value_863: Int = 1\n    var value_864: Int = 1\n    var value_865: Int = 1\n    var value_866: Int = 1\n    var value_867: Int = 1\n    var value_868: Int = 1\n    var value_869: Int = 1\n    var value_870: Int = 1\n    var value_871: Int = 1\n    var value_872: Int = 1\n    var value_873: Int = 1\n    var value_874: Int = 1\n    var value_875: Int = 1\n    var value_876: Int = 1\n    var value_877: Int = 1\n    var value_878: Int = 1\n    var value_879: Int = 1\n    var value_880: Int = 1\n    var value_881: Int = 1\n    var value_882: Int = 1\n    var value_883: Int = 1\n    var value_884: Int = 1\n    var value_885: Int = 1\n    var value_886: Int = 1\n    var value_887: Int = 1\n    var value_888: Int = 1\n    var value_889: Int = 1\n    var value_890: Int = 1\n    var value_891: Int = 1\n    var value_892: Int = 1\n    var value_893: Int = 1\n    var value_894: Int = 1\n    var value_895: Int = 1\n    var value_896: Int = 1\n    var value_897: Int = 1\n    var value_898: Int = 1\n    var value_899: Int = 1\n    var value_900: Int = 1\n    var value_901: Int = 1\n    var value_902: Int = 1\n    var value_903: Int = 1\n    var value_904: Int = 1\n    var value_905: Int = 1\n    var value_906: Int = 1\n    var value_907: Int = 1\n    var value_908: Int = 1\n    var value_909: Int = 1\n    var value_910: Int = 1\n    var value_911: Int = 1\n    var value_912: Int = 1\n    var value_913: Int = 1\n    var value_914: Int = 1\n    var value_915: Int = 1\n    var value_916: Int = 1\n    var value_917: Int = 1\n    var value_918: Int = 1\n    var value_919: Int = 1\n    var value_920: Int = 1\n    var value_921: Int = 1\n    var value_922: Int = 1\n    var value_923: Int = 1\n    var value_924: Int = 1\n    var value_925: Int = 1\n    var value_926: Int = 1\n    var value_927: Int = 1\n    var value_928: Int = 1\n    var value_929: Int = 1\n    var value_930: Int = 1\n    var value_931: Int = 1\n    var value_932: Int = 1\n    var value_933: Int = 1\n    var value_934: Int = 1\n    var value_935: Int = 1\n    var value_936: Int = 1\n    var value_937: Int = 1\n    var value_938: Int = 1\n    var value_939: Int = 1\n    var value_940: Int = 1\n    var value_941: Int = 1\n    var value_942: Int = 1\n    var value_943: Int = 1\n    var value_944: Int = 1\n    var value_945: Int = 1\n    var value_946: Int = 1\n    var value_947: Int = 1\n    var value_948: Int = 1\n    var value_949: Int = 1\n    var value_950: Int = 1\n    var value_951: Int = 1\n    var value_952: Int = 1\n    var value_953: Int = 1\n    var value_954: Int = 1\n    var value_955: Int = 1\n    var value_956: Int = 1\n    var value_957: Int = 1\n    var value_958: Int = 1\n    var value_959: Int = 1\n    var value_960: Int = 1\n    var value_961: Int = 1\n    var value_962: Int = 1\n    var value_963: Int = 1\n    var value_964: Int = 1\n    var value_965: Int = 1\n    var value_966: Int = 1\n    var value_967: Int = 1\n    var value_968: Int = 1\n    var value_969: Int = 1\n    var value_970: Int = 1\n    var value_971: Int = 1\n    var value_972: Int = 1\n    var value_973: Int = 1\n    var value_974: Int = 1\n    var value_975: Int = 1\n    var value_976: Int = 1\n    var value_977: Int = 1\n    var value_978: Int = 1\n    var value_979: Int = 1\n    var value_980: Int = 1\n    var value_981: Int = 1\n    var value_982: Int = 1\n    var value_983: Int = 1\n    var value_984: Int = 1\n    var value_985: Int = 1\n    var value_986: Int = 1\n    var value_987: Int = 1\n    var value_988: Int = 1\n    var value_989: Int = 1\n    var value_990: Int = 1\n    var value_991: Int = 1\n    var value_992: Int = 1\n    var value_993: Int = 1\n    var value_994: Int = 1\n    var value_995: Int = 1\n    var value_996: Int = 1\n    var value_997: Int = 1\n    var value_998: Int = 1\n    var value_999: Int = 1\n  }\n       \n}\n"
  },
  {
    "path": "Tests/VergeTests/CounterTests.swift",
    "content": "//\n//  DateTests.swift\n//  VergeCore\n//\n//  Created by muukii on 2020/01/13.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\n\nimport XCTest\n\nimport Verge\n\nfinal class CounterTests: XCTestCase {\n    \n  func testCounter() {\n    \n    var counter = NonAtomicCounter()\n    \n    for _ in 0..<100 {\n      \n      counter.increment()\n    }\n    \n    XCTAssertEqual(counter.value, 100)\n  }\n  \n  func testCounterPerformance() {\n    var counter = NonAtomicCounter()\n    if #available(iOS 13.0, *) {\n      measure(metrics: [XCTCPUMetric()]) {\n        counter.increment()\n      }\n    } else {\n      // Fallback on earlier versions\n    }\n  }\n  \n  func testGenDatePerformance() {\n    \n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric(), XCTClockMetric()]) {\n      _ = Date()\n    }\n  }\n  \n  func testGenCFDatePerformance() {\n    \n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric(), XCTClockMetric()]) {\n      _ = CFAbsoluteTimeGetCurrent()\n    }\n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/DemoState.swift",
    "content": "\n\n//\n//  DemoState.swift\n//  VergeStoreTests\n//\n//  Created by muukii on 2020/04/21.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\nimport Verge\nimport XCTest\nimport Observation\n\nstruct NonEquatable: Sendable {\n  let id = UUID()\n}\nstruct OnEquatable: Equatable, Sendable {\n  let id = UUID()\n}\n\n@Tracking\nstruct DemoState: Sendable {\n\n  struct Inner: Equatable {\n    var name: String = \"\"\n  }\n\n  var name: String = \"\"\n  var count: Int = 0\n  var items: [Int] = []\n  var inner: Inner = .init()\n  \n  init() {\n    \n  }\n  \n  init(name: String) {\n    self.name = name\n  }\n  \n  init(name: String, count: Int) {\n    self.name = name\n    self.count = count\n  }\n\n  var nonEquatable: NonEquatable = .init()\n\n  var onEquatable: OnEquatable = .init()\n  \n  var recursive: DemoState? = nil\n\n  mutating func updateFromItself() {\n    count += 1\n  }\n\n}\n\nenum DemoActivity {\n  case something\n}\n\n#if canImport(Verge)\n\nimport Verge\n\nfinal class DemoStore: Verge.Store<DemoState, DemoActivity> {\n\n  init() {\n    super.init(initialState: .init(), logger: nil)\n  }\n\n  func increment() {\n    commit {\n      $0.count += 1\n    }\n  }\n\n  func empty() {\n    commit { _ in\n    }\n  }\n\n}\n\n#endif\n"
  },
  {
    "path": "Tests/VergeTests/DerivedTests.swift",
    "content": "//\n//  StoreSliceTests.swift\n//  VergeStore\n//\n//  Created by muukii on 2020/04/21.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nimport Verge\n\nprivate protocol MyProtocol {\n  \n}\n\nprivate protocol MyEquatableProtocol: Equatable {\n  \n}\n\nfinal class DerivedTests: XCTestCase {\n\n  func testSlice() {\n\n    let localStore = DemoStore()\n                    \n    let slice = localStore.derived(.map({ @Sendable in $0.count }), queue: .passthrough)      \n\n    XCTAssertEqual(slice.state.primitive, 0)\n    XCTAssertEqual(slice.state.root, 0)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n    \n    localStore.increment()\n\n    XCTAssertEqual(slice.state.primitive, 1)\n    XCTAssertEqual(slice.state.root, 1)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n      \n    localStore.empty()\n\n    XCTAssertEqual(slice.state.primitive, 1)\n    XCTAssertEqual(slice.state.version, 1)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n\n    localStore.empty()\n\n    XCTAssertEqual(slice.state.primitive, 1)\n    XCTAssertEqual(slice.state.version, 1)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n\n    localStore.increment()\n\n    XCTAssertEqual(slice.state.primitive, 2)\n    XCTAssertEqual(slice.state.version, 2)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n  }\n\n  func testSlice2() {\n\n    let wrapper = DemoStore()\n\n    let slice = wrapper.derived(\n      .map { @Sendable in $0.count },\n      queue: .passthrough\n    )\n\n    XCTAssertEqual(slice.state.primitive, 0)\n    XCTAssertEqual(slice.state.root, 0)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n\n    wrapper.increment()\n\n    XCTAssertEqual(slice.state.primitive, 1)\n    XCTAssertEqual(slice.state.root, 1)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n\n    wrapper.empty()\n\n    XCTAssertEqual(slice.state.primitive, 1)\n    XCTAssertEqual(slice.state.version, 1)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n\n    wrapper.empty()\n\n    XCTAssertEqual(slice.state.primitive, 1)\n    XCTAssertEqual(slice.state.version, 1)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n\n    wrapper.increment()\n\n    XCTAssertEqual(slice.state.primitive, 2)\n    XCTAssertEqual(slice.state.version, 2)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n  }\n    \n  /// combine 2 stored\n  func testCombine2() {\n\n    let wrapper = DemoStore()\n    \n    let s0 = wrapper.derived(.map { @Sendable in $0.count }, queue: .passthrough)\n    let s1 = wrapper.derived(.map { @Sendable in $0.name }, queue: .passthrough)\n    \n    let updateCount = expectation(description: \"updatecount\")\n    updateCount.assertForOverFulfill = true\n    updateCount.expectedFulfillmentCount = 3\n    \n    let update0 = expectation(description: \"\")\n    update0.assertForOverFulfill = true\n    update0.expectedFulfillmentCount = 2\n    \n    let update1 = expectation(description: \"\")\n    update1.assertForOverFulfill = true\n    update1.expectedFulfillmentCount = 2\n        \n    let combined = Derived.combined(s0, s1, queue: .passthrough)\n    \n    XCTAssert((combined.state.primitive.0.primitive, combined.state.primitive.1.primitive) == (0, \"\"))\n        \n    let sub = combined.sinkState { (changes) in\n      \n      updateCount.fulfill()\n      \n      changes.ifChanged(\\.0).do { _0 in\n        update0.fulfill()\n      }\n      \n      changes.ifChanged(\\.1).do { _1 in\n        update1.fulfill()\n      }\n      \n    }\n    \n    wrapper.commit {\n      $0.count += 1\n    }\n    \n    XCTAssert((combined.state.primitive.0.primitive, combined.state.primitive.1.primitive) == (1, \"\"))\n    \n    wrapper.commit {\n      $0.name = \"next\"\n    }\n    \n    XCTAssert((combined.state.primitive.0.primitive, combined.state.primitive.1.primitive) == (1, \"next\"))\n    \n    wait(for: [updateCount, update1, update0], timeout: 10)\n    withExtendedLifetime(sub) {}\n  }\n          \n}\n\nfinal class DerivedCacheTests: XCTestCase {\n  \n  func test_identify_keypath() {\n    \n    let store1 = DemoStore()\n    let store2 = DemoStore()\n    \n    XCTAssert(store1.derived(.map(\\.count)) !== store1.derived(.map(\\.count)))\n    \n    /// Stored in each store\n    XCTAssert(store1.derived(.map(\\.count)) !== store2.derived(.map(\\.count)))\n    \n  }\n  \n  func test_identify_keypath_specify_queue_main() {\n    \n    let store1 = DemoStore()\n    let store2 = DemoStore()\n\n    XCTAssert(\n      store1.derived(.map(\\.count), queue: .asyncMain) !==\n        store1.derived(.map(\\.count), queue: .asyncMain)\n    )\n    \n    XCTAssert(\n      store1.derived(.map(\\.count), queue: .main) !==\n        store1.derived(.map(\\.count), queue: .main)\n    )\n\n    XCTAssert(\n      store1.derived(.map(\\.count)) !==\n        store1.derived(.map(\\.count), queue: .main)\n    )\n\n    XCTAssert(\n      store1.derived(.map(\\.count)) !==\n        store2.derived(.map(\\.count))\n    )\n    \n  }\n  \n  func test_identify_keypath_specify_queue_any() {\n    \n    let store1 = DemoStore()\n    let store2 = DemoStore()\n    \n    let queue = AnyTargetQueue.specific(DispatchQueue(label: \"test\"))\n    let queue2 = AnyTargetQueue.specific(DispatchQueue(label: \"test\"))\n    \n    XCTAssert(store1.derived(.map(\\.count), queue: queue) !== store1.derived(.map(\\.count), queue: queue))\n    XCTAssert(store1.derived(.map(\\.count), queue: queue) !== store1.derived(.map(\\.count), queue: .main))\n    XCTAssert(store1.derived(.map(\\.count), queue: queue) !== store1.derived(.map(\\.count), queue: queue2))\n    XCTAssert(store1.derived(.map(\\.count)) !== store2.derived(.map(\\.count)))\n        \n  }\n  \n  func test_identify_keypath_specify_queue_global() {\n    \n    let store1 = DemoStore()\n    let store2 = DemoStore()\n    \n    let queue = AnyTargetQueue.specific(DispatchQueue.global())\n    \n    XCTAssert(store1.derived(.map(\\.count), queue: queue) !== store1.derived(.map(\\.count), queue: queue))\n    XCTAssert(store1.derived(.map(\\.count), queue: queue) !== store1.derived(.map(\\.count), queue: .main))\n    XCTAssert(store1.derived(.map(\\.count)) !== store2.derived(.map(\\.count)))\n    \n  }\n     \n}\n"
  },
  {
    "path": "Tests/VergeTests/EdgeTests.swift",
    "content": "//\n//  EdgeTests.swift\n//  VergeTests\n//\n//  Created by Muukii on 2020/12/14.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nimport Verge\n\nfinal class EdgeTests: XCTestCase {\n\n  struct Mock: Equatable {\n\n    static func == (lhs: Self, rhs: Self) -> Bool {\n      lhs.onCallEquatable()\n      rhs.onCallEquatable()\n      return lhs.id == rhs.id\n    }\n\n    var onCallEquatable: () -> Void = {}\n    let id = UUID()\n  }\n\n  func testComparion() {\n\n    let exp = expectation(description: \"onCall\")\n    exp.assertForOverFulfill = false\n\n    var mock = Mock()\n    mock.onCallEquatable = {\n      exp.fulfill()\n    }\n\n    let edge = Edge<Mock>.init(wrappedValue: mock)\n    var edge2 = edge\n\n    XCTAssertEqual(edge.version, edge2.version)\n\n    edge2.wrappedValue = mock\n\n    XCTAssertNotEqual(edge.version, edge2.version)\n\n    XCTAssertTrue(edge == edge2)\n    wait(for: [exp], timeout: 1)\n  }\n  \n  func testTuple() {\n    \n    let a = Edge.init(wrappedValue: (1, 2))\n    let b = Edge.init(wrappedValue: (1, 2))\n    \n    XCTAssertEqual(a, b)\n    \n  }\n  \n  func testTuple_NoSupports_Equtable() {\n    \n    let a = Edge.init(wrappedValue: (1, 2, 3, 4, 5, 6, 7))\n    let b = Edge.init(wrappedValue: (1, 2, 3, 4, 5, 6, 7))\n    \n    XCTAssertNotEqual(a, b)\n    \n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/EventEmitterTests.swift",
    "content": "//\n//  EventEmitterTests.swift\n//  VergeCoreTests\n//\n//  Created by muukii on 2019/12/21.\n//  Copyright © 2019 muukii. All rights reserved.\n//\n\nimport XCTest\n@_spi(EventEmitter) import Verge\n\n#if canImport(Combine)\nimport Combine\n#endif\n\n@available(iOS 13.0, *)\nclass EventEmitterTests: XCTestCase {\n\n  struct _Event: EventEmitterEventType {\n    let value: String\n\n    init(_ value: String) {\n      self.value = value\n    }\n\n    func onComsume() {\n      print(\"consume\")\n    }\n  }\n\n  private var subscriptions = Set<AnyCancellable>()\n  \n  @available(iOS 13, *)\n  func testPublisher() {\n    \n    let emitter = EventEmitter<_Event>()\n\n    let waiter = XCTestExpectation()\n    \n    emitter\n      .publisher\n      .handleEvents(receiveSubscription: { (sub) in\n        print(sub)\n      }, receiveOutput: { (value) in\n        XCTAssertEqual(value.value, \"Hello\")\n        waiter.fulfill()\n      }, receiveCompletion: { (completion) in\n        \n      }, receiveCancel: {\n        \n      }, receiveRequest: { demand in\n        \n      })\n      .makeConnectable()\n      .connect()\n      .store(in: &subscriptions)\n    \n    emitter.accept(.init(\"Hello\"))\n\n    wait(for: [waiter], timeout: 10)\n  }\n  \n  @available(iOS 13, *)\n  func testPublisherMultiple() {\n    \n    let emitter = EventEmitter<_Event>()\n\n    let waiter1 = XCTestExpectation()\n    let waiter2 = XCTestExpectation()\n    let waiter3 = XCTestExpectation()\n    \n    emitter\n      .publisher\n      .sink { _ in\n        waiter1.fulfill()\n    }\n    .store(in: &subscriptions)\n    \n    emitter\n      .publisher\n      .sink { _ in\n        waiter2.fulfill()\n    }\n    .store(in: &subscriptions)\n    \n    emitter\n      .publisher\n      .sink { _ in\n        waiter3.fulfill()\n    }\n    .store(in: &subscriptions)\n    \n    emitter.accept(.init(\"Hello\"))\n\n    wait(for: [waiter1, waiter2, waiter3], timeout: 10)\n  }\n  \n  \n  func testRegistrationPerformance() {\n    \n    let emitter = EventEmitter<_Event>()\n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric(), XCTClockMetric()]) {\n      for _ in 0..<1000 {\n        emitter.addEventHandler { _ in\n          \n        }\n      }\n    }\n    \n  }\n\n  func testEmittingPerformance() {\n\n    let emitter = EventEmitter<_Event>()\n\n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric()]) {\n      for _ in 0..<10000 {\n        emitter.accept(.init(\"\"))\n      }\n    }\n\n  }\n\n  func testOrder() {\n\n    let emitter = EventEmitter<_Event>()\n\n    var results_1 = [_Event]()\n    emitter.addEventHandler { value in\n      results_1.append(value)\n\n      if value.value == \"1\" {\n        emitter.accept(.init(\"2\"))\n      }\n    }\n\n    var results_2 = [_Event]()\n    emitter.addEventHandler { value in\n      results_2.append(value)\n    }\n\n    emitter.accept(.init(\"1\"))\n\n    XCTAssertEqual(results_1.map(\\.value), [\"1\", \"2\"])\n    XCTAssertEqual(results_2.map(\\.value), [\"1\", \"2\"])\n\n  }\n\n  func testEmitsAll() {\n\n    let emitter = EventEmitter<_Event>()\n\n    emitter.addEventHandler { value in\n    }\n\n    let outputs = VergeConcurrency.UnfairLockAtomic.init([_Event]())\n    emitter.addEventHandler { value in\n      outputs.modify({\n        $0.append(value)\n      })\n    }\n\n    let inputs = VergeConcurrency.UnfairLockAtomic.init([_Event]())\n    DispatchQueue.concurrentPerform(iterations: 500) { i in\n      inputs.modify {\n        $0.append(.init(\"\\(i)\"))\n      }\n      emitter.accept(.init(\"\\(i)\"))\n    }\n\n    XCTAssertEqual(outputs.value.count, 500)\n\n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeTests/FilterTests.swift",
    "content": "//\n//  FilterTests.swift\n//  VergeCoreTests\n//\n//  Created by muukii on 2020/01/14.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\n\nimport XCTest\n\nimport Verge\n\nfinal class FilterTests: XCTestCase {\n    \n  func testCombinedFilterOR() {\n    \n    struct Model {\n      var a = 0\n      var b = 0\n      var c = 0\n    }\n\n    let comparison = OrComparator<Model, _, _>(\n      .any { @Sendable in $0.a == 1 && $1.a == 1 },\n      .any { @Sendable in  $0.b == 1 && $1.b == 1 }\n    )\n    .or(.any { @Sendable in $0.c == 1 && $1.c == 1 })\n\n    do {\n      let pre = Model()\n      let new = Model()\n      XCTAssertEqual(comparison(pre, new), false)\n    }\n    \n    do {\n      var pre = Model()\n      pre.a = 1\n      var new = Model()\n      new.a = 1\n      XCTAssertEqual(comparison(pre, new), true)\n    }\n    \n    do {\n      var pre = Model()\n      pre.c = 1\n      var new = Model()\n      new.c = 1\n      XCTAssertEqual(comparison(pre, new), true)\n    }\n    \n  }\n  \n  func testCombinedFilterAnd() {\n    \n    struct Model {\n      var a = 0\n      var b = 0\n      var c = 0\n    }\n\n    let comparison = AndComparator<Model, _, _>(\n      .any { @Sendable in $0.a == 1 && $1.a == 1 },\n      .any { @Sendable in  $0.b == 1 && $1.b == 1 }\n    )\n      .and(.any { @Sendable in $0.c == 1 && $1.c == 1 })\n\n    do {\n      let pre = Model()\n      let new = Model()\n      XCTAssertEqual(comparison(pre, new), false)\n    }\n    \n    do {\n      var pre = Model()\n      pre.a = 1\n      var new = Model()\n      new.a = 1\n      XCTAssertEqual(comparison(pre, new), false)\n    }\n    \n    do {\n      var pre = Model()\n      pre.a = 1\n      pre.b = 1\n      var new = Model()\n      new.a = 1\n      new.b = 1\n      XCTAssertEqual(comparison(pre, new), false)\n    }\n    \n    do {\n      var pre = Model()\n      pre.a = 1\n      pre.b = 1\n      pre.c = 1\n      var new = Model()\n      new.a = 1\n      new.b = 1\n      new.c = 1\n      XCTAssertEqual(comparison(pre, new), true)\n    }\n    \n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/IsolatedContextTests.swift",
    "content": "\nimport XCTest\nimport os.lock\n\n@MainActor\nfileprivate func isInMain() {}\n\nfinal class IsolatedContextTests: XCTestCase {\n  \n  func testMainActorSubscription() {\n    \n    Task { @MainActor in\n      isInMain()\n    }\n    \n    let store = DemoStore()\n    \n    _ = store.sinkState { changes in\n      isInMain()\n    }\n    \n    _ = store.sinkState(queue: .main) { @MainActor changes in\n      isInMain()\n    }\n    \n    _ = store.sinkState(queue: .mainIsolated()) { @MainActor changes in\n      isInMain()\n    }\n    \n    _ = store.sinkState(queue: .asyncSerialBackground) { changes in\n      Task { @MainActor in\n        isInMain()\n      }\n    }\n    \n  }\n  \n  func testMainActorSubscription_sink() {\n    \n    // don't add `@MainActor` to make non-isolated-context\n    \n    assert(Thread.isMainThread)\n        \n    let store = DemoStore()\n    \n    let receivedState: OSAllocatedUnfairLock<DemoStore.State?> = .init(initialState: nil)\n    \n    let sub = store.sinkState { changes in\n      receivedState.withLock {\n        $0 = changes.primitive\n      }\n    }\n    \n    store.commit {\n      $0.count = 100\n    }\n    \n    XCTAssertEqual(receivedState.withLock { $0?.count }, 100)\n    \n    withExtendedLifetime(sub, {})\n  }\n  \n  \n}\n"
  },
  {
    "path": "Tests/VergeTests/OldComparer.swift",
    "content": "/// A component that compares an input value.\n/// It can be combined with other comparers.\npublic struct Comparer<Input> {\n\n  public static var alwaysFalse: Self {\n    .init { _, _ in false }\n  }\n\n  private let _equals: (Input, Input) -> Bool\n\n  /// Creates an instance\n  ///\n  /// - Parameter equals: Return true if two inputs are equal.\n  public init(\n    _ equals: @escaping (Input, Input) -> Bool\n  ) {\n    self._equals = equals\n  }\n\n  /// It compares the value selected from passed selector closure\n  /// - Parameter selector:\n  public init<T: Equatable>(selector: @escaping (Input) -> T) {\n    self.init { a, b in\n      selector(a) == selector(b)\n    }\n  }\n\n  public init<T>(selector: @escaping (Input) -> T, equals: @escaping (T, T) -> Bool) {\n    self.init { a, b in\n      equals(selector(a), selector(b))\n    }\n  }\n\n  public init<T>(selector: @escaping (Input) -> T, comparer: Comparer<T>) {\n    self.init { a, b in\n      comparer._equals(selector(a), selector(b))\n    }\n  }\n\n  /// Make Combined comparer\n  /// - Parameter comparers:\n  public init(and comparers: [Comparer<Input>]) {\n    self.init { pre, new in\n      for filter in comparers {\n        guard filter._equals(pre, new) else {\n          return false\n        }\n      }\n      return true\n    }\n  }\n\n  /// Make Combined comparer\n  /// - Parameter comparers:\n  public init(or comparers: [Comparer<Input>]) {\n    self.init { pre, new in\n      for filter in comparers {\n        if filter._equals(pre, new) {\n          return true\n        }\n      }\n      return false\n    }\n  }\n\n  public func equals(_ lhs: Input, _ rhs: Input) -> Bool {\n    _equals(lhs, rhs)\n  }\n\n  /// Returns an curried closure\n  public func curried() -> (_ lhs: Input, _ rhs: Input) -> Bool {\n    _equals\n  }\n\n}\n\nextension Comparer where Input : Equatable {\n  public init() {\n    self.init(==)\n  }\n\n  public static var usingEquatable: Self {\n    return .init(==)\n  }\n}\n\nextension Comparer {\n\n  public func and(_ otherComparer: () -> Comparer) -> Comparer {\n    .init(and: [\n      self,\n      otherComparer()\n    ])\n  }\n\n  public func or(_ otherComparer: () -> Comparer) -> Comparer {\n    .init(or: [\n      self,\n      otherComparer()\n    ])\n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeTests/PerformanceTests.swift",
    "content": "\nimport Foundation\n\nimport XCTest\nimport Verge\n\n/**\n Store's state contains a huge dictionary.\n This test-case tests to commit mutations:\n 1. Mutates property beside of huge dictionary.\n 2. Mutates a huge dictionary.\n It compares that performance.\n It would be good if the first 1 test-case is fast without unaffected from a huge dictionary.\n */\nclass PerformanceTests: XCTestCase {\n\n  func testMutationOnAnotherProperty() {\n\n    let store = DemoStore()\n\n    measure(metrics: [XCTMemoryMetric(), XCTCPUMetric(), XCTClockMetric()]) {\n      store.increment()\n    }\n\n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeTests/PipelineTests.swift",
    "content": "import XCTest\nimport Verge\n\nfinal class PipelineTests: XCTestCase {\n  \n  func test_MapPipeline() {\n        \n    let mapCounter = VergeConcurrency.UnfairLockAtomic<Int>.init(0)\n    \n    let pipeline = Pipelines.ChangesMapPipeline<DemoState, _, Int>(\n      intermediate: {\n        $0.count\n      },\n      transform: {\n        mapCounter.modify { \n          $0 += 1\n        }\n        return $0\n      },\n      additionalDropCondition: nil\n    )\n    \n    var storage: Void = ()\n    \n    do {\n      let s = DemoState()\n            \n      XCTAssertEqual(\n        pipeline.yieldContinuously(\n          Changes<DemoState>.init(\n            old: s,\n            new: s\n          ),\n          storage: &storage\n        ),\n        .noUpdates\n      )\n      \n      XCTAssertEqual(mapCounter.value, 0)\n    }\n    \n    do {\n      \n      XCTAssertEqual(\n        pipeline.yieldContinuously(\n          Changes<DemoState>.init(\n            old: .init(name: \"A\", count: 1),\n            new: .init(name: \"A\", count: 2)\n          ),\n          storage: &storage\n        ),\n        .new(2)\n      )\n      \n      XCTAssertEqual(mapCounter.value , 2)\n      \n    }\n    \n  }\n \n  func test_MapPipeline_Intermediate() {\n    \n    let mapCounter = VergeConcurrency.UnfairLockAtomic<Int>.init(0)\n    \n    let pipeline = Pipelines.ChangesMapPipeline<DemoState, _, _>(\n      intermediate: {\n        $0.name\n      },\n      transform: {\n        mapCounter.modify { $0 += 1 }\n        return $0.count\n      },\n      additionalDropCondition: nil\n    )\n    \n    var storage: Void = ()\n    \n    do {\n      let s = DemoState()\n      \n      XCTAssertEqual(\n        pipeline.yieldContinuously(\n          Changes<DemoState>.init(\n            old: s,\n            new: s\n          ),\n          storage: &storage\n        ),\n        .noUpdates\n      )\n      \n      XCTAssertEqual(mapCounter.value, 0)\n    }\n    \n    do {\n      \n      XCTAssertEqual(\n        pipeline.yieldContinuously(\n          Changes<DemoState>.init(\n            old: .init(name: \"A\", count: 1),\n            new: .init(name: \"A\", count: 2)\n          ),\n          storage: &storage\n        ),\n        .noUpdates\n      )\n      \n      XCTAssertEqual(mapCounter.value, 0)\n      \n    }\n        \n  }\n  \n  func testSelect() {\n    \n    do {\n      let store = Verge.Store<DemoState, Never>(initialState: .init())\n//      do {\n//        let d = store.derived(.map(\\.nonEquatable))\n//        XCTAssert((d as Any) is Derived<Edge<OnEquatable>>)\n//      }\n//      \n//      do {\n//        let d = store.derived(.map(\\.nonEquatable))\n//        XCTAssert((d as Any) is Derived<Edge<NonEquatable>>)\n//      }\n      \n      do {\n        let d = store.derived(.map(\\.onEquatable))\n        XCTAssert((d as Any) is Derived<OnEquatable>)\n      }\n            \n      do {\n        let d = store.derived(.map(\\.count))\n        XCTAssert((d as Any) is Derived<Int>)\n      }\n      \n      do {\n        let d = store.derived(.map { @Sendable in $0.count })\n        XCTAssert((d as Any) is Derived<Int>)\n      }\n    }\n       \n  }\n \n}\n"
  },
  {
    "path": "Tests/VergeTests/ReferenceEdgeTests.swift",
    "content": "\nimport XCTest\nimport Verge\n\nfinal class FragmentTests: XCTestCase {\n\n  struct State {\n    var name: String = \"\"\n    @ReferenceEdge var number = 0\n  }\n\n  func testFragment() {\n\n    var state = State()\n    XCTAssertEqual(state.number, 0)\n\n    state.number += 1\n\n    XCTAssertEqual(state.number, 1)\n  }\n\n  func testFragmentWithCopy() {\n\n    let state = State()\n    XCTAssertEqual(state.number, 0)\n\n    var anotherState = state\n    anotherState.number += 1\n\n    XCTAssertEqual(anotherState.number, 1)\n\n    XCTAssertNotEqual(state.$number._storagePointer, anotherState.$number._storagePointer)\n  }\n\n  func testReference() {\n\n    var state = State()\n\n    state.number += 1\n\n    state.name = \"A\"\n\n    var state2 = state\n    state2.name = \"B\"\n\n    XCTAssert(state.$number._storagePointer == state2.$number._storagePointer)\n\n  }\n\n  func testCast() {\n\n    let source = ReferenceEdge<State?>(wrappedValue: State())\n\n    var binded = unsafeBitCast(source, to: ReferenceEdge<State>.self)\n\n    print(binded.name)\n\n    binded.name = \"hiroshi\"\n\n    XCTAssertEqual(binded.name, \"hiroshi\")\n\n  }\n\n}\n\n"
  },
  {
    "path": "Tests/VergeTests/Retain/PublisherCompletionTests.swift",
    "content": "\nimport Foundation\nimport Combine\nimport Verge\nimport XCTest\n\nfinal class SubjectCompletionTests: XCTestCase {\n\n  func testStatePublisherCompletion1() {\n\n    var bag = Set<AnyCancellable>()\n\n    var store: DemoStore? = DemoStore()\n    weak var weakStore: DemoStore? = store\n\n    store?.statePublisher()\n      .sink(\n        receiveCompletion: { _ in\n          XCTFail()\n        },\n        receiveValue: { _ in }\n      )\n      .store(in: &bag)\n\n    XCTAssertNotNil(weakStore)\n\n    store = nil\n\n    XCTAssertNil(weakStore)\n\n  }\n\n  func testActivityPublisherCompletion1() {\n\n    var bag = Set<AnyCancellable>()\n\n    var store: DemoStore? = DemoStore()\n    weak var weakStore: DemoStore? = store\n\n    store?\n      .activityPublisher()\n      .sink(\n        receiveCompletion: { _ in\n          XCTFail()\n        },\n        receiveValue: { _ in\n          \n        }\n      )\n      .store(in: &bag)\n\n    XCTAssertNotNil(weakStore)\n\n    store = nil\n\n    XCTAssertNil(weakStore)\n    bag.forEach { $0.cancel() }\n    XCTAssertNil(weakStore)\n\n  }\n\n  func testActivityPublisherCompletion2() {\n\n    var bag = Set<AnyCancellable>()\n\n    var store: DemoStore? = DemoStore()\n    weak var weakStore: DemoStore? = store\n\n    store!.activityPublisher()\n      .sink(\n        receiveCompletion: { _ in\n          XCTFail(\"It should not be called, as the subscription was canceled before publishing completion.\")\n        },\n        receiveValue: { [store] _ in\n          withExtendedLifetime(store) {}\n        }\n      )\n      .store(in: &bag)\n\n    XCTAssertNotNil(weakStore)\n\n    store = nil\n\n    XCTAssertNotNil(weakStore)\n    bag.forEach { $0.cancel() }\n    XCTAssertNil(weakStore)\n\n  }\n\n  func testActivityPublisherCompletion_deallocated() {\n\n    var bag = Set<AnyCancellable>()\n\n    var store: DemoStore? = DemoStore()\n    weak var weakStore: DemoStore? = store\n\n    var strongRef: Ref? = Ref()\n    weak var weakRef = strongRef\n\n    store!.activityPublisher()\n      .sink(\n        receiveCompletion: { _ in\n          XCTFail()\n        },\n        receiveValue: { _ in\n          print(\"\")\n          withExtendedLifetime(strongRef) {}\n        }\n      )\n      .store(in: &bag)\n\n    strongRef = nil\n    store = nil\n\n    XCTAssertNil(weakStore)\n\n    XCTAssertNil(weakRef)\n\n  }\n\n  func testDerived_publisher_retains_derived() {\n\n    var c: AnyCancellable?\n\n    let ref = withReference(DemoStore())\n\n    let derivedRef = withReference(ref.value!.derived(.map(\\.count)))\n\n    c = derivedRef.value!\n      .statePublisher()\n      .sink(\n        receiveCompletion: { _ in\n          XCTFail()\n        },\n        receiveValue: { _ in\n\n        }\n      )\n\n\n    derivedRef.release()\n\n    XCTAssertNotNil(derivedRef.value)\n\n    c?.cancel()\n\n    XCTAssertNil(derivedRef.value)\n\n  }\n\n  func testDerived_stream_stops_on_store_deallocated() async {\n\n    var c: AnyCancellable?\n\n    let storeRef = withReference(DemoStore())\n\n    let derivedRef = withReference(storeRef.value!.derived(.map(\\.count)))\n\n    storeRef.release()\n\n    await Task.yield()\n\n    XCTAssertNil(storeRef.value)\n\n    c = derivedRef.value!\n      .statePublisher()\n      .sink(\n        receiveCompletion: { _ in\n          XCTFail()\n        },\n        receiveValue: { _ in\n        }\n      )\n\n    derivedRef.release()\n\n    await Task.yield()\n    \n    // still not nil as the subscription is still on going.\n    XCTAssertNotNil(derivedRef.value)\n\n    XCTAssertNil(storeRef.value)\n    \n    withExtendedLifetime(c, {})\n    \n    c?.cancel()\n    \n    XCTAssertNil(derivedRef.value)\n\n  }\n\n  class Ref {}\n}\n\nfinal class Reference<T: AnyObject>: @unchecked Sendable, CustomDebugStringConvertible {\n\n  weak var value: T?\n  private var strong: T?\n\n  init(_ object: T){\n    self.value = object\n    self.strong = object\n  }\n\n  func release() {\n    strong = nil\n  }\n  \n  var debugDescription: String {\n    \"\\(value)\"\n  }\n\n}\n\nfunc withReference<T: AnyObject>(_ object: T) -> Reference<T> {\n  return .init(object)\n}\n"
  },
  {
    "path": "Tests/VergeTests/Retain/StoreSinkSusbscriptionTests.swift",
    "content": "import Verge\nimport XCTest\nimport Atomics\n\nfinal class StoreSinkSubscriptionTests: XCTestCase {\n\n  func test_Store_sinkState_stops_on_store_deallocated() {\n\n    let storeRef = withReference(DemoStore())\n    let resourceRef = withReference(Resource())\n\n    storeRef.value!\n      .sinkState { [ref = resourceRef.value!] _ in\n\n        withExtendedLifetime(ref) {}\n      }\n      .storeWhileSourceActive()\n\n    resourceRef.release()\n\n    XCTAssertNotNil(storeRef.value)\n    XCTAssertNotNil(resourceRef.value)\n\n    storeRef.release()\n\n    XCTAssertNil(storeRef.value)\n    XCTAssertNil(resourceRef.value)\n\n  }\n\n  func test_Store_sinkState_canceled_by_others() {\n\n    var cancellable: StoreStateSubscription?\n\n    let storeRef = withReference(DemoStore())\n    let resourceRef = withReference(Resource())\n\n    cancellable = storeRef.value!\n      .sinkState { [ref = resourceRef.value!] _ in\n\n        withExtendedLifetime(ref) {}\n      }\n      .storeWhileSourceActive()\n\n    resourceRef.release()\n\n    XCTAssertNotNil(storeRef.value)\n    XCTAssertNotNil(resourceRef.value)\n\n    cancellable?.cancel()\n\n    XCTAssertNotNil(storeRef.value)\n    XCTAssertNil(resourceRef.value)\n\n  }\n\n  func test_Store_sinkActivity_stops_on_store_deallocated() {\n\n    let storeRef = withReference(DemoStore())\n    let resourceRef = withReference(Resource())\n\n    storeRef.value!\n      .sinkActivity { [ref = resourceRef.value!] _ in\n\n        withExtendedLifetime(ref) {}\n      }\n      .storeWhileSourceActive()\n\n    resourceRef.release()\n\n    XCTAssertNotNil(storeRef.value)\n    XCTAssertNotNil(resourceRef.value)\n\n    storeRef.release()\n\n    XCTAssertNil(storeRef.value)\n    XCTAssertNil(resourceRef.value)\n\n  }\n\n  func test_Derived_lifeCycle_with_source() {\n\n    let storeRef = withReference(DemoStore())\n    let resourceRef = withReference(Resource())\n    let derivedRef = withReference(storeRef.value!.derived(.select(\\.count)))\n\n    derivedRef.value!\n      .sinkState { [ref = resourceRef.value!] _ in\n\n        withExtendedLifetime(ref) {}\n      }\n      .storeWhileSourceActive()\n\n    resourceRef.release()\n\n    XCTAssertNotNil(storeRef.value)\n    XCTAssertNotNil(resourceRef.value)\n\n    storeRef.release()\n\n    XCTAssertNil(storeRef.value)\n    XCTAssertNil(resourceRef.value)\n\n  }\n\n  func test_Derived_lifeCycle_with_source_release_store_earlier() {\n\n    let storeRef = withReference(DemoStore())\n    let resourceRef = withReference(Resource())\n\n    // make derived\n    let derivedRef = withReference(storeRef.value!.derived(.select(\\.count)))\n\n    // start subscribe\n    derivedRef.value!\n      .sinkState { [ref = resourceRef.value!] _ in\n\n        withExtendedLifetime(ref) {}\n      }\n      .storeWhileSourceActive()\n\n    // make the resource is captured only from the closure\n    resourceRef.release()\n    XCTAssertNotNil(resourceRef.value)\n\n    // release store earlier than stop derived\n    storeRef.release()\n    // should be nil because derived won't retain store as upstream\n    XCTAssertNil(storeRef.value)\n\n    // released all resouces\n    XCTAssertNil(resourceRef.value)\n\n  }\n\n  func testCompare() {\n    let wasInvalidated = Atomics.ManagedAtomic(false)\n\n    XCTAssertTrue(wasInvalidated.compareExchange(expected: false, desired: true, ordering: .relaxed).exchanged)\n    XCTAssertFalse(wasInvalidated.compareExchange(expected: false, desired: true, ordering: .relaxed).exchanged)\n  }\n\n  /**\n   Store won't retain the Derived\n   */\n  func testRelease() {\n\n    let wrapper = DemoStore()\n    let ref = withReference(wrapper.derived(.map { @Sendable in $0.count }, queue: .passthrough))\n    ref.release()\n    XCTAssertNil(ref.value)\n\n  }\n\n  func testRetain() {\n\n    let store = DemoStore()\n\n    let derivedRef = withReference(store.derived(.map { @Sendable in $0.count }, queue: .passthrough))\n\n    let expectation = XCTestExpectation(description: \"receive changes\")\n    expectation.expectedFulfillmentCount = 1\n    expectation.assertForOverFulfill = true\n\n    let subscription = derivedRef\n      .value!\n      .sinkState(\n        dropsFirst: true,\n        queue: .passthrough\n      ) { (changes) in\n        expectation.fulfill()\n      }\n\n    XCTAssertNotNil(derivedRef.value)\n\n    derivedRef.release()\n\n    XCTAssertNotNil(derivedRef.value, \"as still subscribing\")\n\n    store.commit { _ in }\n\n    store.commit { $0.count += 1 }\n\n    subscription.cancel()\n\n    XCTAssertNil(derivedRef.value)\n\n    wait(for: [expectation], timeout: 1)\n\n  }\n\n  func test_derived_chain() {\n\n    let wrapper = DemoStore()\n\n    var baseSlice: Derived<Int>! = wrapper.derived(.map { @Sendable in $0.count }, queue: .passthrough)\n\n    weak var weakBaseSlice = baseSlice\n\n    var slice: Derived<Int>! = baseSlice.derived(.map { @Sendable in $0.self }, queue: .passthrough)\n\n    baseSlice = nil\n\n    weak var weakSlice = slice\n\n    XCTAssertEqual(slice.state.primitive, 0)\n    XCTAssertEqual(slice.state.version, 0)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n    XCTAssertNotNil(weakBaseSlice)\n\n    wrapper.increment()\n\n    XCTAssertEqual(slice.state.primitive, 1)\n    XCTAssertEqual(slice.state.version, 1)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n    XCTAssertNotNil(weakBaseSlice)\n\n    wrapper.empty()\n\n    XCTAssertEqual(slice.state.primitive, 1)\n    XCTAssertEqual(slice.state.version, 1) // with memoized, version not changed\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n    XCTAssertNotNil(weakBaseSlice)\n\n    wrapper.increment()\n\n    XCTAssertEqual(slice.state.primitive, 2)\n    XCTAssertEqual(slice.state.version, 2)\n    XCTAssertEqual(slice.state.hasChanges(\\.self), true)\n    XCTAssertNotNil(weakBaseSlice)\n\n    slice = nil\n\n    XCTAssertNil(weakSlice)\n    XCTAssertNil(weakBaseSlice)\n\n  }\n\n  final class Resource {\n    deinit {\n      print(\"d\")\n    }\n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/RunLoopTests.swift",
    "content": "import XCTest\n@testable import Verge\n\nfinal class RunLoopTests: XCTestCase {\n\n  func test_performance_adding() {\n\n    measure {\n      for _ in 0..<1000 {\n        RunLoopActivityObserver.addObserver(acitivity: .beforeWaiting, in: .main) {\n        }\n      }\n    }\n\n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeTests/Sample.swift",
    "content": "//\n//  Sample.swift\n//  VergeStoreTests\n//\n//  Created by muukii on 2020/04/18.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\n\n#if canImport(UIKIt)\nimport UIKit\n\nimport Verge\n\nenum Sample {\n  \n  struct State: StateType {\n    var name: String = \"\"\n    var age: Int = 0\n  }\n  \n  enum Activity {\n    case somethingHappen\n  }\n  \n  class ViewController: UIViewController {\n    \n    private let nameLabel: UILabel = .init()\n    private let ageLabel: UILabel = .init()\n    \n    let store = Store<State, Activity>(initialState: .init(), logger: nil)\n    \n    var subscriptions = Set<AnyCancellable>()\n    \n    override func viewDidLoad() {\n      super.viewDidLoad()\n      \n      store.sinkState { [weak self] (changes) in\n        self?.update(changes: changes)\n      }\n      .store(in: &subscriptions)\n    \n    }\n    \n    private func update(changes: Changes<State>) {\n      \n      changes.ifChanged(\\.name) { (name) in\n        nameLabel.text = name\n      }\n      \n      changes.ifChanged(\\.age) { (age) in\n        ageLabel.text = age.description\n      }\n      \n    }\n    \n  }\n}\n\n#endif\n"
  },
  {
    "path": "Tests/VergeTests/StateTypeTests.swift",
    "content": "import Foundation\nimport Verge\nimport XCTest\n\nfinal class StateTypeTests: XCTestCase {\n  \n  func test_init() {\n    \n    let store = Store<State, Never>(initialState: .init())\n    \n    XCTAssertEqual(store.state.count2, 1)\n    \n  }\n\n  func test_store() {\n\n    let store = Store<State, Never>(initialState: .init())\n\n    store.commit {\n      $0.count = 1\n    }\n        \n    XCTAssertEqual(store.state.count2, 2)\n    \n    store.commit {\n      $0.name = \"a\"\n    }\n    \n    XCTAssertEqual(store.state.count2, 2)\n  }\n\n  struct State: StateType {\n\n    var name = \"\"\n    var count = 0\n    var count2 = 0\n    \n    static func reduce(\n      modifying: inout StateTypeTests.State,\n      transaction: inout Transaction,\n      current: Changes<StateTypeTests.State>\n    ) {\n      \n      current.ifChanged(\\.count).do { _ in\n        modifying.count2 += 1\n      }\n    }\n    \n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeTests/StoreAndDerivedTests.swift",
    "content": "import Verge\nimport XCTest\n\nfinal class StoreAndDerivedTests: XCTestCase {\n\n  @MainActor\n  func test() async {\n\n    let store = Store<_, Never>(initialState: DemoState())\n\n    let _ = store.derived(.select(\\.name))\n    let countDerived = store.derived(.select(\\.count))\n\n    await withTaskGroup(of: Void.self) { group in\n\n      for i in 0..<1000 {\n        group.addTask {\n          await withBackground {\n            store.commit {\n              $0.name = \"\\(i)\"\n            }\n          }\n\n        }\n      }\n\n      group.addTask {\n        await withBackground {\n          store.commit {\n            $0.count = 100\n          }\n        }\n\n\n        XCTAssertEqual(store.state.count, 100)\n\n        await store.waitUntilAllEventConsumed()\n        // potentially it fails as EventEmitter's behavior\n        // If EventEmitter's buffer is not empty, commit function escape from the stack by only adding.\n        XCTAssertEqual(countDerived.state.primitive, 100)\n      }\n\n    }\n\n    print(\"end\")\n\n  }\n\n}\n\n/**\n Performs the given task in background\n */\npublic nonisolated func withBackground<Return: Sendable>(\n  _ thunk: @escaping @Sendable () async throws -> Return\n) async rethrows -> Return {\n\n  // for now we will keep this until Swift6.\n  assert(Thread.isMainThread == false)\n\n  // here is the background as it's nonisolated\n  // to inherit current actor context, use @_unsafeInheritExecutor\n\n  // thunk closure runs on the background as it's sendable\n  // if it's not sendable, inherit current actor context but it's already background.\n  // @_inheritActorContext makes closure runs on current actor context even if it's sendable.\n  return try await thunk()\n}\n"
  },
  {
    "path": "Tests/VergeTests/StoreInitTests.swift",
    "content": "\nimport XCTest\nimport Verge\n\nfinal class StoreInitTests: XCTestCase {\n  \n  class RefState {\n    \n  }\n /*\n  class RefViewModel: StoreComponentType {\n    \n    class State: Equatable {\n      static func == (lhs: StoreInitTests.RefViewModel.State, rhs: StoreInitTests.RefViewModel.State) -> Bool {\n        true\n      }\n      \n      init() {}\n    }\n    \n    let store: DefaultStore\n    \n    init() {\n      \n      // it raises a warning\n      self.store = DefaultStore(initialState: .init())\n    }\n  }\n  */\n  \n  class StructViewModel: StoreDriverType {\n    \n    struct State: Equatable {\n      \n      init() {}\n    }\n    \n    let store: Store<State, Never>\n    \n    init() {\n      \n      self.store = .init(initialState: .init())\n    }\n  }\n      \n}\n"
  },
  {
    "path": "Tests/VergeTests/StoreMiddlewareTests.swift",
    "content": "import Testing\n\n@Suite(\"StoreMiddlewareTests\")\nstruct StoreMiddlewareTests {\n\n  @Test(\"Commit Hook\")\n  func testCommitHook() {\n    let store = DemoStore()\n\n    store.add(\n      middleware: .modify { @Sendable modifyingState, transaction, current in\n        current.ifChanged(\\.count).do { _ in\n          modifyingState.count += 1\n        }\n      })\n\n    store.add(\n      middleware: .modify { @Sendable modifyingState, transaction, current in\n        current.ifChanged(\\.name).do { _ in\n          modifyingState.count = 100\n        }\n      })\n\n    #expect(store.state.count == 0)\n\n    store.commit {\n      $0.count += 1\n    }\n\n    #expect(store.state.count == 2)\n\n    store.commit {\n      $0.name = \"A\"\n    }\n\n    if case .graph(let graph) = store.state.modification {\n      graph.prettyPrint()\n      #expect(\n        graph.prettyPrint() == \"\"\"\n          VergeTests.DemoState {\n            name-(1)+(1)\n            count-(1)+(1)\n          }\n          \"\"\")\n    }\n\n    #expect(store.state.count == 100)\n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/StoreSinkTests.swift",
    "content": "import Verge\nimport XCTest\n\n@MainActor\nfileprivate func UI() {\n\n}\n\nfinal class StoreSinkTests: XCTestCase {\n\n  func testMainActorSubscription() {\n\n    let store = DemoStore()\n\n    _ = store.sinkState { _ in\n      UI()\n    }\n\n    _ = store.sinkState(queue: .main) { @MainActor _ in\n      UI()\n    }\n\n  }\n\n  func testNonActorSubscription() {\n\n    let store = DemoStore()\n\n    _ = store.sinkState(queue: .passthrough) { _ in\n      Task {\n        await UI()\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/StoreTaskTests.swift",
    "content": "import Verge\nimport XCTest\nimport Atomics\n\nfinal class StoreTaskTests: XCTestCase {\n\n  func test() {\n    \n    let atomic = ManagedAtomic<Bool>.init(false)\n\n    do {\n      let r = atomic.compareExchange(expected: true, desired: true, ordering: .sequentiallyConsistent).exchanged\n      print(r)\n    }\n\n    do {\n      let r = atomic.compareExchange(expected: true, desired: false, ordering: .sequentiallyConsistent).exchanged\n      print(r)\n    }\n\n    do {\n      let r = atomic.compareExchange(expected: false, desired: true, ordering: .sequentiallyConsistent).exchanged\n      print(r)\n    }\n\n  }\n\n  @MainActor\n  func testActorContext_onMainActor() async throws {\n\n    let store = DemoStore()\n\n    try await store.task {\n      XCTAssertTrue(Thread.isMainThread)\n    }\n    .value\n\n    try await store.taskDetached {\n      XCTAssertFalse(Thread.isMainThread)\n    }\n    .value\n  }\n\n  func testActorContext() async throws {\n\n    let store = DemoStore()\n\n    try await store.task {\n      XCTAssertFalse(Thread.isMainThread)\n    }\n    .value\n\n    try await store.taskDetached {\n      XCTAssertFalse(Thread.isMainThread)\n    }\n    .value\n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/SynchronizeDisplayValueTests.swift",
    "content": "//\n//  SynchronizeDisplayValueTests.swift\n//  VergeStoreTests\n//\n//  Created by muukii on 2019/11/09.\n//  Copyright © 2019 muukii. All rights reserved.\n//\n\nimport Foundation\n\nimport XCTest\n\nimport Verge\n"
  },
  {
    "path": "Tests/VergeTests/SyntaxTests.swift",
    "content": "//\n//  SyntaxTests.swift\n//  VergeStoreTests\n//\n//  Created by muukii on 2020/05/24.\n//  Copyright © 2020 muukii. All rights reserved.\n//\n\nimport Foundation\n\nimport Verge\nimport VergeMacros\n\nenum SyntaxTests {\n\n  static func code() {\n\n    let changes: Changes<DemoState> = .init(old: nil, new: .init())\n\n    changes.ifChanged(\\.name).do { name in\n\n    }\n\n//    changes.ifChanged({ ($0.name, $0.name) }) { args in\n//    }\n\n    changes.ifChanged({ $0.nonEquatable }, comparator: .alwaysFalse()).do { name in\n\n    }\n\n    changes.ifChanged({ $0.name }).do { name in\n\n    }\n\n    changes.ifChanged(\\.name, \\.count).do { name, count in\n\n    }\n\n  }\n}\n"
  },
  {
    "path": "Tests/VergeTests/TransactionTests.swift",
    "content": "import Verge\nimport XCTest\n\nfinal class TransactionTests: XCTestCase {\n\n  func testTransaction() async {\n\n    struct MyKey: TransactionKey {\n      static var defaultValue: String? {\n        nil\n      }\n    }\n\n    let store = Store<DemoState, Never>(initialState: .init())\n\n    await store.commit {\n      $0.count += 1\n      $1[MyKey.self] = \"first commit\"\n    }\n\n    XCTAssertEqual(store.state._transaction[MyKey.self], \"first commit\")\n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeTests/Usage.swift",
    "content": "\nimport Verge\n\nstruct RootState: Equatable {\n\n  struct Nested: Equatable {}\n\n  var nested: Nested = .init()\n\n}\n\nfinal class RootStore: Store<RootState, Never>, @unchecked Sendable {\n\n}\n\nfinal class Service: StoreDriverType {\n\n  var store: RootStore { fatalError() }\n\n  init() {\n\n  }\n\n}\n\nfinal class SpecificService: StoreDriverType {\n\n  var scope: WritableKeyPath<RootState, RootState.Nested> & Sendable { \\.nested }\n\n  var store: RootStore { fatalError() }\n\n  init() {\n\n    _ = sinkState { state in\n\n      let _: Changes<RootState.Nested> = state\n    }\n\n  }\n\n}\n\nfinal class ViewModel: StoreDriverType {\n\n  struct State: Equatable {}\n\n  let store: Store<State, Never> = .init(initialState: .init())\n\n  init() {\n\n    commit { _ in\n\n    }\n\n    _ = sinkState { state in\n      let _: Changes<State> = state\n    }\n\n  }\n\n}\n\n// MARK: - Abstraction\n\nprotocol MyViewModelType: StoreDriverType where TargetStore.State == String, TargetStore.Activity == Int {\n\n}\n\nfinal class Concrete: MyViewModelType {\n\n  let store: Verge.Store<String, Int>\n\n  init() {\n    store = .init(initialState: .init())\n\n    _ = sinkState { _ in\n\n    }\n\n    commit { _ in\n\n    }\n\n  }\n\n}\n\nfinal class Controller<ViewModel: MyViewModelType> where ViewModel.Scope == ViewModel.TargetStore.State {\n\n  init(viewModel: ViewModel) {\n\n    let _: Changes<String> = viewModel.state\n\n    viewModel.send(1)\n  }\n\n}\n"
  },
  {
    "path": "Tests/VergeTests/VergeStoreTests.swift",
    "content": "//\n//  VergeStoreTests.swift\n//  VergeStoreTests\n//\n//  Created by muukii on 2019/11/04.\n//  Copyright © 2019 muukii. All rights reserved.\n//\n\nimport XCTest\n\nimport Verge\nimport os.lock\n\nimport Combine\n\n@available(iOS 13.0, *)\nfinal class VergeStoreTests: XCTestCase {\n      \n  @Tracking\n  struct _State {\n\n    @Tracking\n    struct TreeA {\n      \n    }\n    \n    @Tracking\n    struct TreeB {\n      \n    }\n    \n    @Tracking\n    struct TreeC {\n      \n    }\n    \n    struct NestedState: Equatable {\n      \n      var myName: String = \"\"\n    }\n    \n    struct OptionalNestedState: Equatable {\n      \n      var myName: String = \"\"\n    }\n    \n    var count: Int = 0\n    var optionalNested: OptionalNestedState?\n    var nested: NestedState = .init()\n    \n    var treeA: TreeA = TreeA()\n    var treeB: TreeB = TreeB()\n    var treeC: TreeC = TreeC()\n    \n  }\n  \n  final class _Store: Verge.Store<_State, Never>, @unchecked Sendable {\n\n    init() {\n      super.init(initialState: .init(), logger: DefaultStoreLogger.default)\n    }\n  }\n  \n  class RootDispatcher: StoreDriverType {\n\n    enum Error: Swift.Error {\n      case something\n    }\n\n    var scope: WritableKeyPath<VergeStoreTests._State, VergeStoreTests._State> {\n      \\.self\n    }\n\n    let store: _Store\n\n    init(store: _Store) {\n      self.store = store\n    }\n\n    func resetCount() {\n      return commit { s in\n        s.count = 0\n      }\n    }\n    \n    func increment() {\n      commit {\n        $0.count += 1\n      }\n    }\n    \n    func setNestedState() {\n      commit {\n        $0.optionalNested = .init()\n      }\n    }\n    \n    func setMyName() {\n      commit {\n        if $0.optionalNested != nil {\n          $0.optionalNested?.myName = \"Muuk\"\n        }\n      }\n    }\n    \n    func returnSomeValue() -> String {\n      return commit { _ in\n        return \"Hello, Verge\"\n      }\n    }\n    \n    func continuousIncrement() {\n      increment()\n      increment()\n    }\n    \n    func failableIncrement() throws {\n      try commit { state in\n        throw Error.something\n      }\n    }\n    \n    func hoge() {\n      \n      let _detached = detached(from: \\.nested)\n      \n      let _: Changes<TargetStore.State.NestedState> = _detached.state\n\n      _detached.commit { (state: inout TargetStore.State.NestedState) in\n\n      }\n        \n      let optionalNestedTarget = detached(from: \\.optionalNested)\n                  \n      let _: Changes<TargetStore.State.OptionalNestedState?> = optionalNestedTarget.state\n\n      optionalNestedTarget.commit { (state: inout TargetStore.State.OptionalNestedState?) in\n\n      }\n                      \n    }\n    \n  }\n  \n  /**\n   Use Edge due to TreeA does not have Equatable.\n   */\n  final class TreeADispatcher: StoreDriverType {\n\n    let store: _Store\n    let scope: WritableKeyPath<VergeStoreTests._State, _State.TreeA> & Sendable = \\.treeA\n\n    init(store: _Store) {\n      self.store = store\n    }\n    \n    func operation() {\n      \n      let _: Changes<_State.TreeA> = state\n      \n      commit { (state: inout _State.TreeA) in\n\n      }\n      \n      let treeB = detached(from: \\.treeB)\n      \n      let _: Changes<_State.TreeB> = treeB.state\n                         \n      treeB.commit { (state: inout _State.TreeB) in\n\n      }\n         \n    }\n  }\n  \n  let store = _Store()\n  lazy var dispatcher = RootDispatcher(store: self.store)\n\n  var subs = Set<AnyCancellable>()\n  \n  override func setUp() {\n    // Put setup code here. This method is called before the invocation of each test method in the class.\n  }\n  \n  override func tearDown() {\n    // Put teardown code here. This method is called after the invocation of each test method in the class.\n  }\n  \n  func testCommit() {\n\n    let store = DemoStore()\n\n    store.commit {\n      $0.count = 100\n    }\n\n    XCTAssertEqual(store.state.count, 100)\n\n    store.commit {\n      $0.inner.name = \"mmm\"\n    }\n\n    XCTAssertEqual(store.state.inner.name, \"mmm\")\n\n    let exp = expectation(description: \"async\")\n\n    DispatchQueue.global().async {\n      store.commit {\n        $0.inner.name = \"xxx\"\n      }\n      XCTAssertEqual(store.state.inner.name, \"xxx\")\n      exp.fulfill()\n    }\n\n    wait(for: [exp], timeout: 1)\n\n  }\n\n  func testEmptyCommit() {\n\n    let store = DemoStore()\n\n    let count = VergeConcurrency.UnfairLockAtomic<Int>.init(0)\n\n    let subs = store.sinkState(queue: .passthrough) { (_) in\n      count.modify { $0 += 1 }\n    }\n\n    XCTAssertEqual(store.state.version, 0)\n\n    store.commit {\n      $0.count = 100\n    }\n\n    XCTAssertEqual(store.state.version, 1)\n\n    store.commit { _ in\n\n    }\n\n    // no changes\n    XCTAssertEqual(store.state.version, 1)\n\n    store.commit {\n      $0.count = 100\n    }\n\n    // many times calling empty commits\n    for _ in 0..<3 {\n      store.commit { _ in }\n    }\n\n    // no affects from read a value\n    store.commit {\n      if $0.count > 100 {\n        $0.count = 0\n        XCTFail()\n      }\n    }\n\n    XCTAssertEqual(store.state.version, 2)\n    XCTAssertEqual(count.value, 3)\n\n    withExtendedLifetime(subs, {})\n    \n  }\n\n  func testDispatch() {\n    \n    dispatcher.resetCount()\n    dispatcher.resetCount()\n        \n    dispatcher.resetCount()\n    dispatcher.continuousIncrement()\n    XCTAssert(store.state.primitive.count == 2)\n  }\n  \n  func testTryMutation() {\n    \n    do {\n      try dispatcher.failableIncrement()\n      XCTFail()\n    } catch {\n      \n    }\n    \n  }\n  \n  func testIncrement() {\n    \n    dispatcher.increment()\n    XCTAssertEqual(store.state.primitive.count, 1)\n    \n  }\n  \n  func testTargetingCommit() {\n    \n    dispatcher.setNestedState()\n    dispatcher.setMyName()\n    XCTAssertEqual(store.state.primitive.optionalNested?.myName, \"Muuk\")\n  }\n  \n  func testReturnAnyValueFromMutation() {\n    \n    let r = dispatcher.returnSomeValue()\n    \n    XCTAssertEqual(r, \"Hello, Verge\")\n    \n  }\n  \n  func testSubscription() {\n    \n    var subscriptions = Set<AnyCancellable>()\n    let count = VergeConcurrency.UnfairLockAtomic<Int>.init(0)\n    \n    store.sinkState(queue: .passthrough) { (changes) in\n      count.modify {\n        $0 += 1\n      }\n    }\n    .store(in: &subscriptions)\n        \n    store.commit {\n      $0.count += 1\n    }\n    \n    // stop subscribing\n    subscriptions = .init()\n\n    store.commit {\n      $0.count += 1\n    }\n    \n    XCTAssertEqual(count.value, 2)\n    \n  }\n  \n  @MainActor\n  func testChangesPublisher() {\n    \n    let store = DemoStore()\n    \n    XCTContext.runActivity(named: \"Premise\") { (activity) in\n      \n      XCTAssertEqual(store.state.hasChanges(\\.count), true)\n      \n      store.commit {\n        $0.count = $0.count\n      }\n      \n      XCTAssertEqual(store.state.hasChanges(\\.count), false)\n      \n    }\n    \n    XCTContext.runActivity(named: \"startsFromInitial: true\") { (activity) in\n      \n      let exp1 = expectation(description: \"\")\n      \n      _ = store.statePublisher()\n        .sink { changes in\n          exp1.fulfill()\n          XCTAssertEqual(changes.hasChanges(\\.count), true)\n        }\n      \n      XCTAssertEqual(exp1.expectedFulfillmentCount, 1)\n      \n      wait(for: [exp1], timeout: 1)\n      \n    }\n     \n  }\n\n  func testAsigneeFromStore() {\n\n    let store1 = DemoStore()\n    let store2 = DemoStore()\n\n    let sub = store1\n      .assign(to: store2.assignee(\\.recursive))\n\n    store1.commit {\n      $0.count += 1\n    }\n\n    XCTAssertEqual(store1.state.primitive.count, store2.state.primitive.recursive?.count)\n\n    store1.commit {\n      $0.count += 1\n    }\n\n    XCTAssertEqual(store1.state.primitive.count, store2.state.primitive.recursive?.count)\n\n    withExtendedLifetime(sub, {})\n\n  }\n  \n  enum MyError: Error {\n    case something\n  }\n\n  func testThrowing() {\n    \n    let store = DemoStore()\n    \n    do {\n      try store.commit { _ in\n        throw MyError.something\n      }\n    } catch {\n      print(error)\n    }\n    \n  }\n\n  func testAsigneeFromDerived() {\n    \n    let store1 = DemoStore()\n    let store2 = DemoStore()\n    \n    let sub = store1\n      .derived(.map(\\.count), queue: .passthrough)\n      .assign(to: store2.assignee(\\.count))\n    \n    store1.commit {\n      $0.count += 1\n    }\n    \n    XCTAssertEqual(store1.state.primitive.count, store2.state.primitive.count)\n    \n    store1.commit {\n      $0.count += 1\n    }\n    \n    XCTAssertEqual(store1.state.primitive.count, store2.state.primitive.count)\n    \n    withExtendedLifetime(sub, {})\n    \n  }\n\n  final class DemoStoreWrapper2: StoreDriverType {\n\n    struct State: Equatable {\n      var source: Changes<Int>\n    }\n\n    let store: Verge.Store<State, Never>\n    var sub: StoreStateSubscription? = nil\n\n    init(sourceStore: DemoStore) {\n\n      let d = sourceStore\n        .derived(.map(\\.count), queue: .passthrough)\n\n      self.store = .init(initialState: .init(source: d.state), logger: nil)\n\n      sub = d.assign(to: store.assignee(\\.source))\n\n    }\n\n  }\n  \n  func testAsignee2() {\n\n    let store1 = DemoStore()\n    let store2 = DemoStoreWrapper2(sourceStore: store1)\n\n    store1.commit {\n      $0.count += 1\n    }\n    \n    XCTAssertEqual(store1.state.primitive.count, store2.state.primitive.source.root)\n\n    store1.commit {\n      $0.count += 1\n    }\n    \n    XCTAssertEqual(store1.state.primitive.count, store2.state.primitive.source.root)\n\n  }\n\n  func testScan() {\n\n    let store1 = DemoStore()\n\n    let expect = expectation(description: \"\")\n\n    let subscription = store1.sinkState(scan: Scan(seed: 0, accumulator: { v, c in v += 1 })) { changes, accumulated in\n      XCTAssertEqual(accumulated, 1)\n      expect.fulfill()\n    }\n\n    withExtendedLifetime(subscription) {}\n    wait(for: [expect], timeout: 1)\n  }\n   \n  func testMapIfPresent() {\n    \n    let store = _Store()\n    \n    XCTAssert(store.state.optionalNested == nil)\n    \n    do {\n      \n      let state = store.state\n      \n      if let _ = state.mapIfPresent(\\.optionalNested) {\n        XCTFail()\n      }\n      \n    }\n    \n    store.commit {\n      $0.optionalNested = .init()\n    }\n    \n    do {\n      \n      let state = store.state\n      \n      if let nested = state.mapIfPresent(\\.optionalNested) {\n        XCTAssert(nested.previous == nil)\n      } else {\n        XCTFail()\n      }\n      \n    }\n    \n    store.commit {\n      $0.optionalNested!.myName = \"hello\"\n    }\n    \n    do {\n      \n      let state = store.state\n      \n      if let nested = state.mapIfPresent(\\.optionalNested) {\n        XCTAssert(nested.previous != nil)\n      } else {\n        XCTFail()\n      }\n      \n    }\n  }\n  \n}\n"
  },
  {
    "path": "Tests/VergeTinyTests/VergeTinyTests.swift",
    "content": "//\n// Copyright (c) 2021 Hiroshi Kimura(Muukii) <muukii.app@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport VergeTiny\nimport XCTest\n\nfinal class VergeTinyTests: XCTestCase {\n\n  func testDefineProperty() {\n\n    let filter = DynamicPropertyStorage()\n\n    let property = filter.defineProperty(Int.self)\n\n    XCTAssertEqual(property.value, nil)\n\n    property.value = 1\n\n    XCTAssertEqual(property.value, 1)\n  }\n\n  func testDistinct() {\n\n    let filter = DynamicPropertyStorage()\n\n    let property = filter.defineProperty(Int.self)\n\n    let exp = expectation(description: \"\")\n    exp.assertForOverFulfill = true\n    exp.expectedFulfillmentCount = 2\n\n    property.doIfChanged(1) { value in\n      XCTAssertEqual(value, 1)\n      exp.fulfill()\n    }\n\n    property.doIfChanged(1) { value in\n      XCTFail()\n    }\n\n    property.doIfChanged(2) { value in\n      XCTAssertEqual(value, 2)\n      exp.fulfill()\n    }\n\n    wait(for: [exp], timeout: 0)\n  }\n\n  func testDistinctOptional() {\n\n    let filter = DynamicPropertyStorage()\n\n    let property = filter.defineProperty(Int?.self)\n\n    let exp = expectation(description: \"\")\n    exp.assertForOverFulfill = true\n    exp.expectedFulfillmentCount = 4\n\n    property.doIfChanged(nil) { value in\n      XCTAssertEqual(value, nil)\n      exp.fulfill()\n    }\n\n    property.doIfChanged(nil) { value in\n      XCTFail()\n    }\n\n    property.doIfChanged(1) { value in\n      XCTAssertEqual(value, 1)\n      exp.fulfill()\n    }\n\n    property.doIfChanged(1) { value in\n      XCTFail()\n    }\n\n    property.doIfChanged(2) { value in\n      XCTAssertEqual(value, 2)\n      exp.fulfill()\n    }\n\n    property.doIfChanged(nil) { value in\n      XCTAssertEqual(value, nil)\n      exp.fulfill()\n    }\n\n    property.doIfChanged(nil) { value in\n      XCTFail()\n    }\n\n    wait(for: [exp], timeout: 0)\n  }\n\n  func testPerformanceCreatingProperty() {\n\n    let filter = DynamicPropertyStorage()\n    measure {\n      let _ = filter.defineProperty(Int?.self)\n    }\n  }\n\n  func testPerformanceAccessingProperty() {\n\n    let filter = DynamicPropertyStorage()\n    let property = filter.defineProperty(Int.self)\n    property.value = 1\n    measure {\n      property.value? += 1\n    }\n  }\n}\n"
  },
  {
    "path": "Verge.playground/Pages/Memo.xcplaygroundpage/Contents.swift",
    "content": "\nenum Action {\n  case increment\n  case decrement\n}\n\nclass Store<State> {\n\n  var state: State\n}\n"
  },
  {
    "path": "Verge.playground/Pages/PlainStorePattern1.xcplaygroundpage/Contents.swift",
    "content": "import UIKit\n\nclass ViewA: DemoUIView {\n  \n  // MARK: Components\n  \n  let nameLabel = UILabel()\n  \n  // MARK: State\n  \n  var name: String = \"\" {\n    didSet {\n      self.nameLabel.text = name\n    }\n  }\n         \n}\n\n//: [Next](@next)\n\n"
  },
  {
    "path": "Verge.playground/Pages/PlainStorePattern2.xcplaygroundpage/Contents.swift",
    "content": "//: [Previous](@previous)\n\nimport UIKit\n\nclass ViewA: DemoUIView {\n  \n  // MARK: Components\n  \n  let nameLabel = UILabel()\n  let ageLabel = UILabel()\n  \n  // MARK: State\n  \n  var name: String = \"\" {\n    didSet {\n      self.nameLabel.text = name\n    }\n  }\n  \n  var age: Int = 0 {\n    didSet {\n      self.ageLabel.text = name\n    }\n  }\n  \n}\n\n//: [Next](@next)\n"
  },
  {
    "path": "Verge.playground/Pages/PlainStorePattern3.xcplaygroundpage/Contents.swift",
    "content": "//: [Previous](@previous)\nimport UIKit\n\nclass ViewA: DemoUIView {\n  \n  // MARK: Components\n  \n  let nameLabel = UILabel()\n  let ageLabel = UILabel()\n  \n  // MARK: State\n  \n  struct State {\n    var name: String = \"\"\n    var age: Int = 0\n  }\n  \n  var state: State {\n    didSet {\n      self.nameLabel.text = state.name\n      self.ageLabel.text = state.age.description\n    }\n  }\n    \n}\n//: [Next](@next)\n"
  },
  {
    "path": "Verge.playground/Pages/PlainStorePattern4.xcplaygroundpage/Contents.swift",
    "content": "//: [Previous](@previous)\n\nimport Foundation\n\nimport UIKit\n\nstruct State {\n  var name: String = \"\"\n  var age: Int = 0\n}\n\nclass Store {\n  \n  // State type should be struct type to call didSet\n  var state: State {\n    didSet {\n      // notify a update to subscribers\n    }\n  }\n  \n  init(_ state: State) {\n    self.state = state\n  }\n  \n  func onDidUpdate(_ closure: @escaping (State) -> Void) {\n    // implement to notfy updates\n  }\n}\n\nclass ViewA: DemoUIView {\n    \n  // MARK: Components\n  \n  let nameLabel = UILabel()\n  let ageLabel = UILabel()\n      \n  // MARK: State\n  \n  let store: Store\n  \n  // MARK: - Initializers\n  \n  init(store: Store) {\n    self.store = store\n    \n    super.init()\n    \n    store.onDidUpdate { [weak self] state in\n      \n      guard let self = self else { return }\n      \n      self.ageLabel.text = state.age.description\n      self.nameLabel.text = state.name\n    }\n  }\n  \n  private func updateName() {\n    store.state.name = \"Muukii\"\n    // then, nameLabel updates to \"Muukii\" by store.onDidUpdate.\n  }\n  \n}\n\nclass ViewB: DemoUIView {\n  \n  // MARK: Components\n  \n  let nameLabel = UILabel()\n  let ageLabel = UILabel()\n  \n  // MARK: State\n  \n  let store: Store\n  \n  // MARK: - Initializers\n  \n  init(store: Store) {\n    self.store = store\n    \n    super.init()\n    \n    store.onDidUpdate { [weak self] state in\n      \n      guard let self = self else { return }\n      \n      self.ageLabel.text = state.age.description\n      self.nameLabel.text = state.name\n    }\n  }\n    \n}\n//: [Next](@next)\n"
  },
  {
    "path": "Verge.playground/Pages/PlainStorePattern5.xcplaygroundpage/Contents.swift",
    "content": "//: [Previous](@previous)\n\nimport Foundation\nimport UIKit\n\nstruct State {\n  var name: String = \"\"\n  var age: Int = 0\n}\n\nclass Store {\n  \n  // State type should be struct type to call didSet\n  var state: State {\n    didSet {\n      // notify a update to subscribers\n      let old = oldValue\n      let new = state\n    }\n  }\n  \n  init(_ state: State) {\n    self.state = state\n  }\n  \n  func onDidUpdate(_ closure: @escaping (_ old: State, _ new: State) -> Void) {\n    // implement to notfy updates\n  }\n}\n\nclass ViewA: DemoUIView {\n  \n  // MARK: Components\n  \n  let nameLabel = UILabel()\n  let ageLabel = UILabel()\n  \n  // MARK: State\n  \n  let store: Store\n  \n  // MARK: - Initializers\n  \n  init(store: Store) {\n    self.store = store\n    \n    super.init()\n    \n    store.onDidUpdate { [weak self] old, new in\n      \n      guard let self = self else { return }\n      \n      if old.name != new.name {\n        self.nameLabel.text = new.name\n      }\n      if old.age != new.age {\n        self.ageLabel.text = new.age.description\n      }\n    }\n  }\n  \n  private func updateName() {\n    store.state.name = \"Muukii\"\n    // then, nameLabel updates to \"Muukii\" by store.onDidUpdate.\n  }\n  \n}\n\nclass ViewB: DemoUIView {\n  \n  // MARK: Components\n  \n  let nameLabel = UILabel()\n  let ageLabel = UILabel()\n  \n  // MARK: State\n  \n  let store: Store\n  \n  // MARK: - Initializers\n  \n  init(store: Store) {\n    self.store = store\n    \n    super.init()\n    \n    store.onDidUpdate { [weak self] old, new in\n      \n      guard let self = self else { return }\n        \n      if old.name != new.name {\n        self.nameLabel.text = new.name\n      }\n      if old.age != new.age {\n        self.ageLabel.text = new.age.description\n      }\n    }\n  }\n  \n}\n\n//: [Next](@next)\n"
  },
  {
    "path": "Verge.playground/Pages/VergeStorePartern2.xcplaygroundpage/Contents.swift",
    "content": "//: [Previous](@previous)\nimport UIKit\n\nimport Verge\n\nstruct State {\n  var name: String = \"\"\n  var age: Int = 0\n}\n\nclass Store: VergeStore.Store<State, Never> {\n  \n  init() {\n    super.init(initialState: State(), logger: nil)\n  }\n  \n  func incrementAge() {\n    commit {\n      $0.age += 1\n    }\n  }\n  \n  func updateName(_ name: String) {\n    commit {\n      $0.name = name\n    }\n  }\n}\n\nclass ViewA: DemoUIView {\n    \n  let nameLabel = UILabel()\n  let ageLabel = UILabel()\n      \n  let store: Store\n  private var cancellable: VergeAnyCancellable?\n      \n  init(store: Store) {\n    self.store = store\n    \n    super.init()\n    \n    cancellable = store.sinkChanges { [weak self] (changes) in\n      self?.updateUI(changes: changes)\n    }\n    \n  }\n  \n  private func updateUI(changes: Changes<State>) {\n    \n    changes.ifChanged(\\.name) { name in\n      nameLabel.text = name\n    }\n    \n    changes.ifChanged(\\.age) { age in\n      ageLabel.text = age.description\n    }\n  }\n    \n}\n\n//: [Next](@next)\n"
  },
  {
    "path": "Verge.playground/Pages/VergeStorePattern.xcplaygroundpage/Contents.swift",
    "content": "//: [Previous](@previous)\n\nimport Foundation\n\nimport UIKit\nimport Verge\n\nstruct State {\n  var name: String = \"\"\n  var age: Int = 0\n}\n\nclass Store: VergeStore.Store<State, Never> {\n  \n  init() {\n    super.init(initialState: State(), logger: nil)\n  }\n}\n\nclass ViewA: DemoUIView {\n  \n  // MARK: Components\n  \n  let nameLabel = UILabel()\n  let ageLabel = UILabel()\n  \n  // MARK: State\n  \n  let store: Store\n  private var cancellable: VergeAnyCancellable?\n  \n  // MARK: - Initializers\n  \n  init(store: Store) {\n    self.store = store\n    \n    super.init()\n    \n    cancellable = store.sinkChanges { [weak self] (changes) in\n      \n      guard let self = self else { return }\n      \n      changes.ifChanged(\\.name) { name in\n        self.nameLabel.text = name\n      }\n      \n      changes.ifChanged(\\.age) { age in\n        self.ageLabel.text = age.description\n      }\n      \n    }\n    \n  }\n  \n  private func updateName() {\n    store.commit {\n      $0.name = \"Muukii\"\n    }\n  }\n  \n}\n//: [Next](@next)\n"
  },
  {
    "path": "Verge.playground/Sources/Wire.swift",
    "content": "import UIKit\n\nopen class DemoUIView: UIView {\n  \n  public init() {\n    super.init(frame: .zero)\n  }\n  \n  @available(*, unavailable)\n  public required init?(coder: NSCoder) {\n    fatalError(\"init(coder:) has not been implemented\")\n  }\n}\n"
  },
  {
    "path": "Verge.playground/contents.xcplayground",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='6.0' target-platform='ios' display-mode='raw'>\n    <pages>\n        <page name='PlainStorePattern1'/>\n        <page name='PlainStorePattern2'/>\n        <page name='PlainStorePattern3'/>\n        <page name='PlainStorePattern4'/>\n        <page name='PlainStorePattern5'/>\n        <page name='VergeStorePattern'/>\n        <page name='VergeStorePartern2'/>\n        <page name='Memo'/>\n    </pages>\n</playground>"
  },
  {
    "path": "mise.toml",
    "content": "[tools]\ntuist = \"4.44.3\"\n"
  },
  {
    "path": "playgrounds/.gitignore",
    "content": "!*.xcodeproj"
  },
  {
    "path": "playgrounds/PlaySwiftUI/PlaySwiftUI/Assets.xcassets/AccentColor.colorset/Contents.json",
    "content": "{\n  \"colors\" : [\n    {\n      \"idiom\" : \"universal\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "playgrounds/PlaySwiftUI/PlaySwiftUI/Assets.xcassets/AppIcon.appiconset/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"idiom\" : \"universal\",\n      \"platform\" : \"ios\",\n      \"size\" : \"1024x1024\"\n    },\n    {\n      \"appearances\" : [\n        {\n          \"appearance\" : \"luminosity\",\n          \"value\" : \"dark\"\n        }\n      ],\n      \"idiom\" : \"universal\",\n      \"platform\" : \"ios\",\n      \"size\" : \"1024x1024\"\n    },\n    {\n      \"appearances\" : [\n        {\n          \"appearance\" : \"luminosity\",\n          \"value\" : \"tinted\"\n        }\n      ],\n      \"idiom\" : \"universal\",\n      \"platform\" : \"ios\",\n      \"size\" : \"1024x1024\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "playgrounds/PlaySwiftUI/PlaySwiftUI/Assets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "playgrounds/PlaySwiftUI/PlaySwiftUI/ContentView.swift",
    "content": "//\n//  ContentView.swift\n//  PlaySwiftUI\n//\n//  Created by Muukii on 2025/02/13.\n//\n\nimport SwiftUI\nimport Verge\n\n@Tracking\nstruct ContentState {\n  \n  @Tracking\n  struct Info {\n    \n    let constant: String\n    var name: String\n    \n    init(name: String = \"Init\") {\n      self.constant = name\n      self.name = name\n    }\n  }\n\n  var info = Info()\n  \n  var count: Int = 0\n}\n\nenum AppContainer {\n  static let store = Store<_, Never>(initialState: ContentState())\n}\n\nstruct ContentView: View {\n  \n  let store = AppContainer.store\n  \n  var body: some View {\n    VStack {\n      \n      Button(\"Update Name\") {\n        store.commit {\n          $0.info.name = UUID().uuidString\n        }\n      }\n      \n      Button(\"Increment\") {\n        store.commit {\n          $0.count += 1\n        }\n      }      \n      \n      Button(\"Replace info\") {\n        store.commit {\n          $0.info = .init(name: \"Replaced\")\n        }\n      } \n      \n      StoreReader(store) { (state: ContentState) in\n        Text(state.info.name)\n        Text(state.count.description)\n      }\n      \n      StoreReader(store) { (state: ContentState) in\n        Text(state.info.constant)\n      }\n      \n      @StoreBindable var storeBindable = store\n      TextField(\"Name\", text: $storeBindable.info.name)\n      \n    }\n    .padding()\n  }\n}\n\n#Preview {\n  ContentView()\n}\n"
  },
  {
    "path": "playgrounds/PlaySwiftUI/PlaySwiftUI/PlaySwiftUIApp.swift",
    "content": "//\n//  PlaySwiftUIApp.swift\n//  PlaySwiftUI\n//\n//  Created by Muukii on 2025/02/13.\n//\n\nimport SwiftUI\n\n@main\nstruct PlaySwiftUIApp: App {\n  var body: some Scene {\n    WindowGroup {\n      ContentView()\n    }\n  }\n}\n"
  },
  {
    "path": "playgrounds/PlaySwiftUI/PlaySwiftUI/Preview Content/Preview Assets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "playgrounds/PlaySwiftUI/PlaySwiftUI/Simple.swift",
    "content": "import SwiftUI\nimport Verge\n\nprivate struct _Book: View {\n  \n  @Tracking\n  struct State {\n    var count: Int = 0\n    \n    @Tracking\n    struct NestedState {\n      var isActive: Bool = false\n      var message: String = \"Hello, Verge!\"\n    }\n    \n    var nestedState: NestedState = NestedState()\n  }\n  \n  let store = Store<_, Never>(initialState: State())\n  \n  var body: some View {\n    StoreReader(store) { state in\n      VStack {\n        Text(\"Count: \\(state.count)\")\n        Button(\"Increment\") {\n          store.commit {\n            $0.count += 1\n          }\n        }\n        Text(\"Is Active: \\(state.nestedState.isActive)\")\n        Text(\"Message: \\(state.nestedState.message)\")\n        Button(\"Toggle Active\") {\n          store.commit {\n            $0.nestedState.isActive.toggle()\n          }\n        }\n      }\n    }\n  }\n}\n\n#Preview(\"Simple\") {\n  _Book()\n}\n"
  },
  {
    "path": "playgrounds/PlaySwiftUI/PlaySwiftUI.xcodeproj/project.pbxproj",
    "content": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 77;\n\tobjects = {\n\n/* Begin PBXBuildFile section */\n\t\t4B8F11472D60E10B00FBCA80 /* Verge in Frameworks */ = {isa = PBXBuildFile; productRef = 4B8F11462D60E10B00FBCA80 /* Verge */; };\n\t\t4B8F114A2D60E13900FBCA80 /* Verge in Frameworks */ = {isa = PBXBuildFile; productRef = 4B8F11492D60E13900FBCA80 /* Verge */; };\n\t\t4B8F11632D60E1C900FBCA80 /* Verge in Frameworks */ = {isa = PBXBuildFile; productRef = 4B8F11622D60E1C900FBCA80 /* Verge */; };\n\t\t4BB8698B2D5E213200B2B2FB /* Verge in Frameworks */ = {isa = PBXBuildFile; productRef = 4BB8698A2D5E213200B2B2FB /* Verge */; };\n/* End PBXBuildFile section */\n\n/* Begin PBXFileReference section */\n\t\t4BB869782D5E205E00B2B2FB /* PlaySwiftUI.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PlaySwiftUI.app; sourceTree = BUILT_PRODUCTS_DIR; };\n/* End PBXFileReference section */\n\n/* Begin PBXFileSystemSynchronizedRootGroup section */\n\t\t4BB8697A2D5E205E00B2B2FB /* PlaySwiftUI */ = {\n\t\t\tisa = PBXFileSystemSynchronizedRootGroup;\n\t\t\tpath = PlaySwiftUI;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXFileSystemSynchronizedRootGroup section */\n\n/* Begin PBXFrameworksBuildPhase section */\n\t\t4BB869752D5E205E00B2B2FB /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t4B8F114A2D60E13900FBCA80 /* Verge in Frameworks */,\n\t\t\t\t4B8F11472D60E10B00FBCA80 /* Verge in Frameworks */,\n\t\t\t\t4B8F11632D60E1C900FBCA80 /* Verge in Frameworks */,\n\t\t\t\t4BB8698B2D5E213200B2B2FB /* Verge in Frameworks */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXFrameworksBuildPhase section */\n\n/* Begin PBXGroup section */\n\t\t4BB8696F2D5E205E00B2B2FB = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t4BB8697A2D5E205E00B2B2FB /* PlaySwiftUI */,\n\t\t\t\t4BB869792D5E205E00B2B2FB /* Products */,\n\t\t\t);\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t4BB869792D5E205E00B2B2FB /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t4BB869782D5E205E00B2B2FB /* PlaySwiftUI.app */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXGroup section */\n\n/* Begin PBXNativeTarget section */\n\t\t4BB869772D5E205E00B2B2FB /* PlaySwiftUI */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 4BB869862D5E205F00B2B2FB /* Build configuration list for PBXNativeTarget \"PlaySwiftUI\" */;\n\t\t\tbuildPhases = (\n\t\t\t\t4BB869742D5E205E00B2B2FB /* Sources */,\n\t\t\t\t4BB869752D5E205E00B2B2FB /* Frameworks */,\n\t\t\t\t4BB869762D5E205E00B2B2FB /* Resources */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tfileSystemSynchronizedGroups = (\n\t\t\t\t4BB8697A2D5E205E00B2B2FB /* PlaySwiftUI */,\n\t\t\t);\n\t\t\tname = PlaySwiftUI;\n\t\t\tpackageProductDependencies = (\n\t\t\t\t4BB8698A2D5E213200B2B2FB /* Verge */,\n\t\t\t\t4B8F11462D60E10B00FBCA80 /* Verge */,\n\t\t\t\t4B8F11492D60E13900FBCA80 /* Verge */,\n\t\t\t\t4B8F11622D60E1C900FBCA80 /* Verge */,\n\t\t\t);\n\t\t\tproductName = PlaySwiftUI;\n\t\t\tproductReference = 4BB869782D5E205E00B2B2FB /* PlaySwiftUI.app */;\n\t\t\tproductType = \"com.apple.product-type.application\";\n\t\t};\n/* End PBXNativeTarget section */\n\n/* Begin PBXProject section */\n\t\t4BB869702D5E205E00B2B2FB /* Project object */ = {\n\t\t\tisa = PBXProject;\n\t\t\tattributes = {\n\t\t\t\tBuildIndependentTargetsInParallel = 1;\n\t\t\t\tLastSwiftUpdateCheck = 1620;\n\t\t\t\tLastUpgradeCheck = 1620;\n\t\t\t\tTargetAttributes = {\n\t\t\t\t\t4BB869772D5E205E00B2B2FB = {\n\t\t\t\t\t\tCreatedOnToolsVersion = 16.2;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t\tbuildConfigurationList = 4BB869732D5E205E00B2B2FB /* Build configuration list for PBXProject \"PlaySwiftUI\" */;\n\t\t\tdevelopmentRegion = en;\n\t\t\thasScannedForEncodings = 0;\n\t\t\tknownRegions = (\n\t\t\t\ten,\n\t\t\t\tBase,\n\t\t\t);\n\t\t\tmainGroup = 4BB8696F2D5E205E00B2B2FB;\n\t\t\tminimizedProjectReferenceProxies = 1;\n\t\t\tpackageReferences = (\n\t\t\t\t4B8F11612D60E1C900FBCA80 /* XCLocalSwiftPackageReference \"../../../Verge\" */,\n\t\t\t);\n\t\t\tpreferredProjectObjectVersion = 77;\n\t\t\tproductRefGroup = 4BB869792D5E205E00B2B2FB /* Products */;\n\t\t\tprojectDirPath = \"\";\n\t\t\tprojectRoot = \"\";\n\t\t\ttargets = (\n\t\t\t\t4BB869772D5E205E00B2B2FB /* PlaySwiftUI */,\n\t\t\t);\n\t\t};\n/* End PBXProject section */\n\n/* Begin PBXResourcesBuildPhase section */\n\t\t4BB869762D5E205E00B2B2FB /* Resources */ = {\n\t\t\tisa = PBXResourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXResourcesBuildPhase section */\n\n/* Begin PBXSourcesBuildPhase section */\n\t\t4BB869742D5E205E00B2B2FB /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXSourcesBuildPhase section */\n\n/* Begin XCBuildConfiguration section */\n\t\t4BB869842D5E205F00B2B2FB /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;\n\t\t\t\tCLANG_ANALYZER_NONNULL = YES;\n\t\t\t\tCLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++20\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_WEAK = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = YES;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_LITERAL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tENABLE_TESTABILITY = YES;\n\t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17;\n\t\t\t\tGCC_DYNAMIC_NO_PIC = NO;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\t\"DEBUG=1\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 18.2;\n\t\t\t\tLOCALIZATION_PREFERS_STRING_CATALOGS = YES;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;\n\t\t\t\tMTL_FAST_MATH = YES;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\tSDKROOT = iphoneos;\n\t\t\t\tSWIFT_ACTIVE_COMPILATION_CONDITIONS = \"DEBUG $(inherited)\";\n\t\t\t\tSWIFT_OPTIMIZATION_LEVEL = \"-Onone\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t4BB869852D5E205F00B2B2FB /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;\n\t\t\t\tCLANG_ANALYZER_NONNULL = YES;\n\t\t\t\tCLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"gnu++20\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_WEAK = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_DOCUMENTATION_COMMENTS = YES;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_LITERAL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";\n\t\t\t\tENABLE_NS_ASSERTIONS = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 18.2;\n\t\t\t\tLOCALIZATION_PREFERS_STRING_CATALOGS = YES;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = NO;\n\t\t\t\tMTL_FAST_MATH = YES;\n\t\t\t\tSDKROOT = iphoneos;\n\t\t\t\tSWIFT_COMPILATION_MODE = wholemodule;\n\t\t\t\tVALIDATE_PRODUCT = YES;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t4BB869872D5E205F00B2B2FB /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;\n\t\t\t\tASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;\n\t\t\t\tCODE_SIGN_STYLE = Automatic;\n\t\t\t\tCURRENT_PROJECT_VERSION = 1;\n\t\t\t\tDEVELOPMENT_ASSET_PATHS = \"\\\"PlaySwiftUI/Preview Content\\\"\";\n\t\t\t\tENABLE_PREVIEWS = YES;\n\t\t\t\tGENERATE_INFOPLIST_FILE = YES;\n\t\t\t\tINFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;\n\t\t\t\tINFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;\n\t\t\t\tINFOPLIST_KEY_UILaunchScreen_Generation = YES;\n\t\t\t\tINFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = \"UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight\";\n\t\t\t\tINFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = \"UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight\";\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"@executable_path/Frameworks\",\n\t\t\t\t);\n\t\t\t\tMARKETING_VERSION = 1.0;\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = app.muukii.PlaySwiftUI;\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t\tSWIFT_EMIT_LOC_STRINGS = YES;\n\t\t\t\tSWIFT_VERSION = 5.0;\n\t\t\t\tTARGETED_DEVICE_FAMILY = \"1,2\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t4BB869882D5E205F00B2B2FB /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;\n\t\t\t\tASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;\n\t\t\t\tCODE_SIGN_STYLE = Automatic;\n\t\t\t\tCURRENT_PROJECT_VERSION = 1;\n\t\t\t\tDEVELOPMENT_ASSET_PATHS = \"\\\"PlaySwiftUI/Preview Content\\\"\";\n\t\t\t\tENABLE_PREVIEWS = YES;\n\t\t\t\tGENERATE_INFOPLIST_FILE = YES;\n\t\t\t\tINFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;\n\t\t\t\tINFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;\n\t\t\t\tINFOPLIST_KEY_UILaunchScreen_Generation = YES;\n\t\t\t\tINFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = \"UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight\";\n\t\t\t\tINFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = \"UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight\";\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"@executable_path/Frameworks\",\n\t\t\t\t);\n\t\t\t\tMARKETING_VERSION = 1.0;\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = app.muukii.PlaySwiftUI;\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t\tSWIFT_EMIT_LOC_STRINGS = YES;\n\t\t\t\tSWIFT_VERSION = 5.0;\n\t\t\t\tTARGETED_DEVICE_FAMILY = \"1,2\";\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n/* End XCBuildConfiguration section */\n\n/* Begin XCConfigurationList section */\n\t\t4BB869732D5E205E00B2B2FB /* Build configuration list for PBXProject \"PlaySwiftUI\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t4BB869842D5E205F00B2B2FB /* Debug */,\n\t\t\t\t4BB869852D5E205F00B2B2FB /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t4BB869862D5E205F00B2B2FB /* Build configuration list for PBXNativeTarget \"PlaySwiftUI\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t4BB869872D5E205F00B2B2FB /* Debug */,\n\t\t\t\t4BB869882D5E205F00B2B2FB /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n/* End XCConfigurationList section */\n\n/* Begin XCLocalSwiftPackageReference section */\n\t\t4B8F11612D60E1C900FBCA80 /* XCLocalSwiftPackageReference \"../../../Verge\" */ = {\n\t\t\tisa = XCLocalSwiftPackageReference;\n\t\t\trelativePath = ../../../Verge;\n\t\t};\n/* End XCLocalSwiftPackageReference section */\n\n/* Begin XCSwiftPackageProductDependency section */\n\t\t4B8F11462D60E10B00FBCA80 /* Verge */ = {\n\t\t\tisa = XCSwiftPackageProductDependency;\n\t\t\tproductName = Verge;\n\t\t};\n\t\t4B8F11492D60E13900FBCA80 /* Verge */ = {\n\t\t\tisa = XCSwiftPackageProductDependency;\n\t\t\tproductName = Verge;\n\t\t};\n\t\t4B8F11622D60E1C900FBCA80 /* Verge */ = {\n\t\t\tisa = XCSwiftPackageProductDependency;\n\t\t\tproductName = Verge;\n\t\t};\n\t\t4BB8698A2D5E213200B2B2FB /* Verge */ = {\n\t\t\tisa = XCSwiftPackageProductDependency;\n\t\t\tproductName = Verge;\n\t\t};\n/* End XCSwiftPackageProductDependency section */\n\t};\n\trootObject = 4BB869702D5E205E00B2B2FB /* Project object */;\n}\n"
  },
  {
    "path": "playgrounds/PlaySwiftUI/PlaySwiftUI.xcodeproj/project.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "playgrounds/PlaySwiftUI/PlaySwiftUI.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved",
    "content": "{\n  \"originHash\" : \"91b2bd4d42ac7a19338699d5fcae987277fc6461718b80e90459a6235bafabb2\",\n  \"pins\" : [\n    {\n      \"identity\" : \"normalization\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/Normalization\",\n      \"state\" : {\n        \"revision\" : \"6e7cb1ddeda4d0f1d2fbf8ca6d25ecd8ed6ba917\",\n        \"version\" : \"1.1.0\"\n      }\n    },\n    {\n      \"identity\" : \"rxswift\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/ReactiveX/RxSwift.git\",\n      \"state\" : {\n        \"revision\" : \"c7c7d2cf50a3211fe2843f76869c698e4e417930\",\n        \"version\" : \"6.8.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-atomics\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/apple/swift-atomics.git\",\n      \"state\" : {\n        \"revision\" : \"cd142fd2f64be2100422d658e7411e39489da985\",\n        \"version\" : \"1.2.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-collections\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/apple/swift-collections\",\n      \"state\" : {\n        \"revision\" : \"671108c96644956dddcd89dd59c203dcdb36cec7\",\n        \"version\" : \"1.1.4\"\n      }\n    },\n    {\n      \"identity\" : \"swift-concurrency-task-manager\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/swift-concurrency-task-manager\",\n      \"state\" : {\n        \"revision\" : \"340cf14e0282977deeeb436605d1810ce4f4fbc9\",\n        \"version\" : \"1.4.0\"\n      }\n    },\n    {\n      \"identity\" : \"swift-macro-state-struct\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/swift-macro-state-struct\",\n      \"state\" : {\n        \"branch\" : \"main\",\n        \"revision\" : \"88e3937abd26b76bafe9027938538966457f156f\"\n      }\n    },\n    {\n      \"identity\" : \"swift-syntax\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/apple/swift-syntax.git\",\n      \"state\" : {\n        \"revision\" : \"0687f71944021d616d34d922343dcef086855920\",\n        \"version\" : \"600.0.1\"\n      }\n    },\n    {\n      \"identity\" : \"typedcomparator\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/TypedComparator\",\n      \"state\" : {\n        \"revision\" : \"337ce0e573e7637ddd29392cb88c3b852f042c8e\",\n        \"version\" : \"1.0.0\"\n      }\n    },\n    {\n      \"identity\" : \"typedidentifier\",\n      \"kind\" : \"remoteSourceControl\",\n      \"location\" : \"https://github.com/VergeGroup/TypedIdentifier\",\n      \"state\" : {\n        \"revision\" : \"284340409ba47858a1b3c353dcef9c21303953db\",\n        \"version\" : \"2.0.3\"\n      }\n    }\n  ],\n  \"version\" : 3\n}\n"
  }
]