adoor 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +2 -2
  3. package/dist/adoor.mjs +105 -84
  4. package/native/LICENSE +662 -0
  5. package/native/README.md +12 -0
  6. package/native/darwin/ADoorService.app/Contents/Info.plist +57 -0
  7. package/native/darwin/ADoorService.app/Contents/MacOS/ADoorService +0 -0
  8. package/native/darwin/ADoorService.app/Contents/PkgInfo +1 -0
  9. package/native/darwin/ADoorService.app/Contents/_CodeSignature/CodeResources +123 -0
  10. package/native/darwin/ADoorService.app/Contents/embedded.provisionprofile +0 -0
  11. package/native/source/Package.swift +6 -0
  12. package/native/source/sdk/LICENSE +21 -0
  13. package/native/source/sdk/Package.swift +14 -0
  14. package/native/source/sdk/Sources/ADoor/AdoorClient.swift +270 -0
  15. package/native/source/sdk/Sources/ADoor/AdoorError.swift +60 -0
  16. package/native/source/sdk/Sources/ADoor/Changes.swift +202 -0
  17. package/native/source/sdk/Sources/ADoor/DesktopSessionState.swift +73 -0
  18. package/native/source/sdk/Sources/ADoor/DeviceFlow.swift +70 -0
  19. package/native/source/sdk/Sources/ADoor/FolderCatalog.swift +49 -0
  20. package/native/source/sdk/Sources/ADoor/JSONValue.swift +70 -0
  21. package/native/source/sdk/Sources/ADoor/LocalStore.swift +474 -0
  22. package/native/source/sdk/Sources/ADoor/Models.swift +146 -0
  23. package/native/source/sdk/Sources/ADoor/MountModel.swift +896 -0
  24. package/native/source/sdk/Sources/ADoor/OAuth.swift +225 -0
  25. package/native/source/sdk/Sources/ADoor/Provider.swift +211 -0
  26. package/native/source/sdk/Sources/ADoor/Storage.swift +41 -0
  27. package/native/source/sdk/Sources/ADoor/SyncTree.swift +501 -0
  28. package/native/source/sdk/Sources/ADoor/Trash.swift +283 -0
  29. package/native/source/sdk/Tests/ADoorTests/ADoorTests.swift +182 -0
  30. package/native/source/sdk/Tests/ADoorTests/DesktopSessionStateTests.swift +46 -0
  31. package/native/source/sdk/Tests/ADoorTests/MountTests.swift +560 -0
  32. package/native/source/sdk/Tests/ADoorTests/RegressionTests.swift +360 -0
  33. package/native/source/service/DesktopSession.swift +241 -0
  34. package/native/source/service/DeviceClient.swift +53 -0
  35. package/native/source/service/Domains.swift +182 -0
  36. package/native/source/service/FolderRefresh.swift +37 -0
  37. package/native/source/service/KeychainStore.swift +74 -0
  38. package/native/source/service/LocalSessionSocket.swift +142 -0
  39. package/native/source/service/ServiceMain.swift +14 -0
  40. package/native/source/service/ServiceMounts.swift +34 -0
  41. package/package.json +12 -3
