@capgo/capacitor-widget-kit 8.1.0

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 (54) hide show
  1. package/CapgoCapacitorWidgetKit.podspec +17 -0
  2. package/LICENSE +373 -0
  3. package/Package.swift +28 -0
  4. package/README.md +1119 -0
  5. package/android/build.gradle +59 -0
  6. package/android/src/main/AndroidManifest.xml +8 -0
  7. package/android/src/main/java/app/capgo/widgetkit/CapgoNativeWidgetBridge.java +311 -0
  8. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateActionReceiver.java +36 -0
  9. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateSvgBitmapRenderer.java +25 -0
  10. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateWidgetBridge.java +31 -0
  11. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKit.java +218 -0
  12. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKitConstants.java +18 -0
  13. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKitPlugin.java +370 -0
  14. package/android/src/main/java/app/capgo/widgetkit/TemplateActivityStore.java +167 -0
  15. package/android/src/main/java/app/capgo/widgetkit/TemplateJsonUtils.java +369 -0
  16. package/android/src/main/java/app/capgo/widgetkit/TemplateRuntime.java +676 -0
  17. package/android/src/main/res/.gitkeep +0 -0
  18. package/dist/docs.json +2223 -0
  19. package/dist/esm/definitions.d.ts +1117 -0
  20. package/dist/esm/definitions.js +2 -0
  21. package/dist/esm/definitions.js.map +1 -0
  22. package/dist/esm/helpers/workout.d.ts +32 -0
  23. package/dist/esm/helpers/workout.js +129 -0
  24. package/dist/esm/helpers/workout.js.map +1 -0
  25. package/dist/esm/index.d.ts +6 -0
  26. package/dist/esm/index.js +9 -0
  27. package/dist/esm/index.js.map +1 -0
  28. package/dist/esm/runtime.d.ts +25 -0
  29. package/dist/esm/runtime.js +653 -0
  30. package/dist/esm/runtime.js.map +1 -0
  31. package/dist/esm/web.d.ts +23 -0
  32. package/dist/esm/web.js +292 -0
  33. package/dist/esm/web.js.map +1 -0
  34. package/dist/plugin.cjs.js +1096 -0
  35. package/dist/plugin.cjs.js.map +1 -0
  36. package/dist/plugin.js +1099 -0
  37. package/dist/plugin.js.map +1 -0
  38. package/ios/Sources/CapgoWidgetKitPlugin/CapgoNativeWidgetBridge.swift +372 -0
  39. package/ios/Sources/CapgoWidgetKitPlugin/CapgoTemplateWidgetBridge.swift +199 -0
  40. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKit.swift +218 -0
  41. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKitPlugin.swift +322 -0
  42. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKitSharedStore.swift +47 -0
  43. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWorkoutLiveActivityComponents.swift +246 -0
  44. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWorkoutLiveActivityWidget.swift +257 -0
  45. package/ios/Sources/CapgoWidgetKitPlugin/CompleteSetIntent.swift +24 -0
  46. package/ios/Sources/CapgoWidgetKitPlugin/TemplateActionIntent.swift +56 -0
  47. package/ios/Sources/CapgoWidgetKitPlugin/TemplateActivityStore.swift +239 -0
  48. package/ios/Sources/CapgoWidgetKitPlugin/TemplateLiveActivityManager.swift +251 -0
  49. package/ios/Sources/CapgoWidgetKitPlugin/TemplateRuntime.swift +1067 -0
  50. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutActivityStore.swift +111 -0
  51. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutLiveActivityManager.swift +263 -0
  52. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutSession.swift +271 -0
  53. package/ios/Tests/CapgoWidgetKitPluginTests/CapgoWidgetKitPluginTests.swift +130 -0
  54. package/package.json +93 -0
