-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathbackfill-content-hashes.ts
More file actions
398 lines (326 loc) · 11 KB
/
Copy pathbackfill-content-hashes.ts
File metadata and controls
398 lines (326 loc) · 11 KB
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/**
* Backfill Content Hashes Script
*
* This script calculates and stores content_hash for all existing entities:
* - Pages (metadata hash)
* - PageLayers (layers + CSS hash)
* - Components (name + layers hash)
* - LayerStyles (name + classes + design hash)
* - Assets (all mutable fields hash)
* - CollectionItems (EAV values hash)
*
* Run this after the content_hash migrations have been applied.
*
* Usage: npx tsx database/scripts/backfill-content-hashes.ts
*/
import fs from 'fs';
import path from 'path';
import { createClient, SupabaseClient } from '@supabase/supabase-js';
import {
generatePageMetadataHash,
generatePageLayersHash,
generateComponentContentHash,
generateLayerStyleContentHash,
generateAssetContentHash,
generateCollectionItemContentHash,
} from '../../lib/hash-utils';
const PAGE_SIZE = 1000;
/** Create Supabase client from .credentials.json or env vars (bypasses server-only modules) */
async function getSupabaseClient(): Promise<SupabaseClient> {
const credentialsPath = path.join(process.cwd(), '.credentials.json');
if (!fs.existsSync(credentialsPath)) {
throw new Error(
'Supabase credentials not found. Please configure Supabase in the builder first.'
);
}
const credentialsFile = fs.readFileSync(credentialsPath, 'utf-8');
const credentials = JSON.parse(credentialsFile);
const config = credentials.supabase_config;
if (!config?.connectionUrl || !config?.serviceRoleKey) {
throw new Error('Invalid Supabase configuration in .credentials.json');
}
let projectUrl: string;
if (config.supabaseUrl || process.env.SUPABASE_URL) {
projectUrl = (config.supabaseUrl || process.env.SUPABASE_URL).replace(/\/+$/, '');
} else {
const match = config.connectionUrl.match(/postgres\.([^:]+)/);
if (!match) {
throw new Error(
'Could not derive Supabase API URL from connection string.\n' +
'For self-hosted instances, set SUPABASE_URL in your environment or .env file.'
);
}
projectUrl = `https://${match[1]}.supabase.co`;
}
return createClient(projectUrl, config.serviceRoleKey, {
auth: {
autoRefreshToken: false,
persistSession: false,
},
});
}
/**
* Fetch all rows matching a query using pagination.
* Supabase caps results at 1000 per request.
*/
async function fetchAllPaginated(
client: SupabaseClient,
table: string,
applyFilters: (query: any) => any,
): Promise<any[]> {
const allRows: any[] = [];
let offset = 0;
while (true) {
const baseQuery = client.from(table).select('*');
const { data, error } = await applyFilters(baseQuery)
.range(offset, offset + PAGE_SIZE - 1);
if (error) {
throw new Error(`Failed to fetch ${table}: ${error.message}`);
}
if (!data || data.length === 0) break;
allRows.push(...data);
if (data.length < PAGE_SIZE) break;
offset += PAGE_SIZE;
}
return allRows;
}
async function backfillPageHashes(client: SupabaseClient) {
console.log('Backfilling page content hashes...');
const pages = await fetchAllPaginated(client, 'pages', (q) =>
q.is('deleted_at', null).is('content_hash', null)
);
if (pages.length === 0) {
console.log(' No pages need backfilling');
return;
}
let updated = 0;
for (const page of pages) {
try {
const hash = generatePageMetadataHash({
name: page.name,
slug: page.slug,
settings: page.settings || {},
is_index: page.is_index || false,
is_dynamic: page.is_dynamic || false,
error_page: page.error_page || null,
});
const { error: updateError } = await client
.from('pages')
.update({ content_hash: hash })
.eq('id', page.id);
if (updateError) {
console.error(` Error updating page ${page.id}:`, updateError.message);
} else {
updated++;
}
} catch (error) {
console.error(` Error processing page ${page.id}:`, error);
}
}
console.log(` Updated ${updated} of ${pages.length} pages`);
}
async function backfillPageLayersHashes(client: SupabaseClient) {
console.log('Backfilling page_layers content hashes...');
const pageLayersRecords = await fetchAllPaginated(client, 'page_layers', (q) =>
q.is('deleted_at', null).is('content_hash', null)
);
if (pageLayersRecords.length === 0) {
console.log(' No page_layers need backfilling');
return;
}
let updated = 0;
for (const record of pageLayersRecords) {
try {
const hash = generatePageLayersHash({
layers: record.layers || [],
generated_css: record.generated_css || null,
});
const { error: updateError } = await client
.from('page_layers')
.update({ content_hash: hash })
.eq('id', record.id);
if (updateError) {
console.error(` Error updating page_layers ${record.id}:`, updateError.message);
} else {
updated++;
}
} catch (error) {
console.error(` Error processing page_layers ${record.id}:`, error);
}
}
console.log(` Updated ${updated} of ${pageLayersRecords.length} page_layers records`);
}
async function backfillComponentHashes(client: SupabaseClient) {
console.log('Backfilling component content hashes...');
const components = await fetchAllPaginated(client, 'components', (q) =>
q.is('content_hash', null)
);
if (components.length === 0) {
console.log(' No components need backfilling');
return;
}
let updated = 0;
for (const component of components) {
try {
const hash = generateComponentContentHash({
name: component.name,
layers: component.layers || [],
});
const { error: updateError } = await client
.from('components')
.update({ content_hash: hash })
.eq('id', component.id);
if (updateError) {
console.error(` Error updating component ${component.id}:`, updateError.message);
} else {
updated++;
}
} catch (error) {
console.error(` Error processing component ${component.id}:`, error);
}
}
console.log(` Updated ${updated} of ${components.length} components`);
}
async function backfillLayerStyleHashes(client: SupabaseClient) {
console.log('Backfilling layer_styles content hashes...');
const styles = await fetchAllPaginated(client, 'layer_styles', (q) =>
q.is('content_hash', null)
);
if (styles.length === 0) {
console.log(' No layer_styles need backfilling');
return;
}
let updated = 0;
for (const style of styles) {
try {
const hash = generateLayerStyleContentHash({
name: style.name,
classes: style.classes || '',
design: style.design || {},
});
const { error: updateError } = await client
.from('layer_styles')
.update({ content_hash: hash })
.eq('id', style.id);
if (updateError) {
console.error(` Error updating layer_style ${style.id}:`, updateError.message);
} else {
updated++;
}
} catch (error) {
console.error(` Error processing layer_style ${style.id}:`, error);
}
}
console.log(` Updated ${updated} of ${styles.length} layer_styles`);
}
async function backfillAssetHashes(client: SupabaseClient) {
console.log('Backfilling asset content hashes...');
const assets = await fetchAllPaginated(client, 'assets', (q) =>
q.is('content_hash', null).is('deleted_at', null)
);
if (assets.length === 0) {
console.log(' No assets need backfilling');
return;
}
let updated = 0;
for (const asset of assets) {
try {
const hash = generateAssetContentHash({
filename: asset.filename,
storage_path: asset.storage_path,
public_url: asset.public_url,
file_size: asset.file_size,
mime_type: asset.mime_type,
width: asset.width,
height: asset.height,
asset_folder_id: asset.asset_folder_id,
content: asset.content,
source: asset.source,
});
const { error: updateError } = await client
.from('assets')
.update({ content_hash: hash })
.eq('id', asset.id)
.eq('is_published', asset.is_published);
if (updateError) {
console.error(` Error updating asset ${asset.id}:`, updateError.message);
} else {
updated++;
}
} catch (error) {
console.error(` Error processing asset ${asset.id}:`, error);
}
}
console.log(` Updated ${updated} of ${assets.length} assets`);
}
async function backfillCollectionItemHashes(client: SupabaseClient) {
console.log('Backfilling collection_items content hashes...');
const items = await fetchAllPaginated(client, 'collection_items', (q) =>
q.is('deleted_at', null).is('content_hash', null)
);
if (items.length === 0) {
console.log(' No collection items need backfilling');
return;
}
// Batch-fetch all values for these items
const itemIds = items.map((item: any) => item.id);
// Fetch values in chunks (Supabase .in() has limits)
const CHUNK_SIZE = 200;
const allValues: any[] = [];
for (let i = 0; i < itemIds.length; i += CHUNK_SIZE) {
const chunk = itemIds.slice(i, i + CHUNK_SIZE);
const { data, error } = await client
.from('collection_item_values')
.select('item_id, field_id, value, is_published')
.in('item_id', chunk)
.is('deleted_at', null);
if (error) throw new Error(`Failed to fetch item values: ${error.message}`);
if (data) allValues.push(...data);
}
// Group values by (item_id, is_published)
const valuesMap = new Map<string, Array<{ field_id: string; value: string | null }>>();
for (const row of allValues) {
const key = `${row.item_id}:${row.is_published}`;
if (!valuesMap.has(key)) valuesMap.set(key, []);
valuesMap.get(key)!.push({ field_id: row.field_id, value: row.value });
}
let updated = 0;
for (const item of items) {
try {
const key = `${item.id}:${item.is_published}`;
const values = valuesMap.get(key) || [];
const hash = generateCollectionItemContentHash(values);
const { error: updateError } = await client
.from('collection_items')
.update({ content_hash: hash })
.eq('id', item.id)
.eq('is_published', item.is_published);
if (updateError) {
console.error(` Error updating collection_item ${item.id}:`, updateError.message);
} else {
updated++;
}
} catch (error) {
console.error(` Error processing collection_item ${item.id}:`, error);
}
}
console.log(` Updated ${updated} of ${items.length} collection items`);
}
async function main() {
console.log('Starting content hash backfill...\n');
try {
const client = await getSupabaseClient();
await backfillPageHashes(client);
await backfillPageLayersHashes(client);
await backfillComponentHashes(client);
await backfillLayerStyleHashes(client);
await backfillAssetHashes(client);
await backfillCollectionItemHashes(client);
console.log('\n✅ Content hash backfill completed successfully');
} catch (error) {
console.error('\n❌ Backfill failed:', error);
process.exit(1);
}
}
// Run the script
main();