@@ -0,0 +1,57 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>BuildMachineOSBuild</key>
6
+ <string>26B131</string>
7
+ <key>CFBundleDevelopmentRegion</key>
8
+ <string>en</string>
9
+ <key>CFBundleDisplayName</key>
10
+ <string>ADoor service</string>
11
+ <key>CFBundleExecutable</key>
12
+ <string>ADoorService</string>
13
+ <key>CFBundleIdentifier</key>
14
+ <string>com.halmoslabs.adoor.mac</string>
15
+ <key>CFBundleInfoDictionaryVersion</key>
16
+ <string>6.0</string>
17
+ <key>CFBundleName</key>
18
+ <string>ADoorService</string>
19
+ <key>CFBundlePackageType</key>
20
+ <string>APPL</string>
21
+ <key>CFBundleShortVersionString</key>
22
+ <string>1.0.0</string>
23
+ <key>CFBundleSupportedPlatforms</key>
24
+ <array>
25
+ <string>MacOSX</string>
26
+ </array>
27
+ <key>CFBundleVersion</key>
28
+ <string>1</string>
29
+ <key>DTCompiler</key>
30
+ <string>com.apple.compilers.llvm.clang.1_0</string>
31
+ <key>DTPlatformBuild</key>
32
+ <string>26B118</string>
33
+ <key>DTPlatformName</key>
34
+ <string>macosx</string>
35
+ <key>DTPlatformVersion</key>
36
+ <string>27.2</string>
37
+ <key>DTSDKBuild</key>
38
+ <string>26B118</string>
39
+ <key>DTSDKName</key>
40
+ <string>macosx27.2</string>
41
+ <key>DTXcode</key>
42
+ <string>2720</string>
43
+ <key>DTXcodeBuild</key>
44
+ <string>27B52</string>
45
+ <key>ITSAppUsesNonExemptEncryption</key>
46
+ <false/>
47
+ <key>LSBackgroundOnly</key>
48
+ <true/>
49
+ <key>LSMinimumSystemVersion</key>
50
+ <string>14.0</string>
51
+ <key>NSAppTransportSecurity</key>
52
+ <dict>
53
+ <key>NSAllowsLocalNetworking</key>
54
+ <true/>
55
+ </dict>
56
+ </dict>
57
+ </plist>
@@ -0,0 +1 @@
1
+ APPL????
@@ -0,0 +1,123 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>files</key>
6
+ <dict/>
7
+ <key>files2</key>
8
+ <dict>
9
+ <key>embedded.provisionprofile</key>
10
+ <dict>
11
+ <key>hash2</key>
12
+ <data>
13
+ TYsyUvft61WHER3MCYMC+8CTT1lNJZTwsdZG/0xTmtQ=
14
+ </data>
15
+ </dict>
16
+ </dict>
17
+ <key>rules</key>
18
+ <dict>
19
+ <key>^Resources/</key>
20
+ <true/>
21
+ <key>^Resources/.*\.lproj/</key>
22
+ <dict>
23
+ <key>optional</key>
24
+ <true/>
25
+ <key>weight</key>
26
+ <real>1000</real>
27
+ </dict>
28
+ <key>^Resources/.*\.lproj/locversion.plist$</key>
29
+ <dict>
30
+ <key>omit</key>
31
+ <true/>
32
+ <key>weight</key>
33
+ <real>1100</real>
34
+ </dict>
35
+ <key>^Resources/Base\.lproj/</key>
36
+ <dict>
37
+ <key>weight</key>
38
+ <real>1010</real>
39
+ </dict>
40
+ <key>^version.plist$</key>
41
+ <true/>
42
+ </dict>
43
+ <key>rules2</key>
44
+ <dict>
45
+ <key>.*\.dSYM($|/)</key>
46
+ <dict>
47
+ <key>weight</key>
48
+ <real>11</real>
49
+ </dict>
50
+ <key>^(.*/)?\.DS_Store$</key>
51
+ <dict>
52
+ <key>omit</key>
53
+ <true/>
54
+ <key>weight</key>
55
+ <real>2000</real>
56
+ </dict>
57
+ <key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
58
+ <dict>
59
+ <key>nested</key>
60
+ <true/>
61
+ <key>weight</key>
62
+ <real>10</real>
63
+ </dict>
64
+ <key>^.*</key>
65
+ <true/>
66
+ <key>^Info\.plist$</key>
67
+ <dict>
68
+ <key>omit</key>
69
+ <true/>
70
+ <key>weight</key>
71
+ <real>20</real>
72
+ </dict>
73
+ <key>^PkgInfo$</key>
74
+ <dict>
75
+ <key>omit</key>
76
+ <true/>
77
+ <key>weight</key>
78
+ <real>20</real>
79
+ </dict>
80
+ <key>^Resources/</key>
81
+ <dict>
82
+ <key>weight</key>
83
+ <real>20</real>
84
+ </dict>
85
+ <key>^Resources/.*\.lproj/</key>
86
+ <dict>
87
+ <key>optional</key>
88
+ <true/>
89
+ <key>weight</key>
90
+ <real>1000</real>
91
+ </dict>
92
+ <key>^Resources/.*\.lproj/locversion.plist$</key>
93
+ <dict>
94
+ <key>omit</key>
95
+ <true/>
96
+ <key>weight</key>
97
+ <real>1100</real>
98
+ </dict>
99
+ <key>^Resources/Base\.lproj/</key>
100
+ <dict>
101
+ <key>weight</key>
102
+ <real>1010</real>
103
+ </dict>
104
+ <key>^[^/]+$</key>
105
+ <dict>
106
+ <key>nested</key>
107
+ <true/>
108
+ <key>weight</key>
109
+ <real>10</real>
110
+ </dict>
111
+ <key>^embedded\.provisionprofile$</key>
112
+ <dict>
113
+ <key>weight</key>
114
+ <real>20</real>
115
+ </dict>
116
+ <key>^version\.plist$</key>
117
+ <dict>
118
+ <key>weight</key>
119
+ <real>20</real>
120
+ </dict>
121
+ </dict>
122
+ </dict>
123
+ </plist>
@@ -0,0 +1,6 @@
1
+ // swift-tools-version:5.9
2
+ import PackageDescription
3
+ let package = Package(name: "ADoorService", platforms: [.macOS(.v14)],
4
+ dependencies: [.package(name: "ADoor", path: "sdk")], targets: [
5
+ .executableTarget(name: "ADoorService", dependencies: [.product(name: "ADoor", package: "ADoor")], path: "service")
6
+ ])
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Halmos Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,14 @@
1
+ // swift-tools-version:5.9
2
+ import PackageDescription
3
+
4
+ let package = Package(
5
+ name: "ADoor",
6
+ platforms: [.iOS(.v16), .macOS(.v13), .tvOS(.v16), .watchOS(.v9), .visionOS(.v1)],
7
+ products: [
8
+ .library(name: "ADoor", targets: ["ADoor"])
9
+ ],
10
+ targets: [
11
+ .target(name: "ADoor", path: "Sources/ADoor"),
12
+ .testTarget(name: "ADoorTests", dependencies: ["ADoor"], path: "Tests/ADoorTests")
13
+ ]
14
+ )
@@ -0,0 +1,270 @@
1
+ import Foundation
2
+ #if canImport(FoundationNetworking)
3
+ import FoundationNetworking
4
+ #endif
5
+
6
+ /// Stable, non-secret identity from the app's authenticated session, independent of token rotation.
7
+ public struct LocalIdentity: Equatable, Sendable {
8
+ public let accountId: String
9
+ public let workspaceId: String
10
+ public let spaceId: String
11
+ public init(accountId: String, workspaceId: String, spaceId: String) {
12
+ self.accountId = accountId; self.workspaceId = workspaceId; self.spaceId = spaceId
13
+ }
14
+ }
15
+
16
+ /// Where the bearer token comes from: a fixed access key, or a provider such as `TokenProvider` that refreshes.
17
+ public enum TokenSource: Sendable {
18
+ case fixed(String)
19
+ case provider(@Sendable () async throws -> String)
20
+
21
+ func value() async throws -> String {
22
+ switch self {
23
+ case .fixed(let token): return token
24
+ case .provider(let provider): return try await provider()
25
+ }
26
+ }
27
+ }
28
+
29
+ /// Credentialed requests never follow a redirect to another origin.
30
+ final class RedirectBlocker: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
31
+ func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
32
+ completionHandler(nil)
33
+ }
34
+ }
35
+
36
+ /// Everything the server exposes is a named operation on one endpoint; these are the typed conveniences over it.
37
+ public final class AdoorClient: @unchecked Sendable {
38
+ public static let version = "0.1.2"
39
+ /// The ADoor origin, or your own backend that forwards to it. Browser-style cross-origin access is not
40
+ /// available; native apps call ADoor directly.
41
+ public let url: URL
42
+ private let identitySource: (@Sendable () -> LocalIdentity?)?
43
+ let boundIdentity: LocalIdentity?
44
+ let token: TokenSource
45
+ let session: URLSession
46
+ let headers: [String: String]
47
+ let redirects = RedirectBlocker()
48
+
49
+ public init(url: URL, token: TokenSource, session: URLSession = .shared, headers: [String: String] = [:], identity: (@Sendable () -> LocalIdentity?)? = nil) {
50
+ self.identitySource = identity
51
+ self.boundIdentity = identity?()
52
+ self.url = url
53
+ self.token = token
54
+ self.session = session
55
+ self.headers = headers
56
+ }
57
+
58
+ public convenience init(url: URL, accessKey: String, session: URLSession = .shared, identity: (@Sendable () -> LocalIdentity?)? = nil) {
59
+ self.init(url: url, token: .fixed(accessKey), session: session, identity: identity)
60
+ }
61
+
62
+ /// No network request: the app must update this provider before changing credentials or selected context.
63
+ public func localIdentity() throws -> LocalIdentity? {
64
+ guard let boundIdentity else { return nil }
65
+ guard let current = identitySource?(), current == boundIdentity,
66
+ ![current.accountId, current.workspaceId, current.spaceId].contains(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else {
67
+ throw AdoorError(code: "IDENTITY_CHANGED", message: "The app session changed. Use a new client and local store for this identity.", status: 401)
68
+ }
69
+ return boundIdentity
70
+ }
71
+
72
+ func makeRequest(path: String, method: String = "GET", body: Data? = nil, contentType: String? = nil, accept: String = "application/json", extra: [String: String] = [:]) async throws -> URLRequest {
73
+ _ = try localIdentity()
74
+ var request = URLRequest(url: url.appendingPathComponent(path))
75
+ request.httpMethod = method
76
+ request.httpBody = body
77
+ request.setValue("Bearer \(try await token.value())", forHTTPHeaderField: "Authorization")
78
+ request.setValue("swift/\(AdoorClient.version)", forHTTPHeaderField: "Adoor-Client-Version")
79
+ _ = try localIdentity()
80
+ request.setValue(accept, forHTTPHeaderField: "Accept")
81
+ if let contentType { request.setValue(contentType, forHTTPHeaderField: "Content-Type") }
82
+ for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) }
83
+ for (name, value) in extra { request.setValue(value, forHTTPHeaderField: name) }
84
+ return request
85
+ }
86
+
87
+ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
88
+ _ = try localIdentity()
89
+ let received: (Data, URLResponse)
90
+ do { received = try await session.data(for: request, delegate: redirects) }
91
+ catch { throw AdoorError.network(error) }
92
+ _ = try localIdentity()
93
+ let (data, response) = received
94
+ guard let http = response as? HTTPURLResponse else { throw AdoorError(code: "HTTP_INVALID", message: "The server returned no HTTP response.", status: 0) }
95
+ guard (200..<300).contains(http.statusCode) else { throw AdoorError.from(response: http, data: data) }
96
+ return (data, http)
97
+ }
98
+
99
+ /// Call any operation by name with a JSON input; the result is the operation's JSON output.
100
+ public func call(_ operation: String, input: JSONValue = .object([:])) async throws -> (JSONValue, Data) {
101
+ guard operation.range(of: #"^[a-z]+\.[a-z_]+$"#, options: .regularExpression) != nil else {
102
+ throw AdoorError(code: "INVALID_OPERATION", message: "Operation names look like data.query.", status: 400)
103
+ }
104
+ let request = try await makeRequest(path: "api/operations/\(operation)", method: "POST", body: try JSON.encode(input), contentType: "application/json")
105
+ let reads = ["workspaces.list", "spaces.list", "fs.stat", "fs.read", "fs.range",
106
+ "fs.list", "fs.list_deleted", "changes.head", "changes.list"]
107
+ let retryReads = reads.contains(operation)
108
+ for attempt in 0...3 {
109
+ do {
110
+ let (data, _) = try await send(request)
111
+ return (try JSON.decode(JSONValue.self, from: data), data)
112
+ } catch let error as AdoorError where attempt < 3 && error.status == 429 &&
113
+ (retryReads || (operation.hasPrefix("fs.") && error.code == "RATE_LIMITED")) {
114
+ let delay = max(1, error.retryAfter ?? pow(2, Double(attempt)))
115
+ guard delay <= 65 else { throw error }
116
+ try await Task.sleep(for: .seconds(delay + Double.random(in: 0...0.25)))
117
+ }
118
+ }
119
+ throw CancellationError()
120
+ }
121
+
122
+ public func call<T: Decodable>(_ operation: String, input: JSONValue = .object([:]), as type: T.Type) async throws -> T {
123
+ let (_, data) = try await call(operation, input: input)
124
+ return try JSON.decode(type, from: data)
125
+ }
126
+
127
+ func sql(_ operation: String, _ text: String, params: [JSONValue], spaceId: String?, idempotencyKey: String?, expectRowCount: Int?) async throws -> SqlResult {
128
+ var input: [String: JSONValue] = ["sql": .string(text)]
129
+ if !params.isEmpty { input["params"] = .array(params) }
130
+ if let spaceId { input["spaceId"] = .string(spaceId) }
131
+ if let idempotencyKey { input["idempotencyKey"] = .string(idempotencyKey) }
132
+ if let expectRowCount { input["expectRowCount"] = .number(Double(expectRowCount)) }
133
+ let (json, data) = try await call(operation, input: .object(input))
134
+ return try SqlResult(json: json, data: data)
135
+ }
136
+
137
+ /// One or more SELECT statements with parameters.
138
+ public func query(_ text: String, params: [JSONValue] = [], spaceId: String? = nil) async throws -> SqlResult {
139
+ try await sql("data.query", text, params: params, spaceId: spaceId, idempotencyKey: nil, expectRowCount: nil)
140
+ }
141
+
142
+ /// Send `idempotencyKey` on INSERT, INSERT...SELECT, and upsert, and reuse that key on retry.
143
+ /// UPDATE, DELETE, and SELECT may omit it. A different statement with that key is a 409.
144
+ /// `expectRowCount` makes one mutation conditional. A different count is CONFLICT and rolls back.
145
+ public func execute(_ text: String, params: [JSONValue] = [], spaceId: String? = nil, idempotencyKey: String? = nil, expectRowCount: Int? = nil) async throws -> SqlResult {
146
+ try await sql("data.execute", text, params: params, spaceId: spaceId, idempotencyKey: idempotencyKey, expectRowCount: expectRowCount)
147
+ }
148
+
149
+ public func describe() async throws -> Description {
150
+ try await call("store.describe", as: Description.self)
151
+ }
152
+
153
+ /// The current committed cursor. Capture it before loading a snapshot, then subscribe from it.
154
+ public func changesHead() async throws -> String {
155
+ struct Head: Decodable { let cursor: String }
156
+ return try await call("changes.head", as: Head.self).cursor
157
+ }
158
+
159
+ public func changes(after: String? = nil, limit: Int? = nil) async throws -> ChangePage {
160
+ var input: [String: JSONValue] = [:]
161
+ if let after { input["after"] = .string(after) }
162
+ if let limit { input["limit"] = .number(Double(limit)) }
163
+ return try await call("changes.list", input: .object(input), as: ChangePage.self)
164
+ }
165
+
166
+ private func named(_ operation: String, _ fields: [String: JSONValue]) async throws -> JSONValue {
167
+ let (json, _) = try await call(operation, input: .object(fields))
168
+ return json
169
+ }
170
+
171
+ private func fields(_ pairs: [String: JSONValue?]) -> [String: JSONValue] {
172
+ var result: [String: JSONValue] = [:]
173
+ for (key, value) in pairs { if let value { result[key] = value } }
174
+ return result
175
+ }
176
+
177
+ /// Read one inode. A missing name and a hidden name are both not found.
178
+ public func fsStat(spaceId: String, path: String? = nil, inodeId: String? = nil) async throws -> JSONValue {
179
+ try await named("fs.stat", fields(["spaceId": .string(spaceId), "path": path.map(JSONValue.string), "inodeId": inodeId.map(JSONValue.string)]))
180
+ }
181
+
182
+ /// One directory page. Pass conflicts to list this connection's conflict copies.
183
+ public func fsList(
184
+ spaceId: String, path: String? = nil, inodeId: String? = nil,
185
+ limit: Int? = nil, cursor: String? = nil, conflicts: Bool? = nil
186
+ ) async throws -> JSONValue {
187
+ try await named("fs.list", fields([
188
+ "spaceId": .string(spaceId), "path": path.map(JSONValue.string), "inodeId": inodeId.map(JSONValue.string),
189
+ "limit": limit.map { .number(Double($0)) }, "cursor": cursor.map(JSONValue.string),
190
+ "conflicts": conflicts.map { .bool($0) }
191
+ ]))
192
+ }
193
+
194
+ /// Read an inline file.
195
+ public func fsRead(spaceId: String, path: String? = nil, inodeId: String? = nil) async throws -> JSONValue {
196
+ try await named("fs.read", fields(["spaceId": .string(spaceId), "path": path.map(JSONValue.string), "inodeId": inodeId.map(JSONValue.string)]))
197
+ }
198
+
199
+ /// Create or replace an inline file of at most 32 KiB. A stale text file merges. Pass find and replace to change one occurrence.
200
+ public func fsWrite(
201
+ spaceId: String, body: String? = nil, path: String? = nil, name: String? = nil,
202
+ inodeId: String? = nil, expectedGeneration: Int? = nil, find: String? = nil, replace: String? = nil,
203
+ idempotencyKey: String? = nil
204
+ ) async throws -> JSONValue {
205
+ try await named("fs.write", fields([
206
+ "spaceId": .string(spaceId), "body": body.map(JSONValue.string), "path": path.map(JSONValue.string),
207
+ "name": name.map(JSONValue.string), "inodeId": inodeId.map(JSONValue.string),
208
+ "expectedGeneration": expectedGeneration.map { .number(Double($0)) },
209
+ "find": find.map(JSONValue.string), "replace": replace.map(JSONValue.string),
210
+ "idempotencyKey": idempotencyKey.map(JSONValue.string)
211
+ ]))
212
+ }
213
+
214
+ /// Commit a sliced file after its objects are stored. A stale text file merges. Binary bytes are refused.
215
+ public func fsCommit(
216
+ spaceId: String, contentSha: String, size: Int, manifestHex: String, hashes: [String],
217
+ path: String? = nil, name: String? = nil, inodeId: String? = nil,
218
+ expectedGeneration: Int? = nil, oldHashes: [String]? = nil
219
+ ) async throws -> JSONValue {
220
+ try await named("fs.commit", fields([
221
+ "spaceId": .string(spaceId), "contentSha": .string(contentSha), "size": .number(Double(size)),
222
+ "manifestHex": .string(manifestHex), "hashes": .array(hashes.map(JSONValue.string)),
223
+ "path": path.map(JSONValue.string), "name": name.map(JSONValue.string), "inodeId": inodeId.map(JSONValue.string),
224
+ "expectedGeneration": expectedGeneration.map { .number(Double($0)) },
225
+ "oldHashes": oldHashes.map { .array($0.map(JSONValue.string)) }
226
+ ]))
227
+ }
228
+
229
+ /// Create a directory. `name` is one component.
230
+ public func fsMkdir(spaceId: String, name: String, path: String? = nil, inodeId: String? = nil) async throws -> JSONValue {
231
+ try await named("fs.mkdir", fields([
232
+ "spaceId": .string(spaceId), "name": .string(name), "path": path.map(JSONValue.string), "inodeId": inodeId.map(JSONValue.string)
233
+ ]))
234
+ }
235
+
236
+ /// Rename an inode inside one space.
237
+ public func fsRename(spaceId: String, inodeId: String, name: String, expectedGeneration: Int, parentId: String? = nil) async throws -> JSONValue {
238
+ try await named("fs.rename", fields([
239
+ "spaceId": .string(spaceId), "inodeId": .string(inodeId), "name": .string(name),
240
+ "expectedGeneration": .number(Double(expectedGeneration)), "parentId": parentId.map(JSONValue.string)
241
+ ]))
242
+ }
243
+
244
+ /// Remove a file or an empty directory.
245
+ public func fsRemove(spaceId: String, inodeId: String, expectedGeneration: Int) async throws -> JSONValue {
246
+ try await named("fs.remove", fields([
247
+ "spaceId": .string(spaceId), "inodeId": .string(inodeId), "expectedGeneration": .number(Double(expectedGeneration))
248
+ ]))
249
+ }
250
+
251
+ /// Reparent an inode. A destination that would add an action writes nothing.
252
+ public func fsMove(inodeId: String, toSpaceId: String, toParentId: String, expectedGeneration: Int, name: String? = nil) async throws -> JSONValue {
253
+ try await named("fs.move", fields([
254
+ "inodeId": .string(inodeId), "toSpaceId": .string(toSpaceId), "toParentId": .string(toParentId),
255
+ "expectedGeneration": .number(Double(expectedGeneration)), "name": name.map(JSONValue.string)
256
+ ]))
257
+ }
258
+
259
+ /// Diff two versions of one file by content id or history event id.
260
+ public func fsDiff(
261
+ spaceId: String, inodeId: String, leftContentId: String? = nil, rightContentId: String? = nil,
262
+ leftEventId: String? = nil, rightEventId: String? = nil
263
+ ) async throws -> JSONValue {
264
+ try await named("fs.diff", fields([
265
+ "spaceId": .string(spaceId), "inodeId": .string(inodeId),
266
+ "leftContentId": leftContentId.map(JSONValue.string), "rightContentId": rightContentId.map(JSONValue.string),
267
+ "leftEventId": leftEventId.map(JSONValue.string), "rightEventId": rightEventId.map(JSONValue.string)
268
+ ]))
269
+ }
270
+ }
@@ -0,0 +1,60 @@
1
+ import Foundation
2
+ #if canImport(FoundationNetworking)
3
+ import FoundationNetworking
4
+ #endif
5
+
6
+ /// The server's error envelope as a typed error, plus transport failures with status 0.
7
+ public struct AdoorError: Error, Sendable, CustomStringConvertible {
8
+ public let code: String
9
+ public let message: String
10
+ /// HTTP status, or 0 when the request never reached the server.
11
+ public let status: Int
12
+ public let details: JSONValue?
13
+ public let serverRetryable: Bool
14
+ public let retryAfter: Double?
15
+ public let docUrl: String?
16
+ public let requestId: String?
17
+
18
+ public init(
19
+ code: String, message: String, status: Int, details: JSONValue? = nil,
20
+ serverRetryable: Bool = false, retryAfter: Double? = nil, docUrl: String? = nil, requestId: String? = nil
21
+ ) {
22
+ self.code = code
23
+ self.message = message
24
+ self.status = status
25
+ self.details = details
26
+ self.serverRetryable = serverRetryable
27
+ self.retryAfter = retryAfter
28
+ self.docUrl = docUrl
29
+ self.requestId = requestId
30
+ }
31
+
32
+ /// A retry with the same idempotency key is safe and may succeed later.
33
+ public var retryable: Bool { serverRetryable || status == 0 || status >= 500 || status == 429 }
34
+
35
+ /// The caller's authority ended or changed; a retry needs a new credential or a fresh read.
36
+ public var authority: Bool {
37
+ status == 401 || status == 403 || ["UNAUTHORIZED", "FORBIDDEN", "PERMISSIONS_CHANGED", "CONNECTION_CHANGED", "WORKSPACE_CHANGED", "FIELD_ACCESS_DENIED"].contains(code)
38
+ }
39
+
40
+ public var description: String { "\(code) (\(status)): \(message)" }
41
+
42
+ static func network(_ error: Error) -> AdoorError {
43
+ AdoorError(code: "NETWORK", message: error.localizedDescription, status: 0)
44
+ }
45
+
46
+ /// Build the typed error from a failed response; non-JSON bodies become a transport error with the HTTP status.
47
+ static func from(response: HTTPURLResponse, data: Data) -> AdoorError {
48
+ let headerDelay = response.value(forHTTPHeaderField: "Retry-After").flatMap(Double.init)
49
+ if let body = try? JSON.decode(JSONValue.self, from: data), let error = body["error"], let code = error["code"]?.stringValue {
50
+ let seconds = error["retry_after"]?.doubleValue ?? error["retryAfter"]?.doubleValue ?? headerDelay
51
+ return AdoorError(
52
+ code: code, message: error["message"]?.stringValue ?? code, status: response.statusCode,
53
+ details: error["details"], serverRetryable: error["retryable"]?.boolValue == true,
54
+ retryAfter: seconds, docUrl: error["doc_url"]?.stringValue, requestId: error["request_id"]?.stringValue
55
+ )
56
+ }
57
+ return AdoorError(code: "HTTP_\(response.statusCode)", message: "The request failed with HTTP \(response.statusCode).",
58
+ status: response.statusCode, retryAfter: headerDelay)
59
+ }
60
+ }