strata-storage 2.6.0 → 2.7.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 (130) hide show
  1. package/AI-INTEGRATION-GUIDE.md +97 -10
  2. package/README.md +70 -70
  3. package/android/AGENTS.md +18 -3
  4. package/android/CLAUDE.md +36 -3
  5. package/android/build.gradle +5 -1
  6. package/android/src/main/java/com/strata/storage/EncryptedStorage.java +31 -18
  7. package/android/src/main/java/com/strata/storage/FilesystemStorage.java +62 -10
  8. package/android/src/main/java/com/strata/storage/SQLiteStorage.java +65 -13
  9. package/android/src/main/java/com/strata/storage/SharedPreferencesStorage.java +63 -51
  10. package/android/src/main/java/com/stratastorage/StrataStoragePlugin.java +80 -11
  11. package/dist/README.md +70 -70
  12. package/dist/adapters/capacitor/FilesystemAdapter.d.ts +2 -2
  13. package/dist/adapters/capacitor/FilesystemAdapter.d.ts.map +1 -1
  14. package/dist/adapters/capacitor/FilesystemAdapter.js +6 -2
  15. package/dist/adapters/capacitor/PreferencesAdapter.d.ts +2 -2
  16. package/dist/adapters/capacitor/PreferencesAdapter.d.ts.map +1 -1
  17. package/dist/adapters/capacitor/PreferencesAdapter.js +6 -2
  18. package/dist/adapters/capacitor/SecureAdapter.d.ts +3 -3
  19. package/dist/adapters/capacitor/SecureAdapter.d.ts.map +1 -1
  20. package/dist/adapters/capacitor/SecureAdapter.js +6 -2
  21. package/dist/adapters/capacitor/SqliteAdapter.d.ts +24 -3
  22. package/dist/adapters/capacitor/SqliteAdapter.d.ts.map +1 -1
  23. package/dist/adapters/capacitor/SqliteAdapter.js +105 -23
  24. package/dist/adapters/capacitor/index.d.ts +4 -4
  25. package/dist/adapters/web/CacheAdapter.d.ts +2 -2
  26. package/dist/adapters/web/CookieAdapter.d.ts +2 -2
  27. package/dist/adapters/web/IndexedDBAdapter.d.ts +10 -3
  28. package/dist/adapters/web/IndexedDBAdapter.d.ts.map +1 -1
  29. package/dist/adapters/web/IndexedDBAdapter.js +14 -3
  30. package/dist/adapters/web/LocalStorageAdapter.d.ts +2 -2
  31. package/dist/adapters/web/MemoryAdapter.d.ts +2 -2
  32. package/dist/adapters/web/SessionStorageAdapter.d.ts +10 -10
  33. package/dist/adapters/web/SessionStorageAdapter.d.ts.map +1 -1
  34. package/dist/adapters/web/SessionStorageAdapter.js +3 -2
  35. package/dist/adapters/web/URLAdapter.d.ts +2 -2
  36. package/dist/adapters/web/index.d.ts +7 -7
  37. package/dist/capacitor.d.ts +6 -6
  38. package/dist/capacitor.d.ts.map +1 -1
  39. package/dist/capacitor.js +5 -4
  40. package/dist/core/AdapterRegistry.d.ts +1 -1
  41. package/dist/core/BaseAdapter.d.ts +21 -5
  42. package/dist/core/BaseAdapter.d.ts.map +1 -1
  43. package/dist/core/BaseAdapter.js +29 -1
  44. package/dist/core/Strata.d.ts +41 -7
  45. package/dist/core/Strata.d.ts.map +1 -1
  46. package/dist/core/Strata.js +476 -118
  47. package/dist/features/compression/index.d.ts +1 -1
  48. package/dist/features/compression.d.ts +5 -1
  49. package/dist/features/compression.d.ts.map +1 -1
  50. package/dist/features/encryption/index.d.ts +1 -1
  51. package/dist/features/encryption.d.ts +55 -2
  52. package/dist/features/encryption.d.ts.map +1 -1
  53. package/dist/features/encryption.js +139 -26
  54. package/dist/features/migration.d.ts +1 -1
  55. package/dist/features/observer/index.d.ts +1 -1
  56. package/dist/features/observer.d.ts +1 -1
  57. package/dist/features/query/index.d.ts +1 -1
  58. package/dist/features/query.d.ts +1 -1
  59. package/dist/features/query.d.ts.map +1 -1
  60. package/dist/features/query.js +3 -1
  61. package/dist/features/sync/index.d.ts +1 -1
  62. package/dist/features/sync.d.ts +19 -3
  63. package/dist/features/sync.d.ts.map +1 -1
  64. package/dist/features/sync.js +57 -9
  65. package/dist/features/ttl/index.d.ts +1 -1
  66. package/dist/features/ttl.d.ts +2 -2
  67. package/dist/firebase.d.ts +1 -1
  68. package/dist/firebase.d.ts.map +1 -1
  69. package/dist/firebase.js +34 -9
  70. package/dist/index.d.ts +24 -22
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +6 -1
  73. package/dist/integrations/angular/index.d.ts +2 -2
  74. package/dist/integrations/angular/index.d.ts.map +1 -1
  75. package/dist/integrations/angular/index.js +7 -8
  76. package/dist/integrations/react/index.d.ts +3 -3
  77. package/dist/integrations/react/index.d.ts.map +1 -1
  78. package/dist/integrations/react/index.js +16 -4
  79. package/dist/integrations/vue/index.d.ts +2 -2
  80. package/dist/integrations/vue/index.d.ts.map +1 -1
  81. package/dist/integrations/vue/index.js +5 -2
  82. package/dist/package.json +11 -2
  83. package/dist/plugin/definitions.d.ts +29 -3
  84. package/dist/plugin/definitions.d.ts.map +1 -1
  85. package/dist/plugin/index.d.ts +2 -2
  86. package/dist/plugin/index.d.ts.map +1 -1
  87. package/dist/plugin/index.js +3 -0
  88. package/dist/plugin/web.d.ts +11 -2
  89. package/dist/plugin/web.d.ts.map +1 -1
  90. package/dist/plugin/web.js +23 -4
  91. package/dist/types/index.d.ts +50 -20
  92. package/dist/types/index.d.ts.map +1 -1
  93. package/dist/types/index.js +1 -10
  94. package/dist/utils/index.d.ts +5 -0
  95. package/dist/utils/index.d.ts.map +1 -1
  96. package/dist/utils/index.js +7 -0
  97. package/ios/AGENTS.md +14 -3
  98. package/ios/CLAUDE.md +25 -3
  99. package/ios/Plugin/FilesystemStorage.swift +19 -0
  100. package/ios/Plugin/SQLiteStorage.swift +59 -9
  101. package/ios/Plugin/StrataStoragePlugin.m +1 -0
  102. package/ios/Plugin/StrataStoragePlugin.swift +87 -34
  103. package/ios/Plugin/UserDefaultsStorage.swift +47 -46
  104. package/package.json +29 -26
  105. package/scripts/build.js +16 -14
  106. package/scripts/cli.js +1 -1
  107. package/scripts/configure.js +2 -2
  108. package/scripts/postinstall.js +3 -2
  109. package/dist/android/AGENTS.md +0 -51
  110. package/dist/android/CLAUDE.md +0 -89
  111. package/dist/android/build.gradle +0 -58
  112. package/dist/android/proguard-rules.pro +0 -11
  113. package/dist/android/settings.gradle +0 -2
  114. package/dist/android/src/main/AndroidManifest.xml +0 -2
  115. package/dist/android/src/main/java/com/strata/storage/EncryptedStorage.java +0 -218
  116. package/dist/android/src/main/java/com/strata/storage/FilesystemStorage.java +0 -287
  117. package/dist/android/src/main/java/com/strata/storage/SQLiteStorage.java +0 -371
  118. package/dist/android/src/main/java/com/strata/storage/SharedPreferencesStorage.java +0 -209
  119. package/dist/android/src/main/java/com/stratastorage/StrataStoragePlugin.java +0 -616
  120. package/dist/core/StorageStrategy.d.ts +0 -55
  121. package/dist/core/StorageStrategy.d.ts.map +0 -1
  122. package/dist/core/StorageStrategy.js +0 -200
  123. package/dist/ios/AGENTS.md +0 -48
  124. package/dist/ios/CLAUDE.md +0 -84
  125. package/dist/ios/Plugin/FilesystemStorage.swift +0 -218
  126. package/dist/ios/Plugin/KeychainStorage.swift +0 -233
  127. package/dist/ios/Plugin/SQLiteStorage.swift +0 -426
  128. package/dist/ios/Plugin/StrataStoragePlugin.m +0 -23
  129. package/dist/ios/Plugin/StrataStoragePlugin.swift +0 -411
  130. package/dist/ios/Plugin/UserDefaultsStorage.swift +0 -87
