@forklaunch/core 4.3.0 → 4.6.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.
@@ -33,6 +33,10 @@ var RetentionAction = {
33
33
  delete: "delete",
34
34
  anonymize: "anonymize"
35
35
  };
36
+ var DEFAULT_RETENTION_FROM = "createdAt";
37
+ function retentionFrom(policy) {
38
+ return policy.from ?? DEFAULT_RETENTION_FROM;
39
+ }
36
40
  var RetentionDuration = {
37
41
  days: (n) => `P${n}D`,
38
42
  months: (n) => `P${n}M`,
@@ -1530,9 +1534,22 @@ function defineComplianceEntity(meta) {
1530
1534
  registerEntityCompliance(entityName, complianceFields);
1531
1535
  if (meta.retention) {
1532
1536
  parseDuration(meta.retention.duration);
1533
- if (!resolvedProperties["createdAt"]) {
1537
+ const from = retentionFrom(meta.retention);
1538
+ const fromProperty = resolvedProperties[from];
1539
+ if (!fromProperty) {
1540
+ throw new Error(
1541
+ from === DEFAULT_RETENTION_FROM ? `Entity '${entityName}' has a retention policy but no 'createdAt' property. Retention requires createdAt to compute expiration.` : `Entity '${entityName}' has a retention policy counting from '${from}', but no '${from}' property. Add it (a nullable datetime) or count from another date property.`
1542
+ );
1543
+ }
1544
+ if (typeof fromProperty === "function") {
1545
+ throw new Error(
1546
+ `Entity '${entityName}' retention counts from '${from}', which is a relation. Count from a date property instead.`
1547
+ );
1548
+ }
1549
+ const fromLevel = complianceFields.get(from);
1550
+ if (fromLevel && fromLevel !== "none") {
1534
1551
  throw new Error(
1535
- `Entity '${entityName}' has a retention policy but no 'createdAt' property. Retention requires createdAt to compute expiration.`
1552
+ `Entity '${entityName}' retention counts from '${from}', which is classified '${fromLevel}' and therefore encrypted. Count from an unclassified (compliance('none')) date property.`
1536
1553
  );
1537
1554
  }
1538
1555
  registerEntityRetention(entityName, meta.retention);
@@ -2144,6 +2161,195 @@ async function runMigrationsWithLock(orm, options = {}) {
2144
2161
  await run();
2145
2162
  });
2146
2163
  }
2164
+
2165
+ // src/persistence/migrateOrCreateSchema.ts
2166
+ var INITIAL_STATEMENT = [
2167
+ /^create\s+table\b/,
2168
+ /^create\s+(unique\s+)?index\b/,
2169
+ /^create\s+schema\b/,
2170
+ /^create\s+type\b/,
2171
+ /^create\s+extension\b/,
2172
+ /^create\s+sequence\b/,
2173
+ /^alter\s+table\s+\S+\s+add\s+(constraint|index|unique|key|foreign\s+key|primary\s+key|fulltext|spatial)\b/,
2174
+ /^comment\s+on\b/,
2175
+ /^set\s/,
2176
+ /^pragma\s/
2177
+ ];
2178
+ var CREATE_TABLE = /^create\s+table\s+(?:if\s+not\s+exists\s+)?((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+))?)/i;
2179
+ function unquote(identifier) {
2180
+ return identifier.trim().replace(/^["`[]|["`\]]$/g, "");
2181
+ }
2182
+ function splitStatements(sql) {
2183
+ return sql.split(/;[ \t]*(?:\r?\n|$)/).map(
2184
+ (statement) => statement.replace(/--[^\n]*\n?/g, "").replace(/\/\*[\s\S]*?\*\//g, "").trim()
2185
+ ).filter(Boolean);
2186
+ }
2187
+ function queryText(query) {
2188
+ if (typeof query === "string") return query;
2189
+ if (query && typeof query.sql === "string") {
2190
+ return query.sql;
2191
+ }
2192
+ return void 0;
2193
+ }
2194
+ async function captureMigrationSql(entry, driver, config) {
2195
+ const MigrationClass = typeof entry === "function" ? entry : entry.class;
2196
+ try {
2197
+ const instance = new MigrationClass(driver, config);
2198
+ const refuse = () => {
2199
+ throw new Error("not captured");
2200
+ };
2201
+ instance.execute = refuse;
2202
+ instance.getEntityManager = refuse;
2203
+ await instance.up();
2204
+ const statements = [];
2205
+ for (const query of instance.getQueries()) {
2206
+ const text = queryText(query);
2207
+ if (text === void 0) return void 0;
2208
+ statements.push(...splitStatements(text));
2209
+ }
2210
+ return statements;
2211
+ } catch {
2212
+ return void 0;
2213
+ }
2214
+ }
2215
+ function tablesCreatedByInitialMigration(statements) {
2216
+ const tables = [];
2217
+ for (const statement of statements) {
2218
+ const lower = statement.toLowerCase();
2219
+ if (!INITIAL_STATEMENT.some((pattern) => pattern.test(lower))) {
2220
+ return void 0;
2221
+ }
2222
+ const match = CREATE_TABLE.exec(statement);
2223
+ if (match) {
2224
+ const parts = match[1].split(".").map(unquote);
2225
+ tables.push(
2226
+ parts.length === 2 ? { schema: parts[0], name: parts[1] } : { name: parts[0] }
2227
+ );
2228
+ }
2229
+ }
2230
+ return tables.length ? tables : void 0;
2231
+ }
2232
+ function migrationName(entry) {
2233
+ return typeof entry === "function" ? entry.name : entry.name ?? entry.class.name;
2234
+ }
2235
+ async function migrateOrCreateSchema(orm, options = {}) {
2236
+ const log = options.log ?? ((message) => console.log(message));
2237
+ const warn = options.warn ?? ((message) => console.warn(message));
2238
+ const result = {
2239
+ action: "nothing-to-do",
2240
+ adopted: [],
2241
+ missingTables: []
2242
+ };
2243
+ const migrator = orm.migrator ?? orm.getMigrator?.();
2244
+ if (!migrator) {
2245
+ throw new Error(
2246
+ "migrateOrCreateSchema: the ORM has no Migrator extension; add `extensions: [Migrator]` to the config"
2247
+ );
2248
+ }
2249
+ const platform = orm.em.getPlatform();
2250
+ const helper = platform.getSchemaHelper?.();
2251
+ const generator = orm.schema;
2252
+ const sql = typeof helper?.getAllTables === "function" && typeof generator?.create === "function";
2253
+ const run = async () => {
2254
+ if (!sql) {
2255
+ await migrator.up();
2256
+ result.action = "migrated";
2257
+ return;
2258
+ }
2259
+ const defaultSchema = platform.getDefaultSchemaName?.();
2260
+ const configured = orm.config.get("schema");
2261
+ const key = (schema, name) => {
2262
+ const resolved = schema ?? configured ?? defaultSchema;
2263
+ return resolved && resolved !== defaultSchema ? `${resolved}.${name}` : name;
2264
+ };
2265
+ const expected = generator.getTargetSchema().getTables().map((table) => key(table.schema, table.name));
2266
+ const existingRows = await helper.getAllTables(orm.em.getConnection());
2267
+ const existing = new Set(
2268
+ existingRows.map((row) => key(row.schema_name, row.table_name))
2269
+ );
2270
+ const present = expected.filter((table) => existing.has(table));
2271
+ const executed = await migrator.getExecuted();
2272
+ const pending = await migrator.getPending();
2273
+ if (executed.length === 0 && pending.length === 0) {
2274
+ if (expected.length === 0) return;
2275
+ if (present.length === 0) {
2276
+ warn(
2277
+ `[migrations] No migrations found and none of this service's tables exist: creating the schema from the entities (${expected.join(", ")}). Run migrate:init and commit the migrations folder so later schema changes are versioned.`
2278
+ );
2279
+ await generator.create();
2280
+ log("[migrations] Schema created from the entities.");
2281
+ result.action = "created-schema";
2282
+ } else if (present.length < expected.length) {
2283
+ result.missingTables = expected.filter((table) => !existing.has(table));
2284
+ warn(
2285
+ `[migrations] No migrations found and the database is missing tables: ${result.missingTables.join(", ")}. Some of this service's tables already exist, so nothing is created automatically. Add a migration (migrate:create) that creates them.`
2286
+ );
2287
+ }
2288
+ } else {
2289
+ if (executed.length === 0 && present.length > 0) {
2290
+ const list = orm.config.get("migrations")?.migrationsList ?? [];
2291
+ for (const migration of pending) {
2292
+ const entry = list.find(
2293
+ (candidate) => migrationName(candidate) === migration.name
2294
+ );
2295
+ if (!entry) break;
2296
+ const statements = await captureMigrationSql(
2297
+ entry,
2298
+ orm.em.getDriver(),
2299
+ orm.config
2300
+ );
2301
+ const tables = statements && tablesCreatedByInitialMigration(statements);
2302
+ if (!tables) break;
2303
+ const names = tables.map((table) => key(table.schema, table.name));
2304
+ const there = names.filter((name) => existing.has(name));
2305
+ if (there.length === 0) break;
2306
+ if (there.length < names.length) {
2307
+ throw new Error(
2308
+ `[migrations] ${migration.name} creates tables of which some already exist (${there.join(", ")}) and some do not (${names.filter((name) => !existing.has(name)).join(
2309
+ ", "
2310
+ )}). The database was not created by these migrations (an earlier deploy created it from the entities). Make this migration create only the missing tables, or record it as executed by hand once the database matches it.`
2311
+ );
2312
+ }
2313
+ const storage = migrator.getStorage?.();
2314
+ if (!storage) break;
2315
+ await storage.logMigration({ name: migration.name });
2316
+ result.adopted.push(migration.name);
2317
+ warn(
2318
+ `[migrations] ${migration.name} only creates tables that already exist (${names.join(", ")}); recorded it as executed without running it.`
2319
+ );
2320
+ }
2321
+ }
2322
+ await migrator.up();
2323
+ result.action = "migrated";
2324
+ }
2325
+ if (options.checkDrift !== false) {
2326
+ try {
2327
+ const drift = (await generator.getUpdateSchemaSQL({
2328
+ wrap: false,
2329
+ safe: true,
2330
+ dropTables: false
2331
+ })).trim();
2332
+ if (drift) {
2333
+ result.drift = drift;
2334
+ warn(
2335
+ `[migrations] The database does not match the entities. Add a migration (migrate:create) for:
2336
+ ${drift}`
2337
+ );
2338
+ }
2339
+ } catch (error) {
2340
+ warn(
2341
+ `[migrations] Could not compare the database with the entities: ${error.message}`
2342
+ );
2343
+ }
2344
+ }
2345
+ };
2346
+ await runMigrationsWithLock(orm, {
2347
+ run,
2348
+ lockName: options.lockName,
2349
+ log
2350
+ });
2351
+ return result;
2352
+ }
2147
2353
  export {
2148
2354
  Anon,
2149
2355
  BLIND_INDEX_PREFIX,
@@ -2152,6 +2358,7 @@ export {
2152
2358
  CompliantIndexType,
2153
2359
  CompliantQueryError,
2154
2360
  CompliantType,
2361
+ DEFAULT_RETENTION_FROM,
2155
2362
  DecryptionError,
2156
2363
  ENCRYPTED_PREFIXES2 as ENCRYPTED_PREFIXES,
2157
2364
  ENCRYPTION_FORMAT_ENV,
@@ -2172,6 +2379,7 @@ export {
2172
2379
  UnboundTenantError,
2173
2380
  asEncryptionSafe,
2174
2381
  assertBindableTenantId,
2382
+ captureMigrationSql,
2175
2383
  classifyEncryptedValue,
2176
2384
  collectFallbackTenantIds,
2177
2385
  countValuesByKeyId,
@@ -2196,12 +2404,14 @@ export {
2196
2404
  isCompliantField,
2197
2405
  isEncryptedCiphertext,
2198
2406
  isEncryptedValue,
2407
+ migrateOrCreateSchema,
2199
2408
  onComplianceAccess,
2200
2409
  onComplianceChange,
2201
2410
  parseDuration,
2202
2411
  parseEncryptionKeyList,
2203
2412
  reencryptEncryptedColumns,
2204
2413
  registerEncryptor,
2414
+ retentionFrom,
2205
2415
  rotationTotals,
2206
2416
  runMigrationsWithLock,
2207
2417
  sealedAnon,
@@ -2211,6 +2421,7 @@ export {
2211
2421
  stampedKeyId,
2212
2422
  stampedPrefix,
2213
2423
  subtractDuration,
2424
+ tablesCreatedByInitialMigration,
2214
2425
  withEncryptionContext,
2215
2426
  wrapEmWithForgivingDecryption,
2216
2427
  wrapEmWithNativeQueryBlocking,