@morshoto/framekit 0.1.10 → 0.1.11

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.
@@ -0,0 +1,433 @@
1
+ import { createHash } from "node:crypto";
2
+ import { execFile as execFileCallback } from "node:child_process";
3
+ import { readFile } from "node:fs/promises";
4
+ import { basename } from "node:path";
5
+ import { promisify } from "node:util";
6
+ export const FINAL_CUT_SQLITE_INSPECTION_BACKEND = "final-cut-sqlite-read-only";
7
+ export const FINAL_CUT_SQLITE_INSPECTION_TIMEOUT_MS = 30_000;
8
+ const execFile = promisify(execFileCallback);
9
+ export class FinalCutSqliteInspectionProviderError extends Error {
10
+ failure;
11
+ code;
12
+ retryable;
13
+ constructor(failure) {
14
+ super(`${failure.code}: ${failure.message}`);
15
+ this.failure = failure;
16
+ this.name = "FinalCutSqliteInspectionProviderError";
17
+ this.code = failure.code;
18
+ this.retryable = failure.retryable;
19
+ }
20
+ toJSON() {
21
+ return { ...this.failure };
22
+ }
23
+ }
24
+ /**
25
+ * Read-only inspection of Final Cut's Core Data SQLite stores.
26
+ *
27
+ * The provider intentionally returns an observation rather than ProjectSnapshot:
28
+ * the current schema exposes useful object/type/version hints, while the
29
+ * timeline payload lives in undocumented archived BLOBs.
30
+ */
31
+ export class FinalCutSqliteInspectionProvider {
32
+ backend = FINAL_CUT_SQLITE_INSPECTION_BACKEND;
33
+ executor;
34
+ digest;
35
+ timestamp;
36
+ constructor(options = {}) {
37
+ const sqliteCommand = options.sqliteCommand ?? "sqlite3";
38
+ this.executor = options.executor ?? ((databasePath, query, timeoutMs) => executeSqliteInspection(sqliteCommand, databasePath, query, timeoutMs));
39
+ this.digest = options.digest ?? hashSqliteFile;
40
+ this.timestamp = options.timestamp ?? (() => new Date().toISOString());
41
+ }
42
+ async inspect(databasePath) {
43
+ try {
44
+ const [response, digest] = await Promise.all([
45
+ this.executor(databasePath, buildFinalCutSqliteInspectionQuery(), FINAL_CUT_SQLITE_INSPECTION_TIMEOUT_MS),
46
+ this.digest(databasePath),
47
+ ]);
48
+ const parsed = parseFinalCutSqliteInspectionResponse(response);
49
+ if (parsed.status === "error")
50
+ return parsed;
51
+ const sequence = parsed.payload.collectionRows.reduce((maximum, row) => Math.max(maximum, row.optimisticVersion ?? 0), 0);
52
+ const observation = {
53
+ ...parsed.payload,
54
+ backend: this.backend,
55
+ sourcePath: databasePath,
56
+ databaseKind: databaseKindForPath(databasePath),
57
+ digest,
58
+ revision: { id: digest, sequence, timestamp: this.timestamp() },
59
+ canonical: false,
60
+ coverage: coverageFor(parsed.payload),
61
+ };
62
+ return { status: "partial", observation, issues: parsed.issues };
63
+ }
64
+ catch (error) {
65
+ return {
66
+ status: "unavailable",
67
+ error: unavailableError(error),
68
+ };
69
+ }
70
+ }
71
+ async readObservation(databasePath) {
72
+ const result = await this.inspect(databasePath);
73
+ if (result.status === "partial")
74
+ return result.observation;
75
+ throw new FinalCutSqliteInspectionProviderError(result.error);
76
+ }
77
+ }
78
+ /** Build the only SQL sent to a Final Cut store; it is schema/data read-only. */
79
+ export function buildFinalCutSqliteInspectionQuery() {
80
+ return `
81
+ PRAGMA query_only=ON;
82
+ SELECT json_object(
83
+ 'version', 1,
84
+ 'schemaVersion', (SELECT schema_version FROM pragma_schema_version LIMIT 1),
85
+ 'userVersion', (SELECT user_version FROM pragma_user_version LIMIT 1),
86
+ 'tables', COALESCE((SELECT json_group_array(json_object(
87
+ 'name', name,
88
+ 'sql', sql,
89
+ 'columns', (SELECT COALESCE(json_group_array(json_object(
90
+ 'name', p.name,
91
+ 'type', p.type,
92
+ 'primaryKey', p.pk
93
+ )), json('[]')) FROM pragma_table_info(m.name) AS p)
94
+ )) FROM (SELECT name, sql FROM sqlite_master WHERE type = 'table' ORDER BY name) AS m), json('[]')),
95
+ 'rowCounts', json_object(
96
+ 'ZCATALOGROOT', (SELECT COUNT(*) FROM ZCATALOGROOT),
97
+ 'ZCATALOGROOTMD', (SELECT COUNT(*) FROM ZCATALOGROOTMD),
98
+ 'ZCOLLECTION', (SELECT COUNT(*) FROM ZCOLLECTION),
99
+ 'ZCOLLECTIONMD', (SELECT COUNT(*) FROM ZCOLLECTIONMD),
100
+ 'Z_3CHILDCOLLECTIONS', (SELECT COUNT(*) FROM Z_3CHILDCOLLECTIONS),
101
+ 'Z_METADATA', (SELECT COUNT(*) FROM Z_METADATA),
102
+ 'Z_MODELCACHE', (SELECT COUNT(*) FROM Z_MODELCACHE),
103
+ 'Z_PRIMARYKEY', (SELECT COUNT(*) FROM Z_PRIMARYKEY)
104
+ ),
105
+ 'collectionTypes', COALESCE((SELECT json_group_array(json_object(
106
+ 'type', type,
107
+ 'count', count
108
+ )) FROM (
109
+ SELECT COALESCE(ZTYPE, '') AS type, COUNT(*) AS count
110
+ FROM ZCOLLECTION
111
+ GROUP BY ZTYPE
112
+ ORDER BY type
113
+ )), json('[]')),
114
+ 'collectionRows', COALESCE((SELECT json_group_array(json_object(
115
+ 'primaryKey', Z_PK,
116
+ 'type', ZTYPE,
117
+ 'identifier', ZIDENTIFIER,
118
+ 'optimisticVersion', Z_OPT,
119
+ 'catalogId', ZCATALOG,
120
+ 'metadataId', ZMETADATA
121
+ )) FROM (
122
+ SELECT Z_PK, ZTYPE, ZIDENTIFIER, Z_OPT, ZCATALOG, ZMETADATA
123
+ FROM ZCOLLECTION
124
+ WHERE ZTYPE LIKE 'FFMediaEventProject%'
125
+ OR ZTYPE IN ('FFAnchoredSequence', 'FFAnchoredClip', 'FFAsset', 'FFMediaRep')
126
+ ORDER BY Z_PK
127
+ )), json('[]')),
128
+ 'metadataRows', COALESCE((SELECT json_group_array(json_object(
129
+ 'primaryKey', Z_PK,
130
+ 'collectionId', ZCOLLECTION,
131
+ 'identifier', ZIDENTIFIER,
132
+ 'bytes', length(ZDICTIONARYDATA),
133
+ 'archive', CASE
134
+ WHEN substr(ZDICTIONARYDATA, 1, 8) = x'62706c6973743030' THEN 'NSKeyedArchiver'
135
+ WHEN ZDICTIONARYDATA IS NULL THEN NULL
136
+ ELSE 'opaque'
137
+ END
138
+ )) FROM (
139
+ SELECT Z_PK, ZCOLLECTION, ZIDENTIFIER, ZDICTIONARYDATA
140
+ FROM ZCOLLECTIONMD
141
+ ORDER BY Z_PK
142
+ )), json('[]'))
143
+ ) AS inspection;`;
144
+ }
145
+ export function parseFinalCutSqliteInspectionResponse(input) {
146
+ let payload;
147
+ try {
148
+ payload = typeof input === "string" ? JSON.parse(input) : input;
149
+ }
150
+ catch (error) {
151
+ return invalidResponse(`response was not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
152
+ }
153
+ const record = asRecord(payload);
154
+ if (!record)
155
+ return invalidResponse("response must be an object");
156
+ if (record.version !== 1)
157
+ return invalidResponse("version must be 1");
158
+ const schemaVersion = integerField(record.schemaVersion, "schemaVersion");
159
+ const userVersion = integerField(record.userVersion, "userVersion");
160
+ const tables = parseTables(record.tables);
161
+ const rowCounts = parseNumberMap(record.rowCounts, "rowCounts");
162
+ const collectionTypes = parseCollectionTypes(record.collectionTypes);
163
+ const collectionRows = parseCollectionRows(record.collectionRows);
164
+ const metadataRows = parseMetadataRows(record.metadataRows);
165
+ const firstFailure = [schemaVersion, userVersion]
166
+ .find((value) => isParseFailure(value));
167
+ if (firstFailure || typeof tables === "string" || typeof rowCounts === "string"
168
+ || typeof collectionTypes === "string" || typeof collectionRows === "string" || typeof metadataRows === "string") {
169
+ return invalidResponse(firstFailure?.message
170
+ ?? [tables, rowCounts, collectionTypes, collectionRows, metadataRows]
171
+ .find((value) => typeof value === "string")
172
+ ?? "unknown validation failure");
173
+ }
174
+ return {
175
+ status: "partial",
176
+ payload: {
177
+ version: 1,
178
+ schemaVersion: schemaVersion,
179
+ userVersion: userVersion,
180
+ tables,
181
+ rowCounts,
182
+ collectionTypes,
183
+ collectionRows,
184
+ metadataRows,
185
+ },
186
+ issues: [
187
+ {
188
+ code: "FINAL_CUT_SQLITE_OPAQUE_PAYLOAD",
189
+ message: "ZCOLLECTIONMD.ZDICTIONARYDATA is an undocumented archived payload; timeline fields are not promoted to canonical state",
190
+ path: "ZCOLLECTIONMD.ZDICTIONARYDATA",
191
+ retryable: false,
192
+ },
193
+ {
194
+ code: "FINAL_CUT_SQLITE_REVISION_UNAVAILABLE",
195
+ message: "SQLite digest and Z_OPT provide storage-change evidence, not a target-bound Final Cut editor revision",
196
+ path: "revision",
197
+ retryable: false,
198
+ },
199
+ ],
200
+ };
201
+ }
202
+ export function compareFinalCutSqliteObservations(previous, current) {
203
+ const reasons = [];
204
+ if (previous.digest !== current.digest)
205
+ reasons.push("SQLite file digest changed");
206
+ if (previous.schemaVersion !== current.schemaVersion)
207
+ reasons.push("SQLite schema version changed");
208
+ if (previous.revision.sequence !== current.revision.sequence)
209
+ reasons.push("SQLite object version changed");
210
+ return {
211
+ status: reasons.length > 0 ? "changed" : "unchanged",
212
+ previousDigest: previous.digest,
213
+ currentDigest: current.digest,
214
+ reasons,
215
+ };
216
+ }
217
+ async function executeSqliteInspection(sqliteCommand, databasePath, query, timeoutMs) {
218
+ const result = await execFile(sqliteCommand, ["-readonly", "-batch", "-noheader", databasePath, query], {
219
+ maxBuffer: 8_000_000,
220
+ timeout: timeoutMs,
221
+ });
222
+ return result.stdout.trim();
223
+ }
224
+ async function hashSqliteFile(databasePath) {
225
+ const bytes = await readFile(databasePath);
226
+ return createHash("sha256").update(bytes).digest("hex");
227
+ }
228
+ function databaseKindForPath(databasePath) {
229
+ const fileName = basename(databasePath);
230
+ if (fileName === "CurrentVersion.flexolibrary")
231
+ return "flexolibrary";
232
+ if (fileName === "CurrentVersion.fcpevent")
233
+ return "fcpevent";
234
+ return "unknown";
235
+ }
236
+ function coverageFor(payload) {
237
+ const hasProject = payload.collectionTypes.some(({ type }) => type === "FFMediaEventProject");
238
+ const hasMedia = payload.collectionTypes.some(({ type }) => ["FFAsset", "FFMediaRep"].includes(type));
239
+ return {
240
+ complete: false,
241
+ projectIdentity: hasProject ? "partial" : "unknown",
242
+ sequenceIdentity: "unknown",
243
+ clipOccurrences: "unknown",
244
+ mediaIdentity: hasMedia ? "partial" : "unknown",
245
+ rationalTiming: "unknown",
246
+ roles: "unknown",
247
+ storylineRelationships: "unknown",
248
+ markersCaptions: "unknown",
249
+ revision: "partial",
250
+ };
251
+ }
252
+ function unavailableError(error) {
253
+ const message = error instanceof Error ? error.message : String(error);
254
+ return {
255
+ code: "FINAL_CUT_SQLITE_INSPECTION_UNAVAILABLE",
256
+ message: `Final Cut SQLite inspection is unavailable: ${message}`,
257
+ retryable: /busy|locked|timed out|timeout|temporar/i.test(message),
258
+ };
259
+ }
260
+ function invalidResponse(message) {
261
+ return {
262
+ status: "error",
263
+ error: {
264
+ code: "FINAL_CUT_SQLITE_RESPONSE_INVALID",
265
+ message: `Final Cut SQLite response is invalid: ${message}`,
266
+ retryable: false,
267
+ },
268
+ };
269
+ }
270
+ function parseTables(value) {
271
+ if (!Array.isArray(value))
272
+ return "tables must be an array";
273
+ const result = [];
274
+ for (const [index, item] of value.entries()) {
275
+ const record = asRecord(item);
276
+ if (!record)
277
+ return `tables[${index}] must be an object`;
278
+ const name = textField(record.name, `tables[${index}].name`);
279
+ const sql = textField(record.sql, `tables[${index}].sql`);
280
+ const columns = parseColumns(record.columns, `tables[${index}].columns`);
281
+ if (isParseFailure(name) || isParseFailure(sql) || typeof columns === "string") {
282
+ return isParseFailure(name) ? name.message
283
+ : isParseFailure(sql) ? sql.message : columns;
284
+ }
285
+ result.push({ name, sql, columns });
286
+ }
287
+ return result;
288
+ }
289
+ function parseColumns(value, path) {
290
+ if (!Array.isArray(value))
291
+ return `${path} must be an array`;
292
+ const result = [];
293
+ for (const [index, item] of value.entries()) {
294
+ const record = asRecord(item);
295
+ if (!record)
296
+ return `${path}[${index}] must be an object`;
297
+ const name = textField(record.name, `${path}[${index}].name`);
298
+ const type = textField(record.type, `${path}[${index}].type`);
299
+ const primaryKey = integerField(record.primaryKey, `${path}[${index}].primaryKey`);
300
+ if (isParseFailure(name) || isParseFailure(type) || isParseFailure(primaryKey)) {
301
+ return isParseFailure(name) ? name.message
302
+ : isParseFailure(type) ? type.message : primaryKey.message;
303
+ }
304
+ result.push({ name, type, primaryKey });
305
+ }
306
+ return result;
307
+ }
308
+ function parseNumberMap(value, path) {
309
+ const record = asRecord(value);
310
+ if (!record)
311
+ return `${path} must be an object`;
312
+ const result = {};
313
+ for (const [key, item] of Object.entries(record)) {
314
+ const number = integerField(item, `${path}.${key}`);
315
+ if (isParseFailure(number))
316
+ return number.message;
317
+ result[key] = number;
318
+ }
319
+ return result;
320
+ }
321
+ function parseCollectionTypes(value) {
322
+ if (!Array.isArray(value))
323
+ return "collectionTypes must be an array";
324
+ const result = [];
325
+ for (const [index, item] of value.entries()) {
326
+ const record = asRecord(item);
327
+ if (!record)
328
+ return `collectionTypes[${index}] must be an object`;
329
+ const type = textField(record.type, `collectionTypes[${index}].type`);
330
+ const count = integerField(record.count, `collectionTypes[${index}].count`);
331
+ if (isParseFailure(type) || isParseFailure(count)) {
332
+ return isParseFailure(type) ? type.message : count.message;
333
+ }
334
+ result.push({ type, count });
335
+ }
336
+ return result;
337
+ }
338
+ function parseCollectionRows(value) {
339
+ if (!Array.isArray(value))
340
+ return "collectionRows must be an array";
341
+ const result = [];
342
+ for (const [index, item] of value.entries()) {
343
+ const record = asRecord(item);
344
+ if (!record)
345
+ return `collectionRows[${index}] must be an object`;
346
+ const primaryKey = integerField(record.primaryKey, `collectionRows[${index}].primaryKey`);
347
+ const type = textField(record.type, `collectionRows[${index}].type`);
348
+ if (isParseFailure(primaryKey) || isParseFailure(type)) {
349
+ return isParseFailure(primaryKey) ? primaryKey.message : type.message;
350
+ }
351
+ const identifier = optionalText(record.identifier, `collectionRows[${index}].identifier`);
352
+ const optimisticVersion = optionalNumber(record.optimisticVersion, `collectionRows[${index}].optimisticVersion`);
353
+ const catalogId = optionalNumber(record.catalogId, `collectionRows[${index}].catalogId`);
354
+ const metadataId = optionalNumber(record.metadataId, `collectionRows[${index}].metadataId`);
355
+ if (isParseFailure(identifier))
356
+ return identifier.message;
357
+ if (isParseFailure(optimisticVersion))
358
+ return optimisticVersion.message;
359
+ if (isParseFailure(catalogId))
360
+ return catalogId.message;
361
+ if (isParseFailure(metadataId))
362
+ return metadataId.message;
363
+ result.push({
364
+ primaryKey,
365
+ type,
366
+ ...(typeof identifier === "string" ? { identifier } : {}),
367
+ ...(typeof optimisticVersion === "number" ? { optimisticVersion } : {}),
368
+ ...(typeof catalogId === "number" ? { catalogId } : {}),
369
+ ...(typeof metadataId === "number" ? { metadataId } : {}),
370
+ });
371
+ }
372
+ return result;
373
+ }
374
+ function parseMetadataRows(value) {
375
+ if (!Array.isArray(value))
376
+ return "metadataRows must be an array";
377
+ const result = [];
378
+ for (const [index, item] of value.entries()) {
379
+ const record = asRecord(item);
380
+ if (!record)
381
+ return `metadataRows[${index}] must be an object`;
382
+ const primaryKey = integerField(record.primaryKey, `metadataRows[${index}].primaryKey`);
383
+ const bytes = integerField(record.bytes, `metadataRows[${index}].bytes`);
384
+ if (isParseFailure(primaryKey) || isParseFailure(bytes)) {
385
+ return isParseFailure(primaryKey) ? primaryKey.message : bytes.message;
386
+ }
387
+ const collectionId = optionalNumber(record.collectionId, `metadataRows[${index}].collectionId`);
388
+ const identifier = optionalText(record.identifier, `metadataRows[${index}].identifier`);
389
+ const archive = optionalText(record.archive, `metadataRows[${index}].archive`);
390
+ if (isParseFailure(collectionId))
391
+ return collectionId.message;
392
+ if (isParseFailure(identifier))
393
+ return identifier.message;
394
+ if (isParseFailure(archive))
395
+ return archive.message;
396
+ result.push({
397
+ primaryKey,
398
+ bytes,
399
+ ...(typeof collectionId === "number" ? { collectionId } : {}),
400
+ ...(typeof identifier === "string" ? { identifier } : {}),
401
+ ...(typeof archive === "string" ? { archive } : {}),
402
+ });
403
+ }
404
+ return result;
405
+ }
406
+ function optionalText(value, path) {
407
+ if (value === undefined || value === null)
408
+ return undefined;
409
+ if (typeof value !== "string")
410
+ return failure(`${path} must be a string or null`);
411
+ return value;
412
+ }
413
+ function optionalNumber(value, path) {
414
+ if (value === undefined || value === null)
415
+ return undefined;
416
+ const number = integerField(value, path);
417
+ return isParseFailure(number) ? number : number;
418
+ }
419
+ function textField(value, path) {
420
+ return typeof value === "string" ? value : failure(`${path} must be a string`);
421
+ }
422
+ function integerField(value, path) {
423
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : failure(`${path} must be a safe integer`);
424
+ }
425
+ function failure(message) {
426
+ return { parseFailure: true, message };
427
+ }
428
+ function isParseFailure(value) {
429
+ return Boolean(value && typeof value === "object" && value.parseFailure === true);
430
+ }
431
+ function asRecord(value) {
432
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
433
+ }