@@ -0,0 +1,1067 @@
1
+ import Foundation
2
+
3
+ struct TemplateRuntimeRecord {
4
+ var activityId: String
5
+ var templateId: String
6
+ var definition: [String: Any]
7
+ var state: [String: Any]
8
+ var timers: [String: StoredTemplateTimerState]
9
+ var status: String
10
+ var openUrl: String?
11
+ var updatedAtMs: Int64
12
+ var revision: Int
13
+ var nativeActivityId: String?
14
+
15
+ init(
16
+ activityId: String,
17
+ templateId: String,
18
+ definition: [String: Any],
19
+ state: [String: Any],
20
+ timers: [String: StoredTemplateTimerState],
21
+ status: String,
22
+ openUrl: String?,
23
+ updatedAtMs: Int64,
24
+ revision: Int,
25
+ nativeActivityId: String?
26
+ ) {
27
+ self.activityId = activityId
28
+ self.templateId = templateId
29
+ self.definition = definition
30
+ self.state = state
31
+ self.timers = timers
32
+ self.status = status
33
+ self.openUrl = openUrl
34
+ self.updatedAtMs = updatedAtMs
35
+ self.revision = revision
36
+ self.nativeActivityId = nativeActivityId
37
+ }
38
+
39
+ init(envelope: StoredTemplateActivityEnvelope) throws {
40
+ let definitionObject = try TemplateRuntime.jsonObject(from: envelope.definitionData)
41
+ let stateObject = try TemplateRuntime.jsonObject(from: envelope.stateData)
42
+
43
+ guard let definition = definitionObject as? [String: Any] else {
44
+ throw CapgoWidgetKitBridgeError.invalidObject("The stored template definition is not a JSON object.")
45
+ }
46
+
47
+ guard let state = stateObject as? [String: Any] else {
48
+ throw CapgoWidgetKitBridgeError.invalidObject("The stored template state is not a JSON object.")
49
+ }
50
+
51
+ activityId = envelope.activityId
52
+ templateId = envelope.templateId
53
+ self.definition = definition
54
+ self.state = state
55
+ timers = envelope.timers
56
+ status = envelope.status
57
+ openUrl = envelope.openUrl
58
+ updatedAtMs = envelope.updatedAtMs
59
+ revision = envelope.revision
60
+ nativeActivityId = envelope.nativeActivityId
61
+ }
62
+
63
+ func toEnvelope() throws -> StoredTemplateActivityEnvelope {
64
+ StoredTemplateActivityEnvelope(
65
+ activityId: activityId,
66
+ templateId: templateId,
67
+ definitionData: try TemplateRuntime.jsonData(from: definition),
68
+ stateData: try TemplateRuntime.jsonData(from: state),
69
+ timers: timers,
70
+ status: status,
71
+ openUrl: openUrl,
72
+ updatedAtMs: updatedAtMs,
73
+ revision: revision,
74
+ nativeActivityId: nativeActivityId
75
+ )
76
+ }
77
+ }
78
+
79
+ // swiftlint:disable type_body_length force_try function_parameter_count identifier_name file_length
80
+ enum TemplateRuntime {
81
+ private static let tokenRegex = try! NSRegularExpression(pattern: #"\{\{\s*([^{}]+?)\s*\}\}"#)
82
+ private static let exactTokenRegex = try! NSRegularExpression(pattern: #"^\{\{\s*([^{}]+?)\s*\}\}$"#)
83
+
84
+ static func jsonData(from object: Any) throws -> Data {
85
+ guard JSONSerialization.isValidJSONObject(object) else {
86
+ throw CapgoWidgetKitBridgeError.invalidObject("The template payload contains unsupported values.")
87
+ }
88
+ return try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
89
+ }
90
+
91
+ static func jsonObject(from data: Data) throws -> Any {
92
+ try JSONSerialization.jsonObject(with: data, options: [])
93
+ }
94
+
95
+ static func makeRecord(
96
+ activityId: String,
97
+ definitionObject: [String: Any],
98
+ stateObject: [String: Any],
99
+ openUrl: String?,
100
+ nowMs: Int64
101
+ ) -> TemplateRuntimeRecord {
102
+ var record = TemplateRuntimeRecord(
103
+ activityId: activityId,
104
+ templateId: (definitionObject["id"] as? String) ?? activityId,
105
+ definition: definitionObject,
106
+ state: stateObject,
107
+ timers: [:],
108
+ status: "active",
109
+ openUrl: openUrl,
110
+ updatedAtMs: nowMs,
111
+ revision: 1,
112
+ nativeActivityId: nil
113
+ )
114
+ record.timers = reconcileTimers(for: record, nowMs: nowMs)
115
+ return record
116
+ }
117
+
118
+ static func serializeActivity(_ envelope: StoredTemplateActivityEnvelope) throws -> [String: Any] {
119
+ let record = try TemplateRuntimeRecord(envelope: envelope)
120
+ return serializeActivity(record, nowMs: envelope.updatedAtMs)
121
+ }
122
+
123
+ static func serializeActivity(_ record: TemplateRuntimeRecord, nowMs: Int64) -> [String: Any] {
124
+ [
125
+ "activityId": record.activityId,
126
+ "definition": record.definition,
127
+ "state": record.state,
128
+ "timers": record.timers.mapValues(serializeStoredTimer),
129
+ "status": record.status,
130
+ "openUrl": record.openUrl as Any,
131
+ "updatedAt": record.updatedAtMs,
132
+ "revision": record.revision
133
+ ]
134
+ }
135
+
136
+ static func serializeEvent(_ event: StoredTemplateActionEvent) throws -> [String: Any] {
137
+ let stateObject = try jsonObject(from: event.stateData)
138
+ let payloadObject = try event.payloadData.map(jsonObject(from:))
139
+ return [
140
+ "eventId": event.eventId,
141
+ "activityId": event.activityId,
142
+ "actionId": event.actionId,
143
+ "eventName": event.eventName as Any,
144
+ "sourceId": event.sourceId as Any,
145
+ "createdAt": event.createdAtMs,
146
+ "acknowledgedAt": event.acknowledgedAtMs as Any,
147
+ "payload": payloadObject as Any,
148
+ "state": stateObject,
149
+ "timers": event.timers.mapValues(serializeStoredTimer)
150
+ ]
151
+ }
152
+
153
+ static func applyAction(
154
+ actionId: String,
155
+ sourceId: String?,
156
+ payloadObject: [String: Any]?,
157
+ record: TemplateRuntimeRecord,
158
+ nowMs: Int64
159
+ ) throws -> (TemplateRuntimeRecord, StoredTemplateActionEvent) {
160
+ guard let action = actionDefinitions(from: record.definition).first(where: { ($0["id"] as? String) == actionId }) else {
161
+ throw CapgoWidgetKitBridgeError.invalidObject("The action \(actionId) is not defined on template \(record.templateId).")
162
+ }
163
+
164
+ var nextRecord = record
165
+
166
+ if let patches = action["patches"] as? [[String: Any]] {
167
+ for patch in patches {
168
+ applyPatch(patch, to: &nextRecord, nowMs: nowMs, actionId: actionId, sourceId: sourceId, payloadObject: payloadObject)
169
+ }
170
+ }
171
+
172
+ if let frameMutations = action["frameMutations"] as? [[String: Any]] {
173
+ for mutation in frameMutations {
174
+ applyFrameMutation(
175
+ mutation,
176
+ to: &nextRecord,
177
+ nowMs: nowMs,
178
+ actionId: actionId,
179
+ sourceId: sourceId,
180
+ payloadObject: payloadObject
181
+ )
182
+ }
183
+ }
184
+
185
+ if let timerMutations = action["timerMutations"] as? [[String: Any]] {
186
+ for mutation in timerMutations {
187
+ applyTimerMutation(
188
+ mutation,
189
+ to: &nextRecord,
190
+ nowMs: nowMs,
191
+ actionId: actionId,
192
+ sourceId: sourceId,
193
+ payloadObject: payloadObject
194
+ )
195
+ }
196
+ }
197
+
198
+ nextRecord.timers = reconcileTimers(for: nextRecord, nowMs: nowMs)
199
+ nextRecord.updatedAtMs = nowMs
200
+ nextRecord.revision += 1
201
+
202
+ let event = StoredTemplateActionEvent(
203
+ eventId: createIdentifier(prefix: "event"),
204
+ activityId: nextRecord.activityId,
205
+ actionId: actionId,
206
+ eventName: action["eventName"] as? String,
207
+ sourceId: sourceId,
208
+ createdAtMs: nowMs,
209
+ acknowledgedAtMs: nil,
210
+ payloadData: try payloadObject.map(jsonData(from:)),
211
+ stateData: try jsonData(from: nextRecord.state),
212
+ timers: nextRecord.timers
213
+ )
214
+
215
+ return (nextRecord, event)
216
+ }
217
+
218
+ static func resolveSvg(layoutObject: [String: Any], record: TemplateRuntimeRecord, nowMs: Int64) -> String {
219
+ resolveLayout(layoutObject: layoutObject, record: record, nowMs: nowMs)["svg"] as? String ?? ""
220
+ }
221
+
222
+ static func resolveLayout(layoutObject: [String: Any], record: TemplateRuntimeRecord, nowMs: Int64) -> [String: Any] {
223
+ let resolvedFrame = resolveLayoutFrame(layoutObject: layoutObject, record: record, nowMs: nowMs)
224
+ return [
225
+ "frameId": resolvedFrame.frameId as Any,
226
+ "svg": resolveTemplateString(resolvedFrame.svg, record: record, nowMs: nowMs),
227
+ "hotspots": resolvedFrame.hotspots as Any
228
+ ]
229
+ }
230
+
231
+ private static func resolveLayoutFrame(
232
+ layoutObject: [String: Any],
233
+ record: TemplateRuntimeRecord,
234
+ nowMs: Int64
235
+ ) -> (frameId: String?, svg: String, hotspots: Any?) {
236
+ let frames = layoutObject["frames"] as? [[String: Any]] ?? []
237
+ let requestedFrameId = resolveFrameId(layoutObject["frameIdPath"] as? String, record: record, nowMs: nowMs, dereferenceReferences: true)
238
+ let requestedFrame = frames.first(where: { ($0["id"] as? String) == requestedFrameId })
239
+ let defaultFrame = frames.first(where: { ($0["id"] as? String) == (layoutObject["defaultFrameId"] as? String) })
240
+ let selectedFrame = requestedFrame ?? defaultFrame ?? (layoutObject["svg"] == nil ? frames.first : nil)
241
+
242
+ return (
243
+ frameId: selectedFrame?["id"] as? String,
244
+ svg: selectedFrame?["svg"] as? String ?? layoutObject["svg"] as? String ?? "",
245
+ hotspots: selectedFrame?["hotspots"] ?? layoutObject["hotspots"]
246
+ )
247
+ }
248
+
249
+ static func createIdentifier(prefix: String) -> String {
250
+ "\(prefix)-\(UUID().uuidString.lowercased())"
251
+ }
252
+
253
+ private static func timerDefinitions(from definition: [String: Any]) -> [[String: Any]] {
254
+ definition["timers"] as? [[String: Any]] ?? []
255
+ }
256
+
257
+ private static func actionDefinitions(from definition: [String: Any]) -> [[String: Any]] {
258
+ definition["actions"] as? [[String: Any]] ?? []
259
+ }
260
+
261
+ private static func timerElapsedMs(_ timer: StoredTemplateTimerState, nowMs: Int64) -> Int64 {
262
+ let savedElapsedMs = max(Int64(0), timer.elapsedMs ?? 0)
263
+ if timer.status == "finished", timer.durationMs > 0 {
264
+ return timer.durationMs
265
+ }
266
+ if timer.status == "running", let startedAtMs = timer.startedAtMs {
267
+ return savedElapsedMs + max(Int64(0), nowMs - startedAtMs)
268
+ }
269
+ return savedElapsedMs
270
+ }
271
+
272
+ private static func serializeTimerBinding(_ timer: StoredTemplateTimerState, nowMs: Int64) -> [String: Any] {
273
+ let status = timerStatus(timer, nowMs: nowMs)
274
+ let startedAtMs = status == "running" ? timer.startedAtMs : nil
275
+ let durationMs = timer.durationMs
276
+ let elapsedMs = min(timerElapsedMs(timer, nowMs: nowMs), durationMs > 0 ? durationMs : Int64.max)
277
+ let remainingMs = durationMs > 0 ? max(Int64(0), durationMs - elapsedMs) : 0
278
+ let progress = durationMs > 0 ? min(max(Double(elapsedMs) / Double(durationMs), 0), 1) : 0
279
+ let totalSeconds = max(0, Int(ceil(Double(remainingMs) / 1000.0)))
280
+ let minutes = totalSeconds / 60
281
+ let seconds = totalSeconds % 60
282
+
283
+ return [
284
+ "id": timer.id,
285
+ "startedAtMs": startedAtMs as Any,
286
+ "durationMs": durationMs,
287
+ "status": status,
288
+ "elapsedMs": elapsedMs,
289
+ "remainingMs": remainingMs,
290
+ "progress": progress,
291
+ "progressPct": Double(round(progress * 10_000) / 100),
292
+ "isActive": status == "running",
293
+ "isPaused": status == "paused",
294
+ "remainingText": String(format: "%d:%02d", minutes, seconds),
295
+ "endsAtMs": startedAtMs.map { $0 + max(Int64(0), durationMs - (timer.elapsedMs ?? 0)) } as Any
296
+ ]
297
+ }
298
+
299
+ private static func serializeStoredTimer(_ timer: StoredTemplateTimerState) -> [String: Any] {
300
+ [
301
+ "id": timer.id,
302
+ "startedAt": timer.startedAtMs as Any,
303
+ "elapsedMs": timer.elapsedMs as Any,
304
+ "durationMs": timer.durationMs,
305
+ "status": timer.status,
306
+ "updatedAt": timer.updatedAtMs
307
+ ]
308
+ }
309
+
310
+ static func reconcileTimers(for record: TemplateRuntimeRecord, nowMs: Int64) -> [String: StoredTemplateTimerState] {
311
+ var nextTimers: [String: StoredTemplateTimerState] = [:]
312
+
313
+ for definition in timerDefinitions(from: record.definition) {
314
+ guard let timerId = definition["id"] as? String else {
315
+ continue
316
+ }
317
+
318
+ let previous = record.timers[timerId]
319
+ let durationMs = resolveDuration(definition, record: record, nowMs: nowMs) ?? previous?.durationMs ?? 0
320
+ let hasStartAtPath = !((definition["startAtPath"] as? String) ?? "").isEmpty
321
+ let shouldResolveStartAt = previous == nil || (previous?.startedAtMs == nil && hasStartAtPath)
322
+ let startedAtMs = previous?.startedAtMs ?? (shouldResolveStartAt ? resolveStartAt(definition, record: record, nowMs: nowMs) : nil)
323
+
324
+ var timer = StoredTemplateTimerState(
325
+ id: timerId,
326
+ startedAtMs: startedAtMs,
327
+ durationMs: durationMs,
328
+ status: previous?.status ?? (startedAtMs == nil ? "idle" : "running"),
329
+ updatedAtMs: nowMs,
330
+ elapsedMs: previous?.elapsedMs ?? 0
331
+ )
332
+ timer.status = timerStatus(timer, nowMs: nowMs)
333
+ if timer.status == "finished" {
334
+ timer.startedAtMs = nil
335
+ timer.elapsedMs = timer.durationMs
336
+ }
337
+ nextTimers[timerId] = timer
338
+ }
339
+
340
+ return nextTimers
341
+ }
342
+
343
+ private static func resolveDuration(_ definition: [String: Any], record: TemplateRuntimeRecord, nowMs: Int64) -> Int64? {
344
+ if let duration = coerceInt64(definition["durationMs"]) {
345
+ return max(0, duration)
346
+ }
347
+
348
+ if let durationPath = definition["durationPath"] as? String {
349
+ let resolvedPath = resolveTemplateString(durationPath, record: record, nowMs: nowMs)
350
+ return max(0, coerceInt64(resolveReference(resolvedPath, record: record, nowMs: nowMs)) ?? 0)
351
+ }
352
+
353
+ return nil
354
+ }
355
+
356
+ private static func resolveStartAt(_ definition: [String: Any], record: TemplateRuntimeRecord, nowMs: Int64) -> Int64? {
357
+ if let startAtPath = definition["startAtPath"] as? String {
358
+ let resolvedPath = resolveTemplateString(startAtPath, record: record, nowMs: nowMs)
359
+ if let startAt = coerceInt64(resolveReference(resolvedPath, record: record, nowMs: nowMs)) {
360
+ return startAt
361
+ }
362
+ }
363
+
364
+ if (definition["autoStart"] as? Bool) == true {
365
+ return nowMs
366
+ }
367
+
368
+ return nil
369
+ }
370
+
371
+ private static func applyPatch(
372
+ _ patch: [String: Any],
373
+ to record: inout TemplateRuntimeRecord,
374
+ nowMs: Int64,
375
+ actionId: String,
376
+ sourceId: String?,
377
+ payloadObject: [String: Any]?
378
+ ) {
379
+ guard let op = patch["op"] as? String, let rawPath = patch["path"] as? String else {
380
+ return
381
+ }
382
+
383
+ let resolvedPath = normalizeStatePath(
384
+ resolveTemplateString(
385
+ rawPath,
386
+ record: record,
387
+ nowMs: nowMs,
388
+ actionId: actionId,
389
+ sourceId: sourceId,
390
+ payloadObject: payloadObject
391
+ )
392
+ )
393
+ guard !resolvedPath.isEmpty else {
394
+ return
395
+ }
396
+
397
+ switch op {
398
+ case "set":
399
+ setValue(
400
+ resolvePatchValue(
401
+ patch,
402
+ record: record,
403
+ nowMs: nowMs,
404
+ actionId: actionId,
405
+ sourceId: sourceId,
406
+ payloadObject: payloadObject
407
+ ),
408
+ at: resolvedPath,
409
+ in: &record.state
410
+ )
411
+ case "timestamp":
412
+ setValue(nowMs, at: resolvedPath, in: &record.state)
413
+ case "increment":
414
+ let currentValue = coerceInt64(getValue(at: resolvedPath, in: record.state)) ?? 0
415
+ let amount = coerceInt64(patch["amount"]) ?? 1
416
+ setValue(currentValue + amount, at: resolvedPath, in: &record.state)
417
+ case "toggle":
418
+ let currentValue = getValue(at: resolvedPath, in: record.state) as? Bool ?? false
419
+ setValue(!currentValue, at: resolvedPath, in: &record.state)
420
+ case "unset":
421
+ removeValue(at: resolvedPath, in: &record.state)
422
+ default:
423
+ break
424
+ }
425
+ }
426
+
427
+ private static func resolvePatchValue(
428
+ _ patch: [String: Any],
429
+ record: TemplateRuntimeRecord,
430
+ nowMs: Int64,
431
+ actionId: String,
432
+ sourceId: String?,
433
+ payloadObject: [String: Any]?
434
+ ) -> Any {
435
+ if let valuePath = patch["valuePath"] as? String {
436
+ let resolvedPath = resolveTemplateString(
437
+ valuePath,
438
+ record: record,
439
+ nowMs: nowMs,
440
+ actionId: actionId,
441
+ sourceId: sourceId,
442
+ payloadObject: payloadObject
443
+ )
444
+ return cloneJsonValue(
445
+ resolveReference(
446
+ resolvedPath,
447
+ record: record,
448
+ nowMs: nowMs,
449
+ actionId: actionId,
450
+ sourceId: sourceId,
451
+ payloadObject: payloadObject
452
+ ) ?? NSNull()
453
+ )
454
+ }
455
+
456
+ if let valueTemplate = patch["valueTemplate"] as? String {
457
+ if let exact = exactTokenValue(
458
+ valueTemplate,
459
+ record: record,
460
+ nowMs: nowMs,
461
+ actionId: actionId,
462
+ sourceId: sourceId,
463
+ payloadObject: payloadObject
464
+ ) {
465
+ return cloneJsonValue(exact)
466
+ }
467
+ return resolveTemplateString(
468
+ valueTemplate,
469
+ record: record,
470
+ nowMs: nowMs,
471
+ actionId: actionId,
472
+ sourceId: sourceId,
473
+ payloadObject: payloadObject
474
+ )
475
+ }
476
+
477
+ if let value = patch["value"] {
478
+ return cloneJsonValue(value)
479
+ }
480
+
481
+ return NSNull()
482
+ }
483
+
484
+ private static func frameIdsForMutation(_ mutation: [String: Any], record: TemplateRuntimeRecord) -> [String] {
485
+ if let frameIds = mutation["frameIds"] as? [String], !frameIds.isEmpty {
486
+ return frameIds
487
+ }
488
+
489
+ guard let surface = mutation["surface"] as? String,
490
+ let layouts = record.definition["layouts"] as? [String: Any],
491
+ let layout = layouts[surface] as? [String: Any],
492
+ let frames = layout["frames"] as? [[String: Any]]
493
+ else {
494
+ return []
495
+ }
496
+
497
+ return frames.compactMap { $0["id"] as? String }
498
+ }
499
+
500
+ private static func resolveFrameId(
501
+ _ template: String?,
502
+ record: TemplateRuntimeRecord,
503
+ nowMs: Int64,
504
+ actionId: String? = nil,
505
+ sourceId: String? = nil,
506
+ payloadObject: [String: Any]? = nil,
507
+ dereferenceReferences: Bool = false
508
+ ) -> String? {
509
+ guard let template, !template.isEmpty else {
510
+ return nil
511
+ }
512
+
513
+ if let exact = exactTokenValue(
514
+ template,
515
+ record: record,
516
+ nowMs: nowMs,
517
+ actionId: actionId,
518
+ sourceId: sourceId,
519
+ payloadObject: payloadObject
520
+ ) {
521
+ return stringifyValue(exact)
522
+ }
523
+
524
+ let resolved = resolveTemplateString(
525
+ template,
526
+ record: record,
527
+ nowMs: nowMs,
528
+ actionId: actionId,
529
+ sourceId: sourceId,
530
+ payloadObject: payloadObject
531
+ )
532
+ if dereferenceReferences,
533
+ let referenced = resolveReference(
534
+ resolved,
535
+ record: record,
536
+ nowMs: nowMs,
537
+ actionId: actionId,
538
+ sourceId: sourceId,
539
+ payloadObject: payloadObject
540
+ ) {
541
+ return stringifyValue(referenced)
542
+ }
543
+ return resolved.isEmpty ? nil : resolved
544
+ }
545
+
546
+ private static func normalizeFrameMutationId(_ frameId: String?, frameIds: [String]) -> String? {
547
+ guard let frameId, !frameId.isEmpty else {
548
+ return nil
549
+ }
550
+ return frameIds.isEmpty || frameIds.contains(frameId) ? frameId : nil
551
+ }
552
+
553
+ private static func applyFrameMutation(
554
+ _ mutation: [String: Any],
555
+ to record: inout TemplateRuntimeRecord,
556
+ nowMs: Int64,
557
+ actionId: String,
558
+ sourceId: String?,
559
+ payloadObject: [String: Any]?
560
+ ) {
561
+ guard let op = mutation["op"] as? String, let rawPath = mutation["path"] as? String else {
562
+ return
563
+ }
564
+
565
+ let resolvedPath = normalizeStatePath(
566
+ resolveTemplateString(
567
+ rawPath,
568
+ record: record,
569
+ nowMs: nowMs,
570
+ actionId: actionId,
571
+ sourceId: sourceId,
572
+ payloadObject: payloadObject
573
+ )
574
+ )
575
+ guard !resolvedPath.isEmpty else {
576
+ return
577
+ }
578
+
579
+ let frameIds = frameIdsForMutation(mutation, record: record)
580
+ let currentValue = stringifyValue(getValue(at: resolvedPath, in: record.state))
581
+ let currentIndex = frameIds.firstIndex(of: currentValue)
582
+ let wraps = (mutation["wrap"] as? Bool) ?? true
583
+ var nextFrameId: String?
584
+
585
+ switch op {
586
+ case "set":
587
+ nextFrameId = resolveFrameId(
588
+ mutation["frameId"] as? String,
589
+ record: record,
590
+ nowMs: nowMs,
591
+ actionId: actionId,
592
+ sourceId: sourceId,
593
+ payloadObject: payloadObject
594
+ )
595
+ case "toggle":
596
+ let alternateFrameId = resolveFrameId(
597
+ mutation["frameId"] as? String,
598
+ record: record,
599
+ nowMs: nowMs,
600
+ actionId: actionId,
601
+ sourceId: sourceId,
602
+ payloadObject: payloadObject
603
+ )
604
+ if frameIds.count >= 2 {
605
+ nextFrameId = currentValue == frameIds[0] ? frameIds[1] : frameIds[0]
606
+ } else if let alternateFrameId {
607
+ nextFrameId = currentValue == alternateFrameId ? frameIds.first : alternateFrameId
608
+ }
609
+ case "next":
610
+ guard !frameIds.isEmpty else { break }
611
+ let nextIndex = currentIndex.map { $0 + 1 } ?? 0
612
+ nextFrameId = frameIds.indices.contains(nextIndex) ? frameIds[nextIndex] : (wraps ? frameIds[0] : currentValue)
613
+ case "previous":
614
+ guard !frameIds.isEmpty else { break }
615
+ let nextIndex = currentIndex.map { $0 - 1 } ?? frameIds.count - 1
616
+ nextFrameId = frameIds.indices.contains(nextIndex) ? frameIds[nextIndex] : (wraps ? frameIds[frameIds.count - 1] : currentValue)
617
+ default:
618
+ break
619
+ }
620
+
621
+ nextFrameId = normalizeFrameMutationId(nextFrameId, frameIds: frameIds)
622
+ if let nextFrameId, !nextFrameId.isEmpty {
623
+ setValue(nextFrameId, at: resolvedPath, in: &record.state)
624
+ }
625
+ }
626
+
627
+ private static func pauseTimer(_ timer: inout StoredTemplateTimerState, nowMs: Int64) {
628
+ timer.elapsedMs = min(timer.durationMs, timerElapsedMs(timer, nowMs: nowMs))
629
+ timer.startedAtMs = nil
630
+ timer.status = timerStatus(timer, nowMs: nowMs)
631
+ }
632
+
633
+ private static func resumeTimer(_ timer: inout StoredTemplateTimerState, nowMs: Int64) {
634
+ if timer.status == "stopped" {
635
+ return
636
+ }
637
+ if timer.status != "paused" {
638
+ timer.elapsedMs = 0
639
+ }
640
+ timer.startedAtMs = nowMs
641
+ timer.status = timer.durationMs > 0 ? "running" : "idle"
642
+ }
643
+
644
+ private static func applyTimerMutation(
645
+ _ mutation: [String: Any],
646
+ to record: inout TemplateRuntimeRecord,
647
+ nowMs: Int64,
648
+ actionId: String,
649
+ sourceId: String?,
650
+ payloadObject: [String: Any]?
651
+ ) {
652
+ guard let op = mutation["op"] as? String, let timerId = mutation["timerId"] as? String else {
653
+ return
654
+ }
655
+
656
+ var timer = record.timers[timerId] ?? StoredTemplateTimerState(
657
+ id: timerId,
658
+ startedAtMs: nil,
659
+ durationMs: 0,
660
+ status: "idle",
661
+ updatedAtMs: nowMs,
662
+ elapsedMs: 0
663
+ )
664
+
665
+ if let durationMs = coerceInt64(mutation["durationMs"]) {
666
+ timer.durationMs = max(0, durationMs)
667
+ } else if let durationPath = mutation["durationPath"] as? String {
668
+ let resolvedPath = resolveTemplateString(
669
+ durationPath,
670
+ record: record,
671
+ nowMs: nowMs,
672
+ actionId: actionId,
673
+ sourceId: sourceId,
674
+ payloadObject: payloadObject
675
+ )
676
+ timer.durationMs = max(
677
+ 0,
678
+ coerceInt64(
679
+ resolveReference(
680
+ resolvedPath,
681
+ record: record,
682
+ nowMs: nowMs,
683
+ actionId: actionId,
684
+ sourceId: sourceId,
685
+ payloadObject: payloadObject
686
+ )
687
+ ) ?? timer.durationMs
688
+ )
689
+ }
690
+
691
+ switch op {
692
+ case "start", "restart":
693
+ timer.elapsedMs = 0
694
+ timer.startedAtMs = nowMs
695
+ timer.status = timer.durationMs > 0 ? "running" : "idle"
696
+ case "pause":
697
+ pauseTimer(&timer, nowMs: nowMs)
698
+ case "resume":
699
+ resumeTimer(&timer, nowMs: nowMs)
700
+ case "toggle":
701
+ if timerStatus(timer, nowMs: nowMs) == "running" {
702
+ pauseTimer(&timer, nowMs: nowMs)
703
+ } else {
704
+ resumeTimer(&timer, nowMs: nowMs)
705
+ }
706
+ case "stop":
707
+ timer.elapsedMs = 0
708
+ timer.startedAtMs = nil
709
+ timer.status = "stopped"
710
+ case "reset":
711
+ timer.elapsedMs = 0
712
+ timer.startedAtMs = nil
713
+ timer.status = "idle"
714
+ case "setDuration":
715
+ break
716
+ default:
717
+ break
718
+ }
719
+
720
+ timer.updatedAtMs = nowMs
721
+ timer.status = timerStatus(timer, nowMs: nowMs)
722
+ if timer.status == "finished" {
723
+ timer.elapsedMs = timer.durationMs
724
+ timer.startedAtMs = nil
725
+ }
726
+ record.timers[timerId] = timer
727
+ }
728
+
729
+ private static func normalizeStatePath(_ path: String) -> String {
730
+ path.hasPrefix("state.") ? String(path.dropFirst("state.".count)) : path
731
+ }
732
+
733
+ private static func timerStatus(_ timer: StoredTemplateTimerState, nowMs: Int64) -> String {
734
+ if timer.status == "stopped" {
735
+ return "stopped"
736
+ }
737
+
738
+ let elapsedMs = timerElapsedMs(timer, nowMs: nowMs)
739
+ if timer.durationMs <= 0 {
740
+ return "idle"
741
+ }
742
+ if elapsedMs >= timer.durationMs {
743
+ return "finished"
744
+ }
745
+ if timer.status == "paused" {
746
+ return "paused"
747
+ }
748
+ if timer.startedAtMs != nil {
749
+ return "running"
750
+ }
751
+ return elapsedMs > 0 ? "paused" : "idle"
752
+ }
753
+
754
+ private static func buildScope(
755
+ record: TemplateRuntimeRecord,
756
+ nowMs: Int64,
757
+ actionId: String? = nil,
758
+ sourceId: String? = nil,
759
+ payloadObject: [String: Any]? = nil
760
+ ) -> [String: Any] {
761
+ var timers: [String: Any] = [:]
762
+ for (timerId, timerState) in record.timers {
763
+ timers[timerId] = serializeTimerBinding(timerState, nowMs: nowMs)
764
+ }
765
+
766
+ var scope: [String: Any] = [
767
+ "state": record.state,
768
+ "timers": timers,
769
+ "meta": [
770
+ "nowMs": nowMs,
771
+ "activityId": record.activityId,
772
+ "status": record.status,
773
+ "openUrl": record.openUrl as Any,
774
+ "revision": record.revision,
775
+ "updatedAt": record.updatedAtMs,
776
+ "template": [
777
+ "id": record.templateId,
778
+ "metadata": record.definition["metadata"] as Any
779
+ ]
780
+ ]
781
+ ]
782
+
783
+ if actionId != nil || sourceId != nil || payloadObject != nil {
784
+ scope["action"] = [
785
+ "id": actionId as Any,
786
+ "sourceId": sourceId as Any,
787
+ "payload": payloadObject as Any
788
+ ]
789
+ }
790
+
791
+ return scope
792
+ }
793
+
794
+ private static func resolveReference(
795
+ _ expression: String,
796
+ record: TemplateRuntimeRecord,
797
+ nowMs: Int64,
798
+ actionId: String? = nil,
799
+ sourceId: String? = nil,
800
+ payloadObject: [String: Any]? = nil
801
+ ) -> Any? {
802
+ let scope = buildScope(
803
+ record: record,
804
+ nowMs: nowMs,
805
+ actionId: actionId,
806
+ sourceId: sourceId,
807
+ payloadObject: payloadObject
808
+ )
809
+
810
+ if expression.hasPrefix("state.") || expression.hasPrefix("timers.") || expression.hasPrefix("meta.") || expression.hasPrefix("action.") {
811
+ return getValue(at: expression, in: scope)
812
+ }
813
+
814
+ return getValue(at: expression, in: record.state)
815
+ }
816
+
817
+ private static func exactTokenValue(
818
+ _ template: String,
819
+ record: TemplateRuntimeRecord,
820
+ nowMs: Int64,
821
+ actionId: String? = nil,
822
+ sourceId: String? = nil,
823
+ payloadObject: [String: Any]? = nil
824
+ ) -> Any? {
825
+ let range = NSRange(template.startIndex..., in: template)
826
+ guard let match = exactTokenRegex.firstMatch(in: template, options: [], range: range),
827
+ let tokenRange = Range(match.range(at: 1), in: template)
828
+ else {
829
+ return nil
830
+ }
831
+ return resolveReference(
832
+ String(template[tokenRange]),
833
+ record: record,
834
+ nowMs: nowMs,
835
+ actionId: actionId,
836
+ sourceId: sourceId,
837
+ payloadObject: payloadObject
838
+ )
839
+ }
840
+
841
+ private static func resolveTemplateString(
842
+ _ template: String,
843
+ record: TemplateRuntimeRecord,
844
+ nowMs: Int64,
845
+ actionId: String? = nil,
846
+ sourceId: String? = nil,
847
+ payloadObject: [String: Any]? = nil
848
+ ) -> String {
849
+ let matches = tokenRegex.matches(in: template, options: [], range: NSRange(template.startIndex..., in: template))
850
+ var resolved = template
851
+
852
+ for match in matches.reversed() {
853
+ guard let expressionRange = Range(match.range(at: 1), in: resolved),
854
+ let fullRange = Range(match.range(at: 0), in: resolved)
855
+ else {
856
+ continue
857
+ }
858
+
859
+ let expression = String(resolved[expressionRange])
860
+ let replacement = stringifyValue(
861
+ resolveReference(
862
+ expression,
863
+ record: record,
864
+ nowMs: nowMs,
865
+ actionId: actionId,
866
+ sourceId: sourceId,
867
+ payloadObject: payloadObject
868
+ )
869
+ )
870
+ resolved.replaceSubrange(fullRange, with: replacement)
871
+ }
872
+
873
+ return resolved
874
+ }
875
+
876
+ private static func stringifyValue(_ value: Any?) -> String {
877
+ switch value {
878
+ case nil, is NSNull:
879
+ return ""
880
+ case let string as String:
881
+ return string
882
+ case let number as NSNumber:
883
+ return number.stringValue
884
+ case let object as [String: Any]:
885
+ guard let data = try? jsonData(from: object),
886
+ let string = String(data: data, encoding: .utf8)
887
+ else {
888
+ return ""
889
+ }
890
+ return string
891
+ case let array as [Any]:
892
+ guard JSONSerialization.isValidJSONObject(array),
893
+ let data = try? JSONSerialization.data(withJSONObject: array, options: []),
894
+ let string = String(data: data, encoding: .utf8)
895
+ else {
896
+ return ""
897
+ }
898
+ return string
899
+ default:
900
+ return "\(value ?? "")"
901
+ }
902
+ }
903
+
904
+ private static func coerceInt64(_ value: Any?) -> Int64? {
905
+ switch value {
906
+ case let number as NSNumber:
907
+ return number.int64Value
908
+ case let string as String:
909
+ return Int64(string)
910
+ default:
911
+ return nil
912
+ }
913
+ }
914
+
915
+ private static func cloneJsonValue(_ value: Any) -> Any {
916
+ switch value {
917
+ case let object as [String: Any]:
918
+ guard let data = try? jsonData(from: object),
919
+ let cloned = try? jsonObject(from: data)
920
+ else {
921
+ return object
922
+ }
923
+ return cloned
924
+ case let array as [Any]:
925
+ guard JSONSerialization.isValidJSONObject(array),
926
+ let data = try? JSONSerialization.data(withJSONObject: array, options: []),
927
+ let cloned = try? JSONSerialization.jsonObject(with: data, options: [])
928
+ else {
929
+ return array
930
+ }
931
+ return cloned
932
+ default:
933
+ return value
934
+ }
935
+ }
936
+
937
+ private static func getValue(at path: String, in root: Any?) -> Any? {
938
+ var current = root
939
+ for segment in splitPath(path) {
940
+ if let dictionary = current as? [String: Any] {
941
+ current = dictionary[segment]
942
+ continue
943
+ }
944
+
945
+ if let array = current as? [Any], let index = Int(segment), array.indices.contains(index) {
946
+ current = array[index]
947
+ continue
948
+ }
949
+
950
+ return nil
951
+ }
952
+ return current
953
+ }
954
+
955
+ private static func setValue(_ value: Any, at path: String, in root: inout [String: Any]) {
956
+ let segments = splitPath(path)
957
+ guard !segments.isEmpty else {
958
+ return
959
+ }
960
+ var boxed: Any = root
961
+ setValue(value, segments: segments, current: &boxed)
962
+ root = boxed as? [String: Any] ?? root
963
+ }
964
+
965
+ private static func setValue(_ value: Any, segments: [String], current: inout Any) {
966
+ guard let segment = segments.first else {
967
+ current = value
968
+ return
969
+ }
970
+
971
+ if segments.count == 1 {
972
+ if var dictionary = current as? [String: Any] {
973
+ dictionary[segment] = value
974
+ current = dictionary
975
+ } else if var array = current as? [Any], let index = Int(segment) {
976
+ ensureArrayCapacity(&array, index: index)
977
+ array[index] = value
978
+ current = array
979
+ } else {
980
+ current = [segment: value]
981
+ }
982
+ return
983
+ }
984
+
985
+ if var dictionary = current as? [String: Any] {
986
+ var next = dictionary[segment] ?? defaultContainer(for: segments[1])
987
+ setValue(value, segments: Array(segments.dropFirst()), current: &next)
988
+ dictionary[segment] = next
989
+ current = dictionary
990
+ return
991
+ }
992
+
993
+ if var array = current as? [Any], let index = Int(segment) {
994
+ ensureArrayCapacity(&array, index: index)
995
+ var next = array[index]
996
+ if next is NSNull {
997
+ next = defaultContainer(for: segments[1])
998
+ }
999
+ setValue(value, segments: Array(segments.dropFirst()), current: &next)
1000
+ array[index] = next
1001
+ current = array
1002
+ return
1003
+ }
1004
+
1005
+ var dictionary: [String: Any] = [:]
1006
+ var next = defaultContainer(for: segments[1])
1007
+ setValue(value, segments: Array(segments.dropFirst()), current: &next)
1008
+ dictionary[segment] = next
1009
+ current = dictionary
1010
+ }
1011
+
1012
+ private static func removeValue(at path: String, in root: inout [String: Any]) {
1013
+ let segments = splitPath(path)
1014
+ guard !segments.isEmpty else {
1015
+ return
1016
+ }
1017
+ var boxed: Any = root
1018
+ removeValue(segments: segments, current: &boxed)
1019
+ root = boxed as? [String: Any] ?? root
1020
+ }
1021
+
1022
+ private static func removeValue(segments: [String], current: inout Any) {
1023
+ guard let segment = segments.first else {
1024
+ return
1025
+ }
1026
+
1027
+ if segments.count == 1 {
1028
+ if var dictionary = current as? [String: Any] {
1029
+ dictionary.removeValue(forKey: segment)
1030
+ current = dictionary
1031
+ } else if var array = current as? [Any], let index = Int(segment), array.indices.contains(index) {
1032
+ array.remove(at: index)
1033
+ current = array
1034
+ }
1035
+ return
1036
+ }
1037
+
1038
+ if var dictionary = current as? [String: Any], var next = dictionary[segment] {
1039
+ removeValue(segments: Array(segments.dropFirst()), current: &next)
1040
+ dictionary[segment] = next
1041
+ current = dictionary
1042
+ } else if var array = current as? [Any], let index = Int(segment), array.indices.contains(index) {
1043
+ var next = array[index]
1044
+ removeValue(segments: Array(segments.dropFirst()), current: &next)
1045
+ array[index] = next
1046
+ current = array
1047
+ }
1048
+ }
1049
+
1050
+ private static func splitPath(_ path: String) -> [String] {
1051
+ path
1052
+ .split(separator: ".")
1053
+ .map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) }
1054
+ .filter { !$0.isEmpty }
1055
+ }
1056
+
1057
+ private static func defaultContainer(for nextSegment: String) -> Any {
1058
+ Int(nextSegment) != nil ? [Any]() : [String: Any]()
1059
+ }
1060
+
1061
+ private static func ensureArrayCapacity(_ array: inout [Any], index: Int) {
1062
+ while array.count <= index {
1063
+ array.append(NSNull())
1064
+ }
1065
+ }
1066
+ }
1067
+ // swiftlint:enable type_body_length force_try function_parameter_count identifier_name file_length