File size: 12,878 Bytes
77bd40d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/**
 * Debug utility for validating Date object preservation in Unity cloud saves
 *
 * This script helps verify that JavaScript Date objects are properly preserved
 * through the JSON serialization/deserialization cycle.
 *
 * Usage:
 * 1. Include this script in the browser console
 * 2. Call validateDatePreservation() after playing a Unity game
 * 3. Check the console output for validation results
 */

(function() {
    'use strict';

    /**
     * Test the JSON serialization/deserialization with Date objects
     */
    function testDateSerialization() {
        console.group('πŸ§ͺ Testing Date Object Serialization');

        // Create test data similar to Unity save records
        const testData = [
            {
                key: '/idbfs/PlayerPrefs',
                value: new Uint8Array([1, 2, 3, 4, 5]),
                timestamp: new Date('2025-11-13T10:30:00.000Z'),
                mode: 33206
            },
            {
                key: '/idbfs/data.unity3d',
                value: new Uint8Array([10, 20, 30]),
                timestamp: new Date('2025-11-13T10:31:15.500Z'),
                mode: 33188
            }
        ];

        console.log('Original data:', testData);
        console.log('First timestamp is Date:', testData[0].timestamp instanceof Date);
        console.log('Can call .getTime():', testData[0].timestamp.getTime());

        // Test serialization with custom replacer
        const serialized = JSON.stringify(testData, (key, value) => {
            if (value instanceof Date) {
                console.log('  β†’ Replacing Date object:', value.toISOString());
                return { __date__: value.toISOString() };
            }
            return value;
        });

        console.log('Serialized:', serialized);

        // Test deserialization with custom reviver
        const deserialized = JSON.parse(serialized, (key, value) => {
            if (value && typeof value === 'object' && value.__date__) {
                console.log('  β†’ Restoring Date object from:', value.__date__);
                return new Date(value.__date__);
            }
            return value;
        });

        console.log('Deserialized data:', deserialized);
        console.log('First timestamp is Date:', deserialized[0].timestamp instanceof Date);

        if (deserialized[0].timestamp instanceof Date) {
            console.log('βœ… Date object successfully preserved!');
            console.log('Can call .getTime():', deserialized[0].timestamp.getTime());
        } else {
            console.error('❌ Date object NOT preserved!');
            console.error('Type:', typeof deserialized[0].timestamp);
            console.error('Value:', deserialized[0].timestamp);
        }

        console.groupEnd();

        return deserialized[0].timestamp instanceof Date;
    }

    /**
     * Validate Date objects in actual Unity IndexedDB data
     */
    async function validateUnityIndexedDB() {
        console.group('πŸ” Validating Unity IndexedDB Data');

        return new Promise((resolve) => {
            const request = indexedDB.open('/idbfs');

            request.onerror = () => {
                console.error('❌ Failed to open Unity database');
                console.groupEnd();
                resolve(false);
            };

            request.onsuccess = (e) => {
                const db = e.target.result;

                if (!db.objectStoreNames.contains('FILE_DATA')) {
                    console.warn('⚠️ FILE_DATA store not found');
                    console.groupEnd();
                    resolve(false);
                    return;
                }

                const tx = db.transaction('FILE_DATA', 'readonly');
                const store = tx.objectStore('FILE_DATA');
                const getAllRequest = store.getAll();

                getAllRequest.onsuccess = (e2) => {
                    const records = e2.target.result;
                    console.log(`Found ${records.length} records in FILE_DATA`);

                    let dateCount = 0;
                    let validDates = 0;
                    let invalidDates = 0;

                    records.forEach((record, index) => {
                        if (record.timestamp) {
                            dateCount++;
                            const isDate = record.timestamp instanceof Date;

                            console.log(`Record ${index}:`, {
                                key: record.key,
                                hasTimestamp: true,
                                isDate: isDate,
                                type: typeof record.timestamp,
                                value: record.timestamp
                            });

                            if (isDate) {
                                validDates++;
                                try {
                                    const time = record.timestamp.getTime();
                                    console.log('  βœ… .getTime() works:', time);
                                } catch (err) {
                                    console.error('  ❌ .getTime() failed:', err);
                                    invalidDates++;
                                }
                            } else {
                                invalidDates++;
                                console.error('  ❌ timestamp is not a Date object');
                            }
                        }
                    });

                    console.log('\nπŸ“Š Summary:');
                    console.log(`  Total records: ${records.length}`);
                    console.log(`  Records with timestamp: ${dateCount}`);
                    console.log(`  Valid Date objects: ${validDates}`);
                    console.log(`  Invalid Date objects: ${invalidDates}`);

                    if (invalidDates === 0 && dateCount > 0) {
                        console.log('  βœ… ALL timestamp fields are valid Date objects!');
                    } else if (invalidDates > 0) {
                        console.error('  ❌ Some timestamp fields are NOT Date objects!');
                    }

                    console.groupEnd();
                    resolve(invalidDates === 0);
                };

                getAllRequest.onerror = () => {
                    console.error('❌ Failed to read FILE_DATA');
                    console.groupEnd();
                    resolve(false);
                };
            };
        });
    }

    /**
     * Check what's stored on the backend for the current game
     */
    async function checkBackendData(gameId) {
        console.group('☁️ Checking Backend Data');

        const token = localStorage.getItem('edurocks_auth_token');
        if (!token) {
            console.error('❌ Not logged in - no auth token');
            console.groupEnd();
            return;
        }

        try {
            const response = await fetch(
                `https://backendapi.edurocks.org/userauth/game-api.php?action=getSaves&gameId=${gameId}&token=${token}`,
                { credentials: 'include' }
            );

            const result = await response.json();
            console.log('Backend response:', result);

            if (!result.success) {
                console.error('❌ Failed to fetch saves:', result.message);
                console.groupEnd();
                return;
            }

            const saves = result.saves || {};
            const saveKeys = Object.keys(saves);
            console.log(`Found ${saveKeys.length} save keys`);

            for (const key of saveKeys) {
                console.log(`\nSave key: ${key}`);

                if (key.startsWith('indexedDB:')) {
                    try {
                        // Parse with custom reviver
                        const data = JSON.parse(saves[key], (k, v) => {
                            if (v && typeof v === 'object' && v.__date__) {
                                return new Date(v.__date__);
                            }
                            return v;
                        });

                        console.log(`  Records: ${data.length}`);

                        // Check first record
                        if (data.length > 0 && data[0].timestamp) {
                            const isDate = data[0].timestamp instanceof Date;
                            console.log(`  First record timestamp is Date: ${isDate}`);

                            if (isDate) {
                                console.log('  βœ… Date object properly restored from backend');
                            } else {
                                console.error('  ❌ Date object NOT restored from backend');
                                console.error('  Type:', typeof data[0].timestamp);
                                console.error('  Value:', data[0].timestamp);
                            }
                        }

                        // Check for __date__ markers in raw JSON
                        const rawData = saves[key];
                        if (rawData.includes('"__date__"')) {
                            console.log('  βœ… Backend data contains __date__ markers (serialization working)');
                        } else {
                            console.warn('  ⚠️ Backend data missing __date__ markers (may have Date issues)');
                        }

                    } catch (err) {
                        console.error('  ❌ Failed to parse save data:', err);
                    }
                }
            }

            console.groupEnd();
        } catch (err) {
            console.error('❌ Network error:', err);
            console.groupEnd();
        }
    }

    /**
     * Main validation function - runs all tests
     */
    async function validateDatePreservation(gameId) {
        console.clear();
        console.log('πŸ”¬ Date Object Preservation Validation\n');

        // Test 1: Serialization/Deserialization
        const serializationWorks = testDateSerialization();
        console.log('\n');

        // Test 2: IndexedDB validation
        const indexedDBValid = await validateUnityIndexedDB();
        console.log('\n');

        // Test 3: Backend data validation
        if (gameId) {
            await checkBackendData(gameId);
        } else {
            console.warn('⚠️ No gameId provided, skipping backend validation');
            console.log('   Usage: validateDatePreservation("highway-racer-2")');
        }

        // Final summary
        console.log('\n' + '='.repeat(60));
        console.log('πŸ“‹ VALIDATION SUMMARY');
        console.log('='.repeat(60));
        console.log(`Serialization test: ${serializationWorks ? 'βœ… PASS' : '❌ FAIL'}`);
        console.log(`IndexedDB validation: ${indexedDBValid ? 'βœ… PASS' : '❌ FAIL'}`);

        if (serializationWorks && indexedDBValid) {
            console.log('\nπŸŽ‰ ALL TESTS PASSED - Date preservation is working correctly!');
        } else {
            console.log('\n⚠️ SOME TESTS FAILED - Date preservation may have issues');
        }
        console.log('='.repeat(60));
    }

    /**
     * Quick check for current save sync status
     */
    function checkSaveSyncStatus() {
        console.group('πŸ“Š Save Sync Status');

        if (window.EDUrocksSaveSync) {
            const info = window.EDUrocksSaveSync.debugInfo();
            console.log('Save Sync Active: βœ…');
            console.log('Game ID:', info.gameId);
            console.log('Logged In:', info.isLoggedIn);
            console.log('Open Databases:', info.openDatabases);

            if (info.savedIndexedDBData) {
                console.log('Queued IndexedDB saves:', info.savedIndexedDBData.size);
            }
        } else {
            console.error('Save Sync NOT Active: ❌');
            console.log('Make sure you are on a game page with cloud save enabled');
        }

        console.groupEnd();
    }

    // Expose functions to window for console access
    window.debugDatePreservation = {
        validate: validateDatePreservation,
        testSerialization: testDateSerialization,
        checkIndexedDB: validateUnityIndexedDB,
        checkBackend: checkBackendData,
        checkStatus: checkSaveSyncStatus
    };

    console.log('πŸ› οΈ Date Preservation Debug Tools Loaded');
    console.log('Available commands:');
    console.log('  debugDatePreservation.validate("game-id") - Run full validation');
    console.log('  debugDatePreservation.testSerialization() - Test JSON serialization');
    console.log('  debugDatePreservation.checkIndexedDB() - Check Unity IndexedDB');
    console.log('  debugDatePreservation.checkBackend("game-id") - Check backend data');
    console.log('  debugDatePreservation.checkStatus() - Check save sync status');
})();