@@ -1,200 +0,0 @@
1
- /**
2
- * Storage strategy implementation for automatic adapter selection
3
- */
4
- import { StorageStrategy } from '@/types';
5
- import { AdapterRegistry } from "./AdapterRegistry.js";
6
- /**
7
- * Strategy manager for selecting appropriate storage adapters
8
- */
9
- export class StrategyManager {
10
- registry;
11
- strategy;
12
- constructor(registry, strategy = StorageStrategy.PERFORMANCE_FIRST) {
13
- this.registry = registry;
14
- this.strategy = strategy;
15
- }
16
- /**
17
- * Get the best adapter based on current strategy
18
- */
19
- async getBestAdapter(preferredTypes, requirements) {
20
- const available = await this.registry.getAvailable();
21
- // Filter by preferred types if specified
22
- let candidates = preferredTypes
23
- ? available.filter((adapter) => preferredTypes.includes(adapter.name))
24
- : available;
25
- // Filter by requirements
26
- if (requirements) {
27
- candidates = candidates.filter((adapter) => this.meetsRequirements(adapter.capabilities, requirements));
28
- }
29
- // Sort by strategy
30
- candidates.sort((a, b) => this.compareAdapters(a, b));
31
- return candidates[0] || null;
32
- }
33
- /**
34
- * Get multiple adapters sorted by preference
35
- */
36
- async getAdapterChain(count, preferredTypes, requirements) {
37
- const available = await this.registry.getAvailable();
38
- let candidates = preferredTypes
39
- ? available.filter((adapter) => preferredTypes.includes(adapter.name))
40
- : available;
41
- if (requirements) {
42
- candidates = candidates.filter((adapter) => this.meetsRequirements(adapter.capabilities, requirements));
43
- }
44
- candidates.sort((a, b) => this.compareAdapters(a, b));
45
- return candidates.slice(0, count);
46
- }
47
- /**
48
- * Check if capabilities meet requirements
49
- */
50
- meetsRequirements(capabilities, requirements) {
51
- for (const [key, value] of Object.entries(requirements)) {
52
- const capKey = key;
53
- if (typeof value === 'boolean' && capabilities[capKey] !== value) {
54
- return false;
55
- }
56
- if (capKey === 'maxSize' && typeof value === 'number') {
57
- const capSize = capabilities.maxSize;
58
- if (capSize !== -1 && capSize < value) {
59
- return false;
60
- }
61
- }
62
- }
63
- return true;
64
- }
65
- /**
66
- * Compare two adapters based on current strategy
67
- */
68
- compareAdapters(a, b) {
69
- switch (this.strategy) {
70
- case StorageStrategy.PERFORMANCE_FIRST:
71
- return this.comparePerformance(a, b);
72
- case StorageStrategy.PERSISTENCE_FIRST:
73
- return this.comparePersistence(a, b);
74
- case StorageStrategy.SECURITY_FIRST:
75
- return this.compareSecurity(a, b);
76
- case StorageStrategy.CAPACITY_FIRST:
77
- return this.compareCapacity(a, b);
78
- default:
79
- return 0;
80
- }
81
- }
82
- /**
83
- * Compare adapters by performance
84
- */
85
- comparePerformance(a, b) {
86
- // Priority order for performance
87
- const performanceOrder = [
88
- 'memory',
89
- 'sessionStorage',
90
- 'localStorage',
91
- 'cache',
92
- 'indexedDB',
93
- 'preferences',
94
- 'sqlite',
95
- 'filesystem',
96
- 'cookies',
97
- 'secure',
98
- ];
99
- const aIndex = performanceOrder.indexOf(a.name);
100
- const bIndex = performanceOrder.indexOf(b.name);
101
- // Prefer synchronous adapters for performance
102
- if (a.capabilities.synchronous !== b.capabilities.synchronous) {
103
- return a.capabilities.synchronous ? -1 : 1;
104
- }
105
- return aIndex - bIndex;
106
- }
107
- /**
108
- * Compare adapters by persistence
109
- */
110
- comparePersistence(a, b) {
111
- // Prefer persistent storage
112
- if (a.capabilities.persistent !== b.capabilities.persistent) {
113
- return a.capabilities.persistent ? -1 : 1;
114
- }
115
- // Priority order for persistence
116
- const persistenceOrder = [
117
- 'sqlite',
118
- 'filesystem',
119
- 'secure',
120
- 'indexedDB',
121
- 'preferences',
122
- 'localStorage',
123
- 'cache',
124
- 'cookies',
125
- 'sessionStorage',
126
- 'memory',
127
- ];
128
- const aIndex = persistenceOrder.indexOf(a.name);
129
- const bIndex = persistenceOrder.indexOf(b.name);
130
- return aIndex - bIndex;
131
- }
132
- /**
133
- * Compare adapters by security
134
- */
135
- compareSecurity(a, b) {
136
- // Prefer encrypted storage
137
- if (a.capabilities.encrypted !== b.capabilities.encrypted) {
138
- return a.capabilities.encrypted ? -1 : 1;
139
- }
140
- // Priority order for security
141
- const securityOrder = [
142
- 'secure',
143
- 'preferences',
144
- 'sqlite',
145
- 'indexedDB',
146
- 'filesystem',
147
- 'localStorage',
148
- 'sessionStorage',
149
- 'cache',
150
- 'memory',
151
- 'cookies',
152
- ];
153
- const aIndex = securityOrder.indexOf(a.name);
154
- const bIndex = securityOrder.indexOf(b.name);
155
- return aIndex - bIndex;
156
- }
157
- /**
158
- * Compare adapters by capacity
159
- */
160
- compareCapacity(a, b) {
161
- // Compare max sizes (-1 means unlimited)
162
- const aSize = a.capabilities.maxSize;
163
- const bSize = b.capabilities.maxSize;
164
- if (aSize === -1 && bSize !== -1)
165
- return -1;
166
- if (bSize === -1 && aSize !== -1)
167
- return 1;
168
- if (aSize !== -1 && bSize !== -1) {
169
- return bSize - aSize; // Higher capacity first
170
- }
171
- // Priority order for capacity
172
- const capacityOrder = [
173
- 'filesystem',
174
- 'sqlite',
175
- 'indexedDB',
176
- 'cache',
177
- 'preferences',
178
- 'secure',
179
- 'localStorage',
180
- 'memory',
181
- 'sessionStorage',
182
- 'cookies',
183
- ];
184
- const aIndex = capacityOrder.indexOf(a.name);
185
- const bIndex = capacityOrder.indexOf(b.name);
186
- return aIndex - bIndex;
187
- }
188
- /**
189
- * Update strategy
190
- */
191
- setStrategy(strategy) {
192
- this.strategy = strategy;
193
- }
194
- /**
195
- * Get current strategy
196
- */
197
- getStrategy() {
198
- return this.strategy;
199
- }
200
- }
@@ -1,48 +0,0 @@
1
- # AGENTS.md — ios/
2
-
3
- Last Updated: 2026-05-27
4
-
5
- > Agent instructions for iOS native development.
6
-
7
- ## Files
8
-
9
- | File | Purpose |
10
- |------|---------|
11
- | `Plugin/StrataStoragePlugin.swift` | Capacitor plugin entry |
12
- | `Plugin/UserDefaultsStorage.swift` | General key-value storage |
13
- | `Plugin/KeychainStorage.swift` | Secure storage |
14
- | `Plugin/SQLiteStorage.swift` | SQLite database storage — multi-store (v2.6.0), `database`/`table` options honoured, full `StorageValue` wrapper round-trip, `size(detailed)` supported |
15
- | `Plugin/FilesystemStorage.swift` | File-per-key native storage under `NSDocumentsDirectory/strata_storage/` (new in v2.6.0); atomic writes via staging rename; `isAvailable()` returns `true` |
16
-
17
- ## v2.6.0 Notes
18
-
19
- - **SQLite multi-store:** `database` option → distinct `.db` file. `table` option → sanitised table identifier `[A-Za-z0-9_]`. Previously both were ignored and all adapters shared one table.
20
- - **SQLite value shape:** `get` now returns the full `StorageValue` wrapper (`value`, `created`, `updated`, `expires`, `tags`, `metadata`). Corrupt rows are treated as a miss.
21
- - **SQLite bind safety:** text/blob binds use `SQLITE_TRANSIENT` — removes a latent use-after-free for transient Swift buffers.
22
- - **FilesystemStorage.swift:** new file. Writes are atomic (staging temp → rename). `keys()` excludes `.staging/` artifacts. `size(detailed: true)` returns `{ keys, values, metadata }`.
23
- - **Pending on-device verification** — see `docs/guides/platforms/device-verification.md`.
24
-
25
- ## Agent Rules
26
-
27
- ### Security (IRON-SOLID)
28
- - Sensitive data MUST use `KeychainStorage`
29
- - NEVER store secrets in `UserDefaultsStorage`
30
-
31
- ### SQL Safety
32
- - ALWAYS use parameterized queries in `SQLiteStorage`
33
- - NEVER string-interpolate SQL values
34
- - Use `SQLITE_TRANSIENT` for text/blob binds
35
-
36
- ### Filesystem Safety
37
- - NEVER read from `strata_storage/.staging/` — staging files are transient
38
- - Key sanitisation must be consistent between `set`, `get`, `remove`, and `keys`
39
-
40
- ### Plugin Architecture
41
- - Methods exposed through `StrataStoragePlugin.swift`
42
- - Each storage backend is a separate Swift file
43
- - Bridges Capacitor JS calls to native Swift
44
- - The `CAP_PLUGIN` macro must include every callable method name
45
-
46
- ### Before Modifying
47
- - Understand Capacitor plugin protocol
48
- - Test on iOS simulator after changes; follow device-verification guide
@@ -1,84 +0,0 @@
1
- # CLAUDE.md — ios/
2
-
3
- Last Updated: 2026-05-27
4
-
5
- ## iOS Native Plugin
6
-
7
- Swift implementation of native storage backends for Capacitor.
8
-
9
- ### Files
10
-
11
- | File | Purpose |
12
- |------|---------|
13
- | `Plugin/StrataStoragePlugin.swift` | Main Capacitor plugin entry point |
14
- | `Plugin/UserDefaultsStorage.swift` | UserDefaults-based general storage |
15
- | `Plugin/KeychainStorage.swift` | Keychain-based secure storage |
16
- | `Plugin/SQLiteStorage.swift` | SQLite database storage (multi-store, v2.6.0) |
17
- | `Plugin/FilesystemStorage.swift` | File-per-key storage under `NSDocumentsDirectory/strata_storage/` (new in v2.6.0) |
18
-
19
- ### Configuration
20
-
21
- - Pod spec: `StrataStorage.podspec` (root)
22
- - Minimum iOS version: defined in podspec
23
- - Language: Swift
24
-
25
- ## v2.6.0 Changes
26
-
27
- ### SQLite multi-store
28
- `SQLiteStorage.swift` now accepts `database` and `table` parameters from the
29
- Capacitor call options. Each unique `(database, table)` pair opens a separate
30
- `.db` file in the app's documents directory. Table identifiers are sanitised to
31
- `[A-Za-z0-9_]` before use in SQL. The full `StorageValue` wrapper is serialised
32
- to JSON and stored in a single `value` column; native `get` deserialises and
33
- returns the full wrapper so TTL, tags, and metadata survive the round-trip.
34
- Text/blob binds use `SQLITE_TRANSIENT` (removes a latent use-after-free for
35
- transient Swift buffers). `size(detailed: true)` returns per-column byte
36
- breakdown.
37
-
38
- ### FilesystemStorage.swift (new)
39
- Stores each key as `NSDocumentsDirectory/strata_storage/<sanitised-key>.json`.
40
- Writes are atomic: the value is first written to
41
- `strata_storage/.staging/<key>.tmp`, then renamed into place. Temp files live in
42
- the staging subdirectory, so they are never exposed by `keys()` and are not
43
- deleted by a targeted `remove()`. `isAvailable()` returns `true` on device.
44
- `size(detailed: true)` supported.
45
-
46
- > **Pending on-device verification** — native code is complete and reviewed; see
47
- > `docs/guides/platforms/device-verification.md` for the test matrix.
48
-
49
- ## Rules
50
-
51
- ### Security (IRON-SOLID)
52
- - Sensitive data MUST use `KeychainStorage`
53
- - NEVER store credentials, tokens, or secrets in `UserDefaultsStorage`
54
- - Keychain items should use appropriate access control flags
55
-
56
- ### Plugin Architecture
57
- - All native methods are exposed through `StrataStoragePlugin.swift`
58
- - Plugin bridges Capacitor JS calls to native Swift implementations
59
- - Each storage backend is a separate Swift file
60
- - The `CAP_PLUGIN` macro must list every callable method; missing entries cause
61
- silent `undefined` returns on the JS side
62
-
63
- ### SQLite
64
- - `SQLiteStorage.swift` opens or creates the `.db` file identified by the
65
- `database` call option (default `strata_storage.db`)
66
- - Handles table creation, migrations, and CRUD operations
67
- - Use parameterized queries — NEVER string-interpolate SQL
68
- - Use `SQLITE_TRANSIENT` for text/blob binds
69
-
70
- ### Filesystem
71
- - Key strings are sanitised before use as filenames (`/` → `_`, etc.)
72
- - Staging renames ensure atomic writes; never read from `.staging/`
73
- - `keys()` lists `.json` files only, ignoring staging artifacts
74
-
75
- ### Testing
76
- - Native code is tested through the Capacitor bridge
77
- - Test via the demo app on iOS simulator following
78
- `docs/guides/platforms/device-verification.md`
79
- - Verify all adapter methods work end-to-end
80
-
81
- ### Before Modifying
82
- - Understand the Capacitor plugin protocol
83
- - Test on iOS simulator after changes
84
- - Verify podspec still resolves
@@ -1,218 +0,0 @@
1
- import Foundation
2
- import os.log
3
-
4
- /**
5
- * Filesystem-backed storage: one file per key under
6
- * `<Documents>/strata_storage/`.
7
- *
8
- * Value-shape contract (matches src/plugin/definitions.ts, same as SQLite):
9
- * - File contents are the JSON-serialized FULL `StorageValue` wrapper
10
- * `{ value, created, updated, expires?, tags?, metadata?, ... }`.
11
- * - `get` parses the bytes back into the wrapper object; the plugin resolves
12
- * `{ value: wrapper }`. Missing file OR non-object bytes → miss (no crash).
13
- *
14
- * File naming: the storage key is percent-encoded with an allowed set that
15
- * EXCLUDES `/` (and `%`), so the encoding is reversible and never escapes the
16
- * storage directory. `decodeFileName` reverses it for `keys()`.
17
- *
18
- * Durability: writes go to a temp file in the same directory and are then
19
- * atomically replaced into place, so a crash mid-write cannot leave a torn
20
- * file at the real path.
21
- */
22
- @objc public class FilesystemStorage: NSObject {
23
- private let directory: URL
24
- private let stagingDirectory: URL
25
- private let logger = OSLog(subsystem: "com.strata.storage", category: "FilesystemStorage")
26
-
27
- /// Reserved staging subdirectory name (inside the storage dir) holding
28
- /// in-flight temp files for atomic writes. Enumeration skips it by name, so
29
- /// a temp file can never collide with an encoded key file (e.g. a real key
30
- /// literally named ".tmp-x").
31
- private static let stagingDirName = ".strata-staging"
32
-
33
- /// Characters allowed verbatim in an on-disk file name. Anything else
34
- /// (notably `/` and `%`) is percent-escaped, keeping the name reversible
35
- /// and confined to a single path component.
36
- private static let fileNameAllowed: CharacterSet = {
37
- var set = CharacterSet.alphanumerics
38
- set.insert(charactersIn: "-_. ")
39
- return set
40
- }()
41
-
42
- @objc public override init() {
43
- let base = (try? FileManager.default.url(
44
- for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true
45
- )) ?? URL(fileURLWithPath: NSTemporaryDirectory())
46
- let storageDir = base.appendingPathComponent("strata_storage", isDirectory: true)
47
- self.directory = storageDir
48
- self.stagingDirectory = storageDir.appendingPathComponent(FilesystemStorage.stagingDirName, isDirectory: true)
49
- super.init()
50
- ensureDirectory()
51
- }
52
-
53
- private func ensureDirectory() {
54
- for dir in [directory, stagingDirectory] {
55
- if !FileManager.default.fileExists(atPath: dir.path) {
56
- do {
57
- try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
58
- } catch {
59
- os_log("Failed to create filesystem storage dir: %{public}@", log: logger, type: .error, error.localizedDescription)
60
- }
61
- }
62
- }
63
- }
64
-
65
- /// Reversible encoding of a storage key → safe single-component file name.
66
- private func encodeFileName(_ key: String) -> String {
67
- // addingPercentEncoding only returns nil for invalid unichar sequences,
68
- // which a Swift String key cannot contain; fall back defensively.
69
- return key.addingPercentEncoding(withAllowedCharacters: FilesystemStorage.fileNameAllowed) ?? key
70
- }
71
-
72
- /// Reverses `encodeFileName`. Returns nil if the name cannot be decoded.
73
- private func decodeFileName(_ name: String) -> String? {
74
- return name.removingPercentEncoding
75
- }
76
-
77
- private func fileURL(forKey key: String) -> URL {
78
- return directory.appendingPathComponent(encodeFileName(key), isDirectory: false)
79
- }
80
-
81
- /**
82
- * Persist the full `StorageValue` wrapper for `key`. The wrapper is
83
- * JSON-encoded and written atomically (temp file + replace).
84
- */
85
- @objc public func set(key: String, wrapper: [String: Any]) throws -> Bool {
86
- ensureDirectory()
87
- let data = try JSONSerialization.data(withJSONObject: wrapper, options: [])
88
- let target = fileURL(forKey: key)
89
-
90
- // Atomic write: stage to a unique temp file in the reserved staging
91
- // subdir (same volume → atomic rename), then replace. The staging subdir
92
- // keeps temp names out of the key namespace entirely.
93
- let temp = stagingDirectory.appendingPathComponent(UUID().uuidString, isDirectory: false)
94
- do {
95
- try data.write(to: temp, options: .atomic)
96
- if FileManager.default.fileExists(atPath: target.path) {
97
- _ = try FileManager.default.replaceItemAt(target, withItemAt: temp)
98
- } else {
99
- try FileManager.default.moveItem(at: temp, to: target)
100
- }
101
- } catch {
102
- // Clean up the temp file on any failure so we don't leak partials.
103
- try? FileManager.default.removeItem(at: temp)
104
- throw error
105
- }
106
- return true
107
- }
108
-
109
- /**
110
- * Read the wrapper object for `key`. Missing file OR bytes that are not a
111
- * JSON object → nil (treated as a miss; never throws on corrupt data).
112
- */
113
- @objc public func get(key: String) -> [String: Any]? {
114
- let url = fileURL(forKey: key)
115
- guard let data = try? Data(contentsOf: url) else {
116
- return nil
117
- }
118
- guard let wrapper = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
119
- return nil
120
- }
121
- return wrapper
122
- }
123
-
124
- @objc public func remove(key: String) -> Bool {
125
- let url = fileURL(forKey: key)
126
- if !FileManager.default.fileExists(atPath: url.path) {
127
- return true // already absent — treat as success/idempotent
128
- }
129
- do {
130
- try FileManager.default.removeItem(at: url)
131
- return true
132
- } catch {
133
- os_log("Failed to remove filesystem key: %{public}@", log: logger, type: .error, error.localizedDescription)
134
- return false
135
- }
136
- }
137
-
138
- /// Clears stored entries. When `prefix` is set, only keys starting with it
139
- /// are removed; otherwise the whole storage directory contents are removed.
140
- @objc public func clear(prefix: String? = nil) -> Bool {
141
- let names = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []
142
- var ok = true
143
- for name in names {
144
- // Skip the staging subdirectory (never a key).
145
- if name == FilesystemStorage.stagingDirName { continue }
146
- guard let key = decodeFileName(name) else { continue }
147
- if let prefix = prefix, !key.hasPrefix(prefix) { continue }
148
- do {
149
- try FileManager.default.removeItem(at: directory.appendingPathComponent(name, isDirectory: false))
150
- } catch {
151
- ok = false
152
- }
153
- }
154
- // On a full clear, also drop any orphaned in-flight temp files.
155
- if prefix == nil, let temps = try? FileManager.default.contentsOfDirectory(atPath: stagingDirectory.path) {
156
- for temp in temps {
157
- try? FileManager.default.removeItem(at: stagingDirectory.appendingPathComponent(temp, isDirectory: false))
158
- }
159
- }
160
- return ok
161
- }
162
-
163
- /// Lists stored keys, decoding file names back to their original keys.
164
- /// When `pattern` is set, applies the same prefix/contains matching the
165
- /// other backends use.
166
- @objc public func keys(pattern: String? = nil) -> [String] {
167
- let names = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []
168
- var keys: [String] = []
169
- for name in names {
170
- if name == FilesystemStorage.stagingDirName { continue }
171
- guard let key = decodeFileName(name) else { continue }
172
- keys.append(key)
173
- }
174
- guard let pattern = pattern else { return keys }
175
- return keys.filter { $0.hasPrefix(pattern) || $0.contains(pattern) }
176
- }
177
-
178
- /**
179
- * Aggregate sizes over the storage directory.
180
- *
181
- * `count` = number of entry files; `values` = sum of file byte sizes;
182
- * `keys` = sum of decoded-key UTF-8 byte lengths; `metadata` = sum of the
183
- * serialized `metadata` segment per file (0 when absent or unparseable);
184
- * `total` = `keys` + `values`.
185
- */
186
- @objc public func size() -> [String: Int] {
187
- let names = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []
188
- var count = 0
189
- var keysSize = 0
190
- var valuesSize = 0
191
- var metadataSize = 0
192
-
193
- for name in names {
194
- if name == FilesystemStorage.stagingDirName { continue }
195
- guard let key = decodeFileName(name) else { continue }
196
- let url = directory.appendingPathComponent(name, isDirectory: false)
197
- count += 1
198
- keysSize += key.data(using: .utf8)?.count ?? 0
199
-
200
- if let data = try? Data(contentsOf: url) {
201
- valuesSize += data.count
202
- if let wrapper = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
203
- let metadata = wrapper["metadata"],
204
- let metadataData = try? JSONSerialization.data(withJSONObject: metadata, options: []) {
205
- metadataSize += metadataData.count
206
- }
207
- }
208
- }
209
-
210
- return [
211
- "count": count,
212
- "keys": keysSize,
213
- "values": valuesSize,
214
- "metadata": metadataSize,
215
- "total": keysSize + valuesSize
216
- ]
217
- }
218
- }