Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Attachments.swift

261 lines9.8 KB

1import Foundation
2​
3public enum ImageAttachmentError: LocalizedError, Equatable, Sendable {
4 case empty
5 case tooLarge(actualBytes: Int, maximumBytes: Int)
6 case invalidName
7 case invalidMIMEType
8​
9 public var errorDescription: String? {
10 switch self {
11 case .empty: "The selected image is empty."
12 case let .tooLarge(actualBytes, maximumBytes):
13 "The image is \(actualBytes) bytes. T3 accepts up to \(maximumBytes) bytes."
14 case .invalidName: "The image needs a valid file name."
15 case .invalidMIMEType: "The selected file is not a supported image."
16 }
17 }
19​
20public enum FileAttachmentError: LocalizedError, Equatable, Sendable {
21 case empty
22 case tooLarge(actualBytes: Int, maximumBytes: Int)
23 case invalidName
24 case invalidMIMEType
25 case invalidFileURL
26 case unsupported
27 case tooMany(maximum: Int)
28​
29 public var errorDescription: String? {
30 switch self {
31 case .empty: "The selected file is empty."
32 case let .tooLarge(actualBytes, maximumBytes):
33 "The file is \(actualBytes) bytes. T3 accepts up to \(maximumBytes) bytes."
34 case .invalidName: "The file needs a valid name."
35 case .invalidMIMEType: "The file needs a valid MIME type."
36 case .invalidFileURL: "The attachment file is no longer available."
37 case .unsupported: "This environment does not support file attachments."
38 case let .tooMany(maximum): "You can attach up to \(maximum) files per message."
39 }
40 }
42​
43public struct UploadedAttachmentReference: Codable, Equatable, Sendable {
44 public let environmentID: String
45 public let attachmentID: String
46​
47 public init(environmentID: String, attachmentID: String) {
48 self.environmentID = environmentID
49 self.attachmentID = attachmentID
50 }
52​
53/// A validated turn attachment. Images can remain inline for older servers.
54/// Generic files require the upload capability. Clipboard text can stay in memory.
55public struct UploadChatAttachment: Equatable, Sendable {
56 public static let maximumBytes = 10 * 1024 * 1024
57 public static let maximumFileBytes = 50 * 1024 * 1024
58​
59 enum Source: Equatable, Sendable {
60 case imageData(Data)
61 case fileData(Data)
62 case file(URL)
63 }
64​
65 public let id: UUID
66 public let type: String
67 public let name: String
68 public let mimeType: String
69 public let sizeBytes: Int
70 public let uploadedReference: UploadedAttachmentReference?
71 public let contextSource: PastedTextAttachmentSource?
72 let source: Source
73​
74 public init(
75 id: UUID = UUID(),
76 data: Data,
77 name: String,
78 mimeType: String,
79 uploadedReference: UploadedAttachmentReference? = nil,
80 contextSource: PastedTextAttachmentSource? = nil
81 ) throws {
82 let normalizedMIME = mimeType.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
83 if !normalizedMIME.hasPrefix("image/") {
84 guard !data.isEmpty else { throw FileAttachmentError.empty }
85 guard data.count <= Self.maximumFileBytes else {
86 throw FileAttachmentError.tooLarge(actualBytes: data.count, maximumBytes: Self.maximumFileBytes)
87 }
88 let normalizedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
89 guard !normalizedName.isEmpty, normalizedName.count <= 255 else { throw FileAttachmentError.invalidName }
90 guard !normalizedMIME.isEmpty, normalizedMIME.count <= 100,
91 !normalizedMIME.contains(where: { $0.isWhitespace || $0.isNewline }) else { throw FileAttachmentError.invalidMIMEType }
92 self.id = id
93 type = "file"
94 self.name = normalizedName
95 self.mimeType = normalizedMIME
96 sizeBytes = data.count
97 self.uploadedReference = uploadedReference
98 self.contextSource = contextSource
99 source = .fileData(data)
100 return
101 }
102 guard !data.isEmpty else { throw ImageAttachmentError.empty }
103 guard data.count <= Self.maximumBytes else {
104 throw ImageAttachmentError.tooLarge(
105 actualBytes: data.count,
106 maximumBytes: Self.maximumBytes
107 )
108 }
109 let normalizedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
110 guard !normalizedName.isEmpty, normalizedName.count <= 255 else {
111 throw ImageAttachmentError.invalidName
112 }
113 guard normalizedMIME.hasPrefix("image/"), normalizedMIME.count <= 100 else {
114 throw ImageAttachmentError.invalidMIMEType
115 }
116 self.id = id
117 type = "image"
118 self.name = normalizedName
119 self.mimeType = normalizedMIME
120 sizeBytes = data.count
121 self.uploadedReference = uploadedReference
122 self.contextSource = nil
123 source = .imageData(data)
124 }
125​
126 public init(
127 id: UUID = UUID(),
128 fileURL: URL,
129 name: String,
130 mimeType: String,
131 sizeBytes: Int,
132 uploadedReference: UploadedAttachmentReference? = nil,
133 contextSource: PastedTextAttachmentSource? = nil
134 ) throws {
135 guard fileURL.isFileURL else { throw FileAttachmentError.invalidFileURL }
136 guard sizeBytes > 0 else { throw FileAttachmentError.empty }
137 guard sizeBytes <= Self.maximumFileBytes else {
138 throw FileAttachmentError.tooLarge(
139 actualBytes: sizeBytes,
140 maximumBytes: Self.maximumFileBytes
141 )
142 }
143 let normalizedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
144 guard !normalizedName.isEmpty, normalizedName.count <= 255 else {
145 throw FileAttachmentError.invalidName
146 }
147 let normalizedMIME = mimeType.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
148 guard !normalizedMIME.isEmpty, normalizedMIME.count <= 100,
149 !normalizedMIME.contains(where: { $0.isWhitespace || $0.isNewline }) else {
150 throw FileAttachmentError.invalidMIMEType
151 }
152 self.id = id
153 type = "file"
154 self.name = normalizedName
155 self.mimeType = normalizedMIME
156 self.sizeBytes = sizeBytes
157 self.uploadedReference = uploadedReference
158 self.contextSource = contextSource
159 source = .file(fileURL)
160 }
161​
162 var jsonValue: JSONValue {
163 var value: [String: JSONValue] = [
164 "type": .string(type),
165 "name": .string(name),
166 "mimeType": .string(mimeType),
167 "sizeBytes": .number(Double(sizeBytes)),
168 ]
169 if case let .imageData(data) = source {
170 value["id"] = .string(id.uuidString)
171 value["dataUrl"] = .string(
172 "data:\(mimeType);base64,\(data.base64EncodedString())"
173 )
174 }
175 return .object(value)
176 }
177​
178 func uploadedJSONValue(id: String) -> JSONValue {
179 var value: [String: JSONValue] = [
180 "type": .string(type),
181 "id": .string(id),
182 "name": .string(name),
183 "mimeType": .string(mimeType),
184 "sizeBytes": .number(Double(sizeBytes)),
185 ]
186 if let contextSource {
187 value["source"] = .object(["_tag": .string(contextSource.rawValue)])
188 }
189 return .object(value)
190 }
192​
193/// Keeps the existing image API and call sites source-compatible.
194public typealias UploadChatImageAttachment = UploadChatAttachment
195​
196public struct AttachmentCreateUploadURLResult: Codable, Equatable, Sendable {
197 public let attachmentId: String
198 public let relativeUrl: String
199 public let expiresAt: Double
201​
202public enum AssetResource: Equatable, Sendable {
203 case workspaceFile(threadID: String, path: String)
204 case mediaFile(threadID: String, path: String)
205 case attachment(id: String, fileName: String? = nil, mimeType: String? = nil)
206 case projectFavicon(cwd: String)
207 case nativeAppIcon(ToolNativeAppReference)
208​
209 var jsonValue: JSONValue {
210 switch self {
211 case let .nativeAppIcon(app):
212 var reference: [String: JSONValue] = ["_tag": .string(app._tag)]
213 if let id = app.appId { reference["appId"] = .string(id) }
214 if let name = app.displayName { reference["displayName"] = .string(name) }
215 return .object(["_tag": .string("native-app-icon"), "app": .object(reference)])
216 case let .workspaceFile(threadID, path):
217 return .object([
218 "_tag": .string("workspace-file"),
219 "threadId": .string(threadID),
220 "path": .string(path),
221 ])
222 case let .mediaFile(threadID, path):
223 return .object([
224 "_tag": .string("media-file"),
225 "threadId": .string(threadID),
226 "path": .string(path),
227 ])
228 case let .attachment(id, fileName, mimeType):
229 var value: [String: JSONValue] = [
230 "_tag": .string("attachment"),
231 "attachmentId": .string(id),
232 ]
233 if let fileName { value["fileName"] = .string(fileName) }
234 if let mimeType { value["mimeType"] = .string(mimeType) }
235 return .object(value)
236 case let .projectFavicon(cwd):
237 return .object([
238 "_tag": .string("project-favicon"),
239 "cwd": .string(cwd),
240 ])
241 }
242 }
244​
245public struct AssetImageDimensions: Codable, Equatable, Sendable {
246 public let width: Int
247 public let height: Int
249​
250public struct AssetCreateURLResult: Codable, Equatable, Sendable {
251 public let relativeUrl: String
252 /// Unix epoch milliseconds from the server contract.
253 public let expiresAt: Double
254 public let imageDimensions: AssetImageDimensions?
256​
257public struct ResolvedAssetURL: Equatable, Sendable {
258 public let url: URL
259 public let expiresAt: Date
260 public var imageDimensions: AssetImageDimensions? = nil