monorise 1.8.0-dev.0 → 1.9.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 (82) hide show
  1. package/dist/base/index.d.ts +38 -4
  2. package/dist/base/index.js +28 -8
  3. package/dist/base/index.js.map +1 -1
  4. package/dist/cli/cli.js +239 -153
  5. package/dist/cli/cli.js.map +1 -1
  6. package/dist/cli/templates/files/proxy-request.ts +2 -1
  7. package/dist/cli/templates/files/sst.config.ts +5 -4
  8. package/dist/core/index.d.ts +54 -12
  9. package/dist/core/index.js +504 -145
  10. package/dist/core/index.js.map +1 -1
  11. package/dist/index.d.ts +107 -4
  12. package/dist/react/actions/config.action.d.ts +2 -2
  13. package/dist/react/actions/core.action.d.ts.map +1 -1
  14. package/dist/react/helpers/transactional.d.ts +40 -0
  15. package/dist/react/helpers/transactional.d.ts.map +1 -0
  16. package/dist/react/index.d.ts +7 -20
  17. package/dist/react/index.d.ts.map +1 -1
  18. package/dist/react/index.js +390 -25645
  19. package/dist/react/index.js.map +1 -1
  20. package/dist/react/lib/utils.d.ts +7 -0
  21. package/dist/react/lib/utils.d.ts.map +1 -1
  22. package/dist/react/services/core.service.d.ts +2 -8
  23. package/dist/react/services/core.service.d.ts.map +1 -1
  24. package/dist/sst/components/analytics.d.ts +26 -6
  25. package/dist/sst/components/analytics.d.ts.map +1 -1
  26. package/dist/sst/components/monorise-core.d.ts +1 -0
  27. package/dist/sst/components/monorise-core.d.ts.map +1 -1
  28. package/dist/sst/components/single-table.d.ts +1 -0
  29. package/dist/sst/components/single-table.d.ts.map +1 -1
  30. package/dist/sst/index.js +173 -67
  31. package/dist/sst/index.js.map +1 -1
  32. package/package.json +3 -3
  33. package/dist/react/bowser-RUCNDTEX.js +0 -2822
  34. package/dist/react/bowser-RUCNDTEX.js.map +0 -1
  35. package/dist/react/chunk-2U2REJF4.js +0 -138
  36. package/dist/react/chunk-2U2REJF4.js.map +0 -1
  37. package/dist/react/chunk-5CPIG7AN.js +0 -449
  38. package/dist/react/chunk-5CPIG7AN.js.map +0 -1
  39. package/dist/react/chunk-7BSJSLIL.js +0 -528
  40. package/dist/react/chunk-7BSJSLIL.js.map +0 -1
  41. package/dist/react/chunk-7MNBSDJI.js +0 -3362
  42. package/dist/react/chunk-7MNBSDJI.js.map +0 -1
  43. package/dist/react/chunk-JXBFOCBM.js +0 -2929
  44. package/dist/react/chunk-JXBFOCBM.js.map +0 -1
  45. package/dist/react/chunk-MIXAYX55.js +0 -147
  46. package/dist/react/chunk-MIXAYX55.js.map +0 -1
  47. package/dist/react/chunk-Q26JGAFF.js +0 -47
  48. package/dist/react/chunk-Q26JGAFF.js.map +0 -1
  49. package/dist/react/chunk-QZSEUOCY.js +0 -2298
  50. package/dist/react/chunk-QZSEUOCY.js.map +0 -1
  51. package/dist/react/chunk-W6S3JWZV.js +0 -1045
  52. package/dist/react/chunk-W6S3JWZV.js.map +0 -1
  53. package/dist/react/chunk-WUOPYF3V.js +0 -127
  54. package/dist/react/chunk-WUOPYF3V.js.map +0 -1
  55. package/dist/react/chunk-Z45ECZFO.js +0 -995
  56. package/dist/react/chunk-Z45ECZFO.js.map +0 -1
  57. package/dist/react/dist-es-2P6AKQM3.js +0 -325
  58. package/dist/react/dist-es-2P6AKQM3.js.map +0 -1
  59. package/dist/react/dist-es-CEMZ6HT6.js +0 -294
  60. package/dist/react/dist-es-CEMZ6HT6.js.map +0 -1
  61. package/dist/react/dist-es-NZWWHEBR.js +0 -89
  62. package/dist/react/dist-es-NZWWHEBR.js.map +0 -1
  63. package/dist/react/dist-es-QVQ2CPIM.js +0 -376
  64. package/dist/react/dist-es-QVQ2CPIM.js.map +0 -1
  65. package/dist/react/dist-es-VBWII54H.js +0 -70
  66. package/dist/react/dist-es-VBWII54H.js.map +0 -1
  67. package/dist/react/dist-es-VXN7IC3J.js +0 -23
  68. package/dist/react/dist-es-VXN7IC3J.js.map +0 -1
  69. package/dist/react/dist-es-YKVDPOOB.js +0 -221
  70. package/dist/react/dist-es-YKVDPOOB.js.map +0 -1
  71. package/dist/react/dist-es-ZPOY2Z6R.js +0 -178
  72. package/dist/react/dist-es-ZPOY2Z6R.js.map +0 -1
  73. package/dist/react/event-streams-NBH35WQC.js +0 -44
  74. package/dist/react/event-streams-NBH35WQC.js.map +0 -1
  75. package/dist/react/loadSso-2GPAQE3H.js +0 -583
  76. package/dist/react/loadSso-2GPAQE3H.js.map +0 -1
  77. package/dist/react/signin-HT4EDHQE.js +0 -821
  78. package/dist/react/signin-HT4EDHQE.js.map +0 -1
  79. package/dist/react/sso-oidc-WA3BK6FI.js +0 -830
  80. package/dist/react/sso-oidc-WA3BK6FI.js.map +0 -1
  81. package/dist/react/sts-V7PNNQ2L.js +0 -1114
  82. package/dist/react/sts-V7PNNQ2L.js.map +0 -1
@@ -2315,6 +2315,166 @@ var appHandler = (container) => ({ routes }) => {
2315
2315
  return handle(app);
2316
2316
  };
2317
2317
 
2318
+ // handles/analytics-query.ts
2319
+ import {
2320
+ AthenaClient,
2321
+ GetQueryExecutionCommand,
2322
+ GetQueryResultsCommand,
2323
+ StartQueryExecutionCommand,
2324
+ StopQueryExecutionCommand
2325
+ } from "@aws-sdk/client-athena";
2326
+ import { DynamoDBClient, GetItemCommand, PutItemCommand } from "@aws-sdk/client-dynamodb";
2327
+ import { createHash } from "crypto";
2328
+ import { handle as handle2 } from "hono/aws-lambda";
2329
+ import { Hono as Hono3 } from "hono";
2330
+ import httpStatus4 from "http-status";
2331
+ var athena = new AthenaClient();
2332
+ var dynamo = new DynamoDBClient();
2333
+ function required(name) {
2334
+ const value = process.env[name];
2335
+ if (!value) throw new Error(`${name} is required.`);
2336
+ return value;
2337
+ }
2338
+ function queries() {
2339
+ return JSON.parse(required("ANALYTICS_QUERIES"));
2340
+ }
2341
+ function validParameter(value, type) {
2342
+ if (type === "string" && typeof value === "string") return value;
2343
+ if (type === "number" && typeof value === "number" && Number.isFinite(value)) return String(value);
2344
+ if (type === "boolean" && typeof value === "boolean") return String(value);
2345
+ if (type === "date" && typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
2346
+ if (type === "timestamp" && typeof value === "string" && !Number.isNaN(Date.parse(value))) return value;
2347
+ return void 0;
2348
+ }
2349
+ function executionParameter(value, type) {
2350
+ if (type === "string") return `'${value.replaceAll("'", "''")}'`;
2351
+ if (type === "date") return `DATE '${value}'`;
2352
+ if (type === "timestamp") return `TIMESTAMP '${value.replaceAll("'", "''")}'`;
2353
+ return value;
2354
+ }
2355
+ function apiKeys() {
2356
+ return process.env.ANALYTICS_API_KEYS ? JSON.parse(process.env.ANALYTICS_API_KEYS) : [];
2357
+ }
2358
+ function keyFingerprint(key) {
2359
+ return createHash("sha256").update(key).digest("hex");
2360
+ }
2361
+ function ownedExecution(id, key) {
2362
+ return __async(this, null, function* () {
2363
+ var _a, _b;
2364
+ const item = yield dynamo.send(new GetItemCommand({
2365
+ TableName: required("ANALYTICS_EXECUTIONS_TABLE"),
2366
+ Key: { id: { S: id } },
2367
+ ConsistentRead: true
2368
+ }));
2369
+ return ((_b = (_a = item.Item) == null ? void 0 : _a.ownerKeyHash) == null ? void 0 : _b.S) === keyFingerprint(key);
2370
+ });
2371
+ }
2372
+ var analyticsQueryHandler = () => {
2373
+ const app = new Hono3().basePath("/analytics");
2374
+ app.use("*", (c, next) => __async(null, null, function* () {
2375
+ const key = c.req.header("x-api-key");
2376
+ if (!key || !apiKeys().includes(key)) {
2377
+ return c.json({ status: httpStatus4.UNAUTHORIZED, message: httpStatus4["401_MESSAGE"] }, httpStatus4.UNAUTHORIZED);
2378
+ }
2379
+ return next();
2380
+ }));
2381
+ app.get("/queries", (c) => c.json({
2382
+ queries: Object.entries(queries()).map(([name, query]) => {
2383
+ var _a;
2384
+ return { name, parameters: (_a = query.parameters) != null ? _a : {} };
2385
+ })
2386
+ }));
2387
+ app.post("/queries/:name/executions", (c) => __async(null, null, function* () {
2388
+ var _a, _b;
2389
+ const query = queries()[c.req.param("name")];
2390
+ if (!query) return c.json({ message: "Unknown analytics query." }, httpStatus4.NOT_FOUND);
2391
+ const body = yield c.req.json().catch(() => ({}));
2392
+ const declared = (_a = query.parameters) != null ? _a : {};
2393
+ if (Object.keys(body).some((name) => !(name in declared))) {
2394
+ return c.json({ message: "Unexpected query parameter." }, httpStatus4.BAD_REQUEST);
2395
+ }
2396
+ try {
2397
+ const parameters = Object.entries(declared).map(([name, definition]) => {
2398
+ const value = validParameter(body[name], definition.type);
2399
+ if (value === void 0) throw new Error(`Invalid or missing parameter: ${name}.`);
2400
+ return executionParameter(value, definition.type);
2401
+ });
2402
+ const started = yield athena.send(new StartQueryExecutionCommand({
2403
+ QueryString: query.sql,
2404
+ ExecutionParameters: parameters,
2405
+ WorkGroup: required("ANALYTICS_WORKGROUP"),
2406
+ QueryExecutionContext: { Database: required("ANALYTICS_DATABASE") },
2407
+ ResultConfiguration: { OutputLocation: required("ANALYTICS_ATHENA_OUTPUT") },
2408
+ ResultReuseConfiguration: query.resultReuse ? { ResultReuseByAgeConfiguration: { Enabled: true, MaxAgeInMinutes: query.resultReuse.maxAgeMinutes } } : void 0
2409
+ }));
2410
+ if (!started.QueryExecutionId) throw new Error("Athena did not return a query execution id.");
2411
+ yield dynamo.send(new PutItemCommand({
2412
+ TableName: required("ANALYTICS_EXECUTIONS_TABLE"),
2413
+ Item: {
2414
+ id: { S: started.QueryExecutionId },
2415
+ queryName: { S: c.req.param("name") },
2416
+ ownerKeyHash: { S: keyFingerprint((_b = c.req.header("x-api-key")) != null ? _b : "") },
2417
+ expiresAt: { N: String(Math.floor(Date.now() / 1e3) + 86400) }
2418
+ }
2419
+ }));
2420
+ return c.json({ queryExecutionId: started.QueryExecutionId, state: "QUEUED" }, httpStatus4.ACCEPTED);
2421
+ } catch (error) {
2422
+ if (error instanceof Error && error.message.startsWith("Invalid or missing parameter:")) {
2423
+ return c.json({ message: error.message }, httpStatus4.BAD_REQUEST);
2424
+ }
2425
+ throw error;
2426
+ }
2427
+ }));
2428
+ app.get("/executions/:id", (c) => __async(null, null, function* () {
2429
+ var _a, _b, _c, _d, _e, _f;
2430
+ const id = c.req.param("id");
2431
+ if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
2432
+ const execution = yield athena.send(new GetQueryExecutionCommand({ QueryExecutionId: id }));
2433
+ const status = (_b = execution.QueryExecution) == null ? void 0 : _b.Status;
2434
+ return c.json({
2435
+ queryExecutionId: id,
2436
+ state: status == null ? void 0 : status.State,
2437
+ reason: status == null ? void 0 : status.StateChangeReason,
2438
+ statistics: (_c = execution.QueryExecution) == null ? void 0 : _c.Statistics,
2439
+ reusedPreviousResult: (_f = (_e = (_d = execution.QueryExecution) == null ? void 0 : _d.Statistics) == null ? void 0 : _e.ResultReuseInformation) == null ? void 0 : _f.ReusedPreviousResult
2440
+ });
2441
+ }));
2442
+ app.get("/executions/:id/results", (c) => __async(null, null, function* () {
2443
+ var _a, _b, _c, _d, _e, _f, _g;
2444
+ const id = c.req.param("id");
2445
+ if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
2446
+ const requested = Number((_b = c.req.query("maxResults")) != null ? _b : 100);
2447
+ const maxResults = Number.isFinite(requested) ? Math.min(Math.max(requested, 1), 1e3) : 100;
2448
+ const nextToken = c.req.query("nextToken");
2449
+ const results = yield athena.send(new GetQueryResultsCommand({
2450
+ QueryExecutionId: id,
2451
+ NextToken: nextToken,
2452
+ MaxResults: maxResults
2453
+ }));
2454
+ const rows = (_d = (_c = results.ResultSet) == null ? void 0 : _c.Rows) != null ? _d : [];
2455
+ const columns = ((_g = (_f = (_e = results.ResultSet) == null ? void 0 : _e.ResultSetMetadata) == null ? void 0 : _f.ColumnInfo) != null ? _g : []).map((column) => column.Name);
2456
+ return c.json({
2457
+ columns,
2458
+ rows: rows.slice(nextToken ? 0 : 1).map((row) => {
2459
+ var _a2;
2460
+ return ((_a2 = row.Data) != null ? _a2 : []).map((value) => {
2461
+ var _a3;
2462
+ return (_a3 = value.VarCharValue) != null ? _a3 : null;
2463
+ });
2464
+ }),
2465
+ nextToken: results.NextToken
2466
+ });
2467
+ }));
2468
+ app.post("/executions/:id/cancel", (c) => __async(null, null, function* () {
2469
+ var _a;
2470
+ const id = c.req.param("id");
2471
+ if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
2472
+ yield athena.send(new StopQueryExecutionCommand({ QueryExecutionId: id }));
2473
+ return c.body(null, httpStatus4.NO_CONTENT);
2474
+ }));
2475
+ return handle2(app);
2476
+ };
2477
+
2318
2478
  // processors/create-entity-processor.ts
2319
2479
  var handler = (container) => (ev) => __async(null, null, function* () {
2320
2480
  const { entityService } = container;
@@ -2357,6 +2517,8 @@ import {
2357
2517
  PutRecordBatchCommand
2358
2518
  } from "@aws-sdk/client-firehose";
2359
2519
  import { unmarshall as unmarshall4 } from "@aws-sdk/util-dynamodb";
2520
+ var maxFirehoseBatchBytes = 4 * 1024 * 1024;
2521
+ var maxFirehoseRecordBytes = 1e3 * 1024;
2360
2522
  var firehose = new FirehoseClient();
2361
2523
  function encodeAnalyticsEvent(event) {
2362
2524
  return {
@@ -2373,6 +2535,28 @@ function encodeAnalyticsEvent(event) {
2373
2535
  after: event.after ? JSON.stringify(event.after) : void 0
2374
2536
  };
2375
2537
  }
2538
+ function batchAnalyticsRecords(values, serialize) {
2539
+ const batches = [];
2540
+ const oversized = [];
2541
+ let batch = [];
2542
+ let batchBytes = 0;
2543
+ for (const value of values) {
2544
+ const bytes = Buffer.byteLength(serialize(value));
2545
+ if (bytes > maxFirehoseRecordBytes) {
2546
+ oversized.push(value);
2547
+ continue;
2548
+ }
2549
+ if (batch.length === 500 || batchBytes + bytes > maxFirehoseBatchBytes) {
2550
+ batches.push(batch);
2551
+ batch = [];
2552
+ batchBytes = 0;
2553
+ }
2554
+ batch.push(value);
2555
+ batchBytes += bytes;
2556
+ }
2557
+ if (batch.length) batches.push(batch);
2558
+ return { batches, oversized };
2559
+ }
2376
2560
  function omitTopLevelFields(value, fields) {
2377
2561
  if (!value) return value;
2378
2562
  return Object.fromEntries(
@@ -2433,7 +2617,7 @@ function datasetForRecord(record, manifest2, config) {
2433
2617
  }
2434
2618
  }
2435
2619
  var handler2 = (config) => (event) => __async(null, null, function* () {
2436
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
2620
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
2437
2621
  const streamName = process.env.ANALYTICS_DELIVERY_STREAM;
2438
2622
  if (!streamName) throw new Error("ANALYTICS_DELIVERY_STREAM is required.");
2439
2623
  const manifest2 = parseAnalyticsManifest();
@@ -2481,8 +2665,15 @@ var handler2 = (config) => (event) => __async(null, null, function* () {
2481
2665
  failures.push({ itemIdentifier: (_j = (_i = record.dynamodb) == null ? void 0 : _i.SequenceNumber) != null ? _j : "" });
2482
2666
  }
2483
2667
  }
2484
- for (let index = 0; index < events.length; index += 500) {
2485
- const batch = events.slice(index, index + 500);
2668
+ const { batches, oversized } = batchAnalyticsRecords(
2669
+ events,
2670
+ ({ event: value }) => `${JSON.stringify(encodeAnalyticsEvent(value))}
2671
+ `
2672
+ );
2673
+ for (const { record } of oversized) {
2674
+ failures.push({ itemIdentifier: (_l = (_k = record.dynamodb) == null ? void 0 : _k.SequenceNumber) != null ? _l : "" });
2675
+ }
2676
+ for (const batch of batches) {
2486
2677
  const result = yield firehose.send(
2487
2678
  new PutRecordBatchCommand({
2488
2679
  DeliveryStreamName: streamName,
@@ -2492,7 +2683,7 @@ var handler2 = (config) => (event) => __async(null, null, function* () {
2492
2683
  }))
2493
2684
  })
2494
2685
  );
2495
- (_k = result.RequestResponses) == null ? void 0 : _k.forEach((response, responseIndex) => {
2686
+ (_m = result.RequestResponses) == null ? void 0 : _m.forEach((response, responseIndex) => {
2496
2687
  var _a2, _b2, _c2;
2497
2688
  if (!response.ErrorCode) return;
2498
2689
  failures.push({
@@ -2506,21 +2697,24 @@ var handler2 = (config) => (event) => __async(null, null, function* () {
2506
2697
  // processors/analytics-backfill-processor.ts
2507
2698
  import {
2508
2699
  DeleteItemCommand,
2509
- DynamoDBClient,
2700
+ DynamoDBClient as DynamoDBClient2,
2510
2701
  ExportTableToPointInTimeCommand,
2511
- GetItemCommand,
2512
- PutItemCommand,
2702
+ GetItemCommand as GetItemCommand2,
2703
+ PutItemCommand as PutItemCommand2,
2513
2704
  UpdateItemCommand
2514
2705
  } from "@aws-sdk/client-dynamodb";
2515
2706
  import { FirehoseClient as FirehoseClient2, PutRecordBatchCommand as PutRecordBatchCommand2 } from "@aws-sdk/client-firehose";
2707
+ import { InvokeCommand, LambdaClient } from "@aws-sdk/client-lambda";
2516
2708
  import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
2517
2709
  import { marshall as marshall5, unmarshall as unmarshall5 } from "@aws-sdk/util-dynamodb";
2710
+ import { setTimeout as setTimeout2 } from "timers/promises";
2518
2711
  import { gunzipSync } from "zlib";
2519
- var dynamodb = new DynamoDBClient();
2712
+ var dynamodb = new DynamoDBClient2();
2520
2713
  var firehose2 = new FirehoseClient2();
2714
+ var lambda = new LambdaClient();
2521
2715
  var s3 = new S3Client();
2522
2716
  var backfillMarker = { PK: "#ANALYTICS#", SK: "#BACKFILL#" };
2523
- function required(name) {
2717
+ function required2(name) {
2524
2718
  const value = process.env[name];
2525
2719
  if (!value) throw new Error(`${name} is required.`);
2526
2720
  return value;
@@ -2537,11 +2731,11 @@ function startBackfill(reconcile = false) {
2537
2731
  return __async(this, null, function* () {
2538
2732
  var _a, _b, _c;
2539
2733
  const timestamp = exportTimestamp();
2540
- const tableName = required("ANALYTICS_BACKFILL_MARKER_TABLE");
2734
+ const tableName = required2("ANALYTICS_BACKFILL_MARKER_TABLE");
2541
2735
  const marker = marshall5(__spreadProps(__spreadValues({}, backfillMarker), { exportTime: timestamp.toISOString(), state: "starting" }));
2542
2736
  let createdMarker = false;
2543
2737
  try {
2544
- yield dynamodb.send(new PutItemCommand({ TableName: tableName, Item: marker, ConditionExpression: "attribute_not_exists(PK)" }));
2738
+ yield dynamodb.send(new PutItemCommand2({ TableName: tableName, Item: marker, ConditionExpression: "attribute_not_exists(PK)" }));
2545
2739
  createdMarker = true;
2546
2740
  } catch (error) {
2547
2741
  if (error.name !== "ConditionalCheckFailedException") throw error;
@@ -2554,7 +2748,7 @@ function startBackfill(reconcile = false) {
2554
2748
  ExpressionAttributeValues: marshall5({ ":exportTime": timestamp.toISOString(), ":state": "starting" })
2555
2749
  }));
2556
2750
  } else {
2557
- const existing = yield dynamodb.send(new GetItemCommand({ TableName: tableName, Key: marshall5(backfillMarker), ConsistentRead: true }));
2751
+ const existing = yield dynamodb.send(new GetItemCommand2({ TableName: tableName, Key: marshall5(backfillMarker), ConsistentRead: true }));
2558
2752
  const value = existing.Item ? unmarshall5(existing.Item) : {};
2559
2753
  return { exportArn: value.exportArn, exportTime: value.exportTime, started: false };
2560
2754
  }
@@ -2562,8 +2756,8 @@ function startBackfill(reconcile = false) {
2562
2756
  let result;
2563
2757
  try {
2564
2758
  result = yield dynamodb.send(new ExportTableToPointInTimeCommand({
2565
- TableArn: required("ANALYTICS_TABLE_ARN"),
2566
- S3Bucket: required("ANALYTICS_BACKFILL_BUCKET"),
2759
+ TableArn: required2("ANALYTICS_TABLE_ARN"),
2760
+ S3Bucket: required2("ANALYTICS_BACKFILL_BUCKET"),
2567
2761
  S3Prefix: (_a = process.env.ANALYTICS_BACKFILL_PREFIX) != null ? _a : "backfill",
2568
2762
  ExportTime: timestamp,
2569
2763
  ExportFormat: "DYNAMODB_JSON"
@@ -2603,7 +2797,7 @@ function backfillTimestamp() {
2603
2797
  return __async(this, null, function* () {
2604
2798
  const tableName = process.env.ANALYTICS_BACKFILL_MARKER_TABLE;
2605
2799
  if (!tableName) return exportTimestamp();
2606
- const result = yield dynamodb.send(new GetItemCommand({ TableName: tableName, Key: marshall5(backfillMarker), ConsistentRead: true }));
2800
+ const result = yield dynamodb.send(new GetItemCommand2({ TableName: tableName, Key: marshall5(backfillMarker), ConsistentRead: true }));
2607
2801
  const value = result.Item ? unmarshall5(result.Item).exportTime : void 0;
2608
2802
  if (typeof value !== "string") throw new Error("Analytics backfill marker is missing its export timestamp.");
2609
2803
  const timestamp = new Date(value);
@@ -2632,9 +2826,9 @@ function streamToBuffer(stream) {
2632
2826
  return Buffer.concat(chunks);
2633
2827
  }))();
2634
2828
  }
2635
- function snapshotEvent(item, config, occurredAt, omittedFields) {
2829
+ function snapshotEvent(item, config, manifest2, occurredAt, omittedFields) {
2636
2830
  const attributes = marshall5(item, { removeUndefinedValues: true });
2637
- const dataset = datasetForRecord({ dynamodb: { NewImage: attributes } }, parseAnalyticsManifest(), config);
2831
+ const dataset = datasetForRecord({ dynamodb: { NewImage: attributes } }, manifest2, config);
2638
2832
  if (!dataset) return void 0;
2639
2833
  const after = sanitizeItem(item, omittedFields);
2640
2834
  const key = `${String(item.PK)}:${String(item.SK)}`;
@@ -2659,39 +2853,60 @@ var handler3 = (config) => (event) => __async(null, null, function* () {
2659
2853
  throw new Error("Unsupported analytics backfill event.");
2660
2854
  }
2661
2855
  const timestamp = yield backfillTimestamp();
2856
+ const manifest2 = parseAnalyticsManifest();
2662
2857
  const omittedFields = new Set(JSON.parse((_a = process.env.ANALYTICS_OMIT_FIELDS) != null ? _a : "[]"));
2663
- const deliveryStream = required("ANALYTICS_DELIVERY_STREAM");
2858
+ const deliveryStream = required2("ANALYTICS_DELIVERY_STREAM");
2859
+ let exportComplete = false;
2664
2860
  let delivered = 0;
2665
2861
  for (const record of event.Records) {
2666
2862
  const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
2863
+ if (key.endsWith("manifest-summary.json")) {
2864
+ exportComplete = true;
2865
+ continue;
2866
+ }
2667
2867
  if (!key.endsWith(".json.gz")) continue;
2668
2868
  const response = yield s3.send(new GetObjectCommand({ Bucket: record.s3.bucket.name, Key: key }));
2669
2869
  if (!response.Body) throw new Error(`Backfill export object ${key} has no body.`);
2670
2870
  const content = gunzipSync(yield streamToBuffer(response.Body)).toString("utf8");
2671
2871
  const events = content.split("\n").filter(Boolean).flatMap((line) => {
2672
2872
  const attributes = JSON.parse(line).Item;
2673
- return attributes ? [snapshotEvent(unmarshall5(attributes), config, timestamp, omittedFields)].filter(Boolean) : [];
2873
+ return attributes ? [snapshotEvent(unmarshall5(attributes), config, manifest2, timestamp, omittedFields)].filter(Boolean) : [];
2674
2874
  });
2675
- for (let index = 0; index < events.length; index += 500) {
2676
- const batch = events.slice(index, index + 500);
2875
+ const { batches, oversized } = batchAnalyticsRecords(
2876
+ events,
2877
+ (value) => `${JSON.stringify(encodeAnalyticsEvent(value))}
2878
+ `
2879
+ );
2880
+ if (oversized.length) {
2881
+ throw new Error(`Cannot deliver ${oversized.length} backfill records exceeding Firehose's 1000 KiB record limit.`);
2882
+ }
2883
+ for (const batch of batches) {
2677
2884
  const result = yield firehose2.send(new PutRecordBatchCommand2({ DeliveryStreamName: deliveryStream, Records: batch.map((value) => ({ Data: Buffer.from(`${JSON.stringify(encodeAnalyticsEvent(value))}
2678
2885
  `) })) }));
2679
2886
  if (result.FailedPutCount) throw new Error(`Failed to deliver ${result.FailedPutCount} backfill records; retry this export object.`);
2680
2887
  delivered += batch.length;
2681
2888
  }
2682
2889
  }
2890
+ if (exportComplete && process.env.ANALYTICS_MATERIALIZATION_FUNCTION) {
2891
+ yield setTimeout2(31e4);
2892
+ yield lambda.send(new InvokeCommand({
2893
+ FunctionName: process.env.ANALYTICS_MATERIALIZATION_FUNCTION,
2894
+ InvocationType: "Event",
2895
+ Payload: Buffer.from("{}")
2896
+ }));
2897
+ }
2683
2898
  return { delivered, exportTime: timestamp.toISOString() };
2684
2899
  });
2685
2900
 
2686
2901
  // processors/analytics-materialization-processor.ts
2687
2902
  import {
2688
- AthenaClient,
2689
- GetQueryExecutionCommand,
2690
- GetQueryResultsCommand,
2691
- StartQueryExecutionCommand
2903
+ AthenaClient as AthenaClient2,
2904
+ GetQueryExecutionCommand as GetQueryExecutionCommand2,
2905
+ GetQueryResultsCommand as GetQueryResultsCommand2,
2906
+ StartQueryExecutionCommand as StartQueryExecutionCommand2
2692
2907
  } from "@aws-sdk/client-athena";
2693
- var athena = new AthenaClient();
2694
- function required2(name) {
2908
+ var athena2 = new AthenaClient2();
2909
+ function required3(name) {
2695
2910
  const value = process.env[name];
2696
2911
  if (!value) throw new Error(`${name} is required.`);
2697
2912
  return value;
@@ -2699,16 +2914,21 @@ function required2(name) {
2699
2914
  function quoteIdentifier(identifier) {
2700
2915
  return `"${identifier.replaceAll('"', '""')}"`;
2701
2916
  }
2917
+ function quoteDdlIdentifier(identifier) {
2918
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier))
2919
+ throw new Error(`Invalid Athena DDL identifier: ${identifier}`);
2920
+ return identifier;
2921
+ }
2702
2922
  function quoteLiteral(value) {
2703
2923
  return `'${value.replaceAll("'", "''")}'`;
2704
2924
  }
2705
2925
  function manifest() {
2706
- return JSON.parse(required2("ANALYTICS_MANIFEST"));
2926
+ return JSON.parse(required3("ANALYTICS_MANIFEST"));
2707
2927
  }
2708
2928
  function valueExpression(column, kind) {
2709
2929
  const payload = "coalesce(after, before)";
2710
2930
  const path = `$.${kind === "mutual" ? "mutualData" : "data"}.${column.sourceName.replaceAll('"', '\\"')}`;
2711
- const scalar = `json_extract_scalar(payload, ${quoteLiteral(path)})`;
2931
+ const scalar = `json_extract_scalar(${payload}, ${quoteLiteral(path)})`;
2712
2932
  switch (column.type) {
2713
2933
  case "boolean":
2714
2934
  return `try_cast(${scalar} AS boolean)`;
@@ -2717,25 +2937,45 @@ function valueExpression(column, kind) {
2717
2937
  case "timestamp":
2718
2938
  return `try_cast(from_iso8601_timestamp(${scalar}) AS timestamp)`;
2719
2939
  case "json":
2720
- return `json_format(json_extract(payload, ${quoteLiteral(path)}))`;
2940
+ return `json_format(json_extract(${payload}, ${quoteLiteral(path)}))`;
2721
2941
  default:
2722
2942
  return scalar;
2723
2943
  }
2724
2944
  }
2945
+ function endpointExpression(endpoint) {
2946
+ const payload = "coalesce(after, before)";
2947
+ if (endpoint.role === "source") {
2948
+ return `json_extract_scalar(${payload}, '$.byEntityId')`;
2949
+ }
2950
+ if (endpoint.role === "target") {
2951
+ return `json_extract_scalar(${payload}, '$.entityId')`;
2952
+ }
2953
+ const entityName = quoteLiteral(endpoint.entityName);
2954
+ return `CASE WHEN json_extract_scalar(${payload}, '$.byEntityType') = ${entityName} THEN json_extract_scalar(${payload}, '$.byEntityId') WHEN json_extract_scalar(${payload}, '$.entityType') = ${entityName} THEN json_extract_scalar(${payload}, '$.entityId') END`;
2955
+ }
2725
2956
  function datasetSql(dataset, database, bucket) {
2726
2957
  var _a;
2727
2958
  const history = `${quoteIdentifier(database)}.${quoteIdentifier(dataset.historyTable)}`;
2728
2959
  const current = `${quoteIdentifier(database)}.${quoteIdentifier(dataset.currentTable)}`;
2960
+ const historyDdl = dataset.historyTable;
2961
+ const currentDdl = dataset.currentTable;
2729
2962
  const raw = `${quoteIdentifier(database)}.${quoteIdentifier((_a = dataset.rawTable) != null ? _a : `${dataset.historyTable}_raw`)}`;
2730
2963
  const typedColumns = dataset.columns.map(
2731
- (column) => `${quoteIdentifier(column.name)} ${column.type === "json" ? "varchar" : column.type}`
2964
+ (column) => `${quoteDdlIdentifier(column.name)} ${column.type === "json" ? "string" : column.type}`
2732
2965
  );
2733
2966
  const names = dataset.columns.map((column) => quoteIdentifier(column.name));
2967
+ const endpointNames = dataset.endpoints.map(
2968
+ (endpoint) => quoteIdentifier(endpoint.column)
2969
+ );
2970
+ const endpointDdlNames = dataset.endpoints.map(
2971
+ (endpoint) => quoteDdlIdentifier(endpoint.column)
2972
+ );
2734
2973
  const values = dataset.columns.map(
2735
2974
  (column) => valueExpression(column, dataset.kind)
2736
2975
  );
2737
2976
  const payload = "coalesce(after, before)";
2738
- const recordIdPath = dataset.kind === "entity" ? "$.entityId" : "$.mutualId";
2977
+ const idPath = dataset.kind === "entity" ? "$.entityId" : "$.mutualId";
2978
+ const recentRaw = `${raw} WHERE event_date >= date_format(date_add('day', -3, current_date), '%Y-%m-%d')`;
2739
2979
  const selected = [
2740
2980
  "event_id",
2741
2981
  "idempotency_key",
@@ -2743,21 +2983,25 @@ function datasetSql(dataset, database, bucket) {
2743
2983
  "sequence_number",
2744
2984
  "operation",
2745
2985
  "try_cast(from_iso8601_timestamp(occurred_at) AS timestamp) AS occurred_at",
2746
- `json_extract_scalar(${payload}, ${quoteLiteral(recordIdPath)}) AS record_id`,
2986
+ `json_extract_scalar(${payload}, ${quoteLiteral(idPath)}) AS ${quoteIdentifier(dataset.idColumn)}`,
2747
2987
  "before AS before_json",
2748
2988
  "after AS after_json",
2989
+ ...dataset.endpoints.map(
2990
+ (endpoint) => `${endpointExpression(endpoint)} AS ${quoteIdentifier(endpoint.column)}`
2991
+ ),
2749
2992
  ...values.map((value, index) => `${value} AS ${names[index]}`)
2750
2993
  ];
2751
2994
  const allColumns = [
2752
- "event_id varchar",
2753
- "idempotency_key varchar",
2754
- "ordering_key varchar",
2755
- "sequence_number varchar",
2756
- "operation varchar",
2995
+ "event_id string",
2996
+ "idempotency_key string",
2997
+ "ordering_key string",
2998
+ "sequence_number string",
2999
+ "operation string",
2757
3000
  "occurred_at timestamp",
2758
- "record_id varchar",
2759
- "before_json varchar",
2760
- "after_json varchar",
3001
+ `${quoteDdlIdentifier(dataset.idColumn)} string`,
3002
+ "before_json string",
3003
+ "after_json string",
3004
+ ...endpointDdlNames.map((name) => `${name} string`),
2761
3005
  ...typedColumns
2762
3006
  ];
2763
3007
  const historyNames = [
@@ -2767,10 +3011,11 @@ function datasetSql(dataset, database, bucket) {
2767
3011
  "sequence_number",
2768
3012
  "operation",
2769
3013
  "occurred_at",
2770
- "record_id",
3014
+ dataset.idColumn,
2771
3015
  "before_json",
2772
3016
  "after_json",
2773
- ...names
3017
+ ...dataset.endpoints.map((endpoint) => endpoint.column),
3018
+ ...dataset.columns.map((column) => column.name)
2774
3019
  ].map(quoteIdentifier).join(", ");
2775
3020
  const insertValues = [
2776
3021
  "s.event_id",
@@ -2779,36 +3024,37 @@ function datasetSql(dataset, database, bucket) {
2779
3024
  "s.sequence_number",
2780
3025
  "s.operation",
2781
3026
  "s.occurred_at",
2782
- "s.record_id",
3027
+ `s.${quoteIdentifier(dataset.idColumn)}`,
2783
3028
  "s.before_json",
2784
3029
  "s.after_json",
3030
+ ...endpointNames.map((name) => `s.${name}`),
2785
3031
  ...names.map((name) => `s.${name}`)
2786
3032
  ].join(", ");
2787
3033
  return [
2788
- `CREATE TABLE IF NOT EXISTS ${history} (${allColumns.join(", ")}) LOCATION ${quoteLiteral(`s3://${bucket}/curated/history/${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/`)} TBLPROPERTIES ('table_type'='ICEBERG')`,
2789
- `MERGE INTO ${history} h USING (SELECT * FROM (SELECT ${selected.join(", ")}, row_number() OVER (PARTITION BY event_id ORDER BY ordering_key DESC) AS row_number FROM ${raw}) WHERE row_number = 1) s ON h.event_id = s.event_id WHEN NOT MATCHED THEN INSERT (${historyNames}) VALUES (${insertValues})`,
2790
- `CREATE TABLE IF NOT EXISTS ${current} (${allColumns.filter((column) => !column.startsWith("event_id ") && !column.startsWith("idempotency_key ") && !column.startsWith("sequence_number ") && !column.startsWith("before_json ") && !column.startsWith("after_json ")).join(", ")}) LOCATION ${quoteLiteral(`s3://${bucket}/current/${dataset.name}/`)} TBLPROPERTIES ('table_type'='ICEBERG')`,
2791
- `MERGE INTO ${current} c USING (SELECT * FROM (SELECT h.*, row_number() OVER (PARTITION BY record_id ORDER BY occurred_at DESC, ordering_key DESC) AS row_number FROM ${history} h) WHERE row_number = 1) s ON c.record_id = s.record_id WHEN MATCHED AND s.operation = 'REMOVE' THEN DELETE WHEN MATCHED THEN UPDATE SET operation = s.operation, occurred_at = s.occurred_at, ordering_key = s.ordering_key${names.map((name) => `, ${name} = s.${name}`).join("")} WHEN NOT MATCHED AND s.operation <> 'REMOVE' THEN INSERT (operation, occurred_at, ordering_key, record_id${names.length ? `, ${names.join(", ")}` : ""}) VALUES (s.operation, s.occurred_at, s.ordering_key, s.record_id${names.length ? `, ${names.map((name) => `s.${name}`).join(", ")}` : ""})`
3034
+ `CREATE TABLE ${historyDdl} (${allColumns.join(", ")}) LOCATION ${quoteLiteral(`s3://${bucket}/curated/history/${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/`)} TBLPROPERTIES ('table_type' = 'ICEBERG')`,
3035
+ `MERGE INTO ${history} h USING (SELECT * FROM (SELECT ${selected.join(", ")}, row_number() OVER (PARTITION BY event_id ORDER BY ordering_key DESC) AS row_number FROM ${recentRaw}) WHERE row_number = 1) s ON h.event_id = s.event_id WHEN NOT MATCHED THEN INSERT (${historyNames}) VALUES (${insertValues})`,
3036
+ `CREATE TABLE ${currentDdl} (${allColumns.filter((column) => !column.startsWith("event_id ") && !column.startsWith("idempotency_key ") && !column.startsWith("sequence_number ") && !column.startsWith("before_json ") && !column.startsWith("after_json ")).join(", ")}) LOCATION ${quoteLiteral(`s3://${bucket}/current/${dataset.name}/`)} TBLPROPERTIES ('table_type' = 'ICEBERG')`,
3037
+ `MERGE INTO ${current} c USING (SELECT * FROM (SELECT h.*, row_number() OVER (PARTITION BY ${quoteIdentifier(dataset.idColumn)} ORDER BY occurred_at DESC, ordering_key DESC) AS row_number FROM ${history} h WHERE h.${quoteIdentifier(dataset.idColumn)} IN (SELECT DISTINCT json_extract_scalar(${payload}, ${quoteLiteral(idPath)}) FROM ${recentRaw})) WHERE row_number = 1) s ON c.${quoteIdentifier(dataset.idColumn)} = s.${quoteIdentifier(dataset.idColumn)} WHEN MATCHED AND s.operation = 'REMOVE' THEN DELETE WHEN MATCHED THEN UPDATE SET operation = s.operation, occurred_at = s.occurred_at, ordering_key = s.ordering_key${endpointNames.map((name) => `, ${name} = s.${name}`).join("")}${names.map((name) => `, ${name} = s.${name}`).join("")} WHEN NOT MATCHED AND s.operation <> 'REMOVE' THEN INSERT (operation, occurred_at, ordering_key, ${quoteIdentifier(dataset.idColumn)}${endpointNames.length ? `, ${endpointNames.join(", ")}` : ""}${names.length ? `, ${names.join(", ")}` : ""}) VALUES (s.operation, s.occurred_at, s.ordering_key, s.${quoteIdentifier(dataset.idColumn)}${endpointNames.length ? `, ${endpointNames.map((name) => `s.${name}`).join(", ")}` : ""}${names.length ? `, ${names.map((name) => `s.${name}`).join(", ")}` : ""})`
2792
3038
  ];
2793
3039
  }
2794
3040
  function execute(statement) {
2795
3041
  return __async(this, null, function* () {
2796
3042
  var _a, _b;
2797
- const started = yield athena.send(
2798
- new StartQueryExecutionCommand({
3043
+ const started = yield athena2.send(
3044
+ new StartQueryExecutionCommand2({
2799
3045
  QueryString: statement,
2800
- WorkGroup: required2("ANALYTICS_WORKGROUP"),
2801
- QueryExecutionContext: { Database: required2("ANALYTICS_DATABASE") },
3046
+ WorkGroup: required3("ANALYTICS_WORKGROUP"),
3047
+ QueryExecutionContext: { Database: required3("ANALYTICS_DATABASE") },
2802
3048
  ResultConfiguration: {
2803
- OutputLocation: required2("ANALYTICS_ATHENA_OUTPUT")
3049
+ OutputLocation: required3("ANALYTICS_ATHENA_OUTPUT")
2804
3050
  }
2805
3051
  })
2806
3052
  );
2807
3053
  if (!started.QueryExecutionId)
2808
3054
  throw new Error("Athena did not return a query execution id.");
2809
3055
  for (; ; ) {
2810
- const status = (_a = (yield athena.send(
2811
- new GetQueryExecutionCommand({
3056
+ const status = (_a = (yield athena2.send(
3057
+ new GetQueryExecutionCommand2({
2812
3058
  QueryExecutionId: started.QueryExecutionId
2813
3059
  })
2814
3060
  )).QueryExecution) == null ? void 0 : _a.Status;
@@ -2822,14 +3068,24 @@ function execute(statement) {
2822
3068
  }
2823
3069
  });
2824
3070
  }
3071
+ function createTable(statement) {
3072
+ return __async(this, null, function* () {
3073
+ try {
3074
+ yield execute(statement);
3075
+ } catch (error) {
3076
+ if (/already exists/i.test(error instanceof Error ? error.message : String(error))) return;
3077
+ throw error;
3078
+ }
3079
+ });
3080
+ }
2825
3081
  function tableColumns(database, table) {
2826
3082
  return __async(this, null, function* () {
2827
3083
  var _a, _b;
2828
3084
  const queryExecutionId = yield execute(
2829
3085
  `SELECT column_name FROM information_schema.columns WHERE table_schema = ${quoteLiteral(database)} AND table_name = ${quoteLiteral(table)}`
2830
3086
  );
2831
- const result = yield athena.send(
2832
- new GetQueryResultsCommand({ QueryExecutionId: queryExecutionId })
3087
+ const result = yield athena2.send(
3088
+ new GetQueryResultsCommand2({ QueryExecutionId: queryExecutionId })
2833
3089
  );
2834
3090
  return new Set(
2835
3091
  ((_b = (_a = result.ResultSet) == null ? void 0 : _a.Rows) != null ? _b : []).slice(1).map((row) => {
@@ -2846,7 +3102,7 @@ function addMissingColumns(database, table, columns) {
2846
3102
  (column) => {
2847
3103
  var _a, _b;
2848
3104
  return !existing.has(
2849
- (_b = (_a = column.match(/^"((?:[^"]|"")+)"/)) == null ? void 0 : _a[1].replaceAll('""', '"')) != null ? _b : ""
3105
+ (_b = (_a = column.match(/^([A-Za-z_][A-Za-z0-9_]*)/)) == null ? void 0 : _a[1]) != null ? _b : ""
2850
3106
  );
2851
3107
  }
2852
3108
  );
@@ -2856,26 +3112,34 @@ function addMissingColumns(database, table, columns) {
2856
3112
  );
2857
3113
  });
2858
3114
  }
2859
- var handler4 = () => __async(null, null, function* () {
2860
- const database = required2("ANALYTICS_DATABASE");
2861
- const bucket = required2("ANALYTICS_BUCKET");
2862
- for (const dataset of manifest().datasets) {
3115
+ function generatedColumns(dataset) {
3116
+ return [
3117
+ `${quoteDdlIdentifier(dataset.idColumn)} string`,
3118
+ ...dataset.endpoints.map(
3119
+ (endpoint) => `${quoteDdlIdentifier(endpoint.column)} string`
3120
+ )
3121
+ ];
3122
+ }
3123
+ var handler4 = (configuredManifest) => () => __async(null, null, function* () {
3124
+ const database = required3("ANALYTICS_DATABASE");
3125
+ const bucket = required3("ANALYTICS_BUCKET");
3126
+ for (const dataset of (configuredManifest != null ? configuredManifest : manifest()).datasets) {
2863
3127
  const statements = datasetSql(dataset, database, bucket);
2864
- yield execute(statements[0]);
3128
+ yield createTable(statements[0]);
2865
3129
  yield addMissingColumns(
2866
3130
  database,
2867
3131
  dataset.historyTable,
2868
- dataset.columns.map(
2869
- (column) => `${quoteIdentifier(column.name)} ${column.type === "json" ? "varchar" : column.type}`
2870
- )
3132
+ [...generatedColumns(dataset), ...dataset.columns.map(
3133
+ (column) => `${quoteDdlIdentifier(column.name)} ${column.type === "json" ? "string" : column.type}`
3134
+ )]
2871
3135
  );
2872
- yield execute(statements[2]);
3136
+ yield createTable(statements[2]);
2873
3137
  yield addMissingColumns(
2874
3138
  database,
2875
3139
  dataset.currentTable,
2876
- dataset.columns.map(
2877
- (column) => `${quoteIdentifier(column.name)} ${column.type === "json" ? "varchar" : column.type}`
2878
- )
3140
+ [...generatedColumns(dataset), ...dataset.columns.map(
3141
+ (column) => `${quoteDdlIdentifier(column.name)} ${column.type === "json" ? "string" : column.type}`
3142
+ )]
2879
3143
  );
2880
3144
  for (const statement of [statements[1], statements[3]]) {
2881
3145
  yield execute(statement);
@@ -2883,12 +3147,94 @@ var handler4 = () => __async(null, null, function* () {
2883
3147
  }
2884
3148
  });
2885
3149
 
3150
+ // processors/analytics-model-processor.ts
3151
+ import { AthenaClient as AthenaClient3, GetQueryExecutionCommand as GetQueryExecutionCommand3, StartQueryExecutionCommand as StartQueryExecutionCommand3 } from "@aws-sdk/client-athena";
3152
+ var athena3 = new AthenaClient3();
3153
+ function required4(name) {
3154
+ const value = process.env[name];
3155
+ if (!value) throw new Error(`${name} is required.`);
3156
+ return value;
3157
+ }
3158
+ function quote(identifier) {
3159
+ return `"${identifier.replaceAll('"', '""')}"`;
3160
+ }
3161
+ function execute2(statement) {
3162
+ return __async(this, null, function* () {
3163
+ var _a, _b;
3164
+ const started = yield athena3.send(new StartQueryExecutionCommand3({
3165
+ QueryString: statement,
3166
+ WorkGroup: required4("ANALYTICS_WORKGROUP"),
3167
+ QueryExecutionContext: { Database: required4("ANALYTICS_DATABASE") },
3168
+ ResultConfiguration: { OutputLocation: required4("ANALYTICS_ATHENA_OUTPUT") }
3169
+ }));
3170
+ if (!started.QueryExecutionId) throw new Error("Athena did not return a query execution id.");
3171
+ for (; ; ) {
3172
+ const status = (_a = (yield athena3.send(new GetQueryExecutionCommand3({ QueryExecutionId: started.QueryExecutionId }))).QueryExecution) == null ? void 0 : _a.Status;
3173
+ if ((status == null ? void 0 : status.State) === "SUCCEEDED") return;
3174
+ if ((status == null ? void 0 : status.State) === "FAILED" || (status == null ? void 0 : status.State) === "CANCELLED") throw new Error(`Analytics model ${status.State}: ${(_b = status.StateChangeReason) != null ? _b : "no reason provided"}`);
3175
+ yield new Promise((resolve) => setTimeout(resolve, 1e3));
3176
+ }
3177
+ });
3178
+ }
3179
+ function modelStatements(model, database, bucket, now = /* @__PURE__ */ new Date()) {
3180
+ const table = model.name.replaceAll("-", "_");
3181
+ const end = now;
3182
+ const start = new Date(end.getTime() - model.lookbackDays * 864e5);
3183
+ start.setUTCHours(0, 0, 0, 0);
3184
+ const source = model.sql.replaceAll("{{windowStart}}", `'${start.toISOString().replaceAll("'", "''")}'`).replaceAll("{{windowEnd}}", `'${end.toISOString().replaceAll("'", "''")}'`);
3185
+ const target = `${quote(database)}.${quote(table)}`;
3186
+ const location = `s3://${bucket}/models/${table}/`;
3187
+ const partitionStart = start.toISOString().slice(0, 10);
3188
+ return [
3189
+ `CREATE TABLE IF NOT EXISTS ${target} WITH (table_type = 'ICEBERG', location = '${location}', partitioning = ARRAY['${model.partitionColumn}']) AS ${source}`,
3190
+ `DELETE FROM ${target} WHERE ${quote(model.partitionColumn)} >= DATE '${partitionStart}'`,
3191
+ `INSERT INTO ${target} ${source}`
3192
+ ];
3193
+ }
3194
+ var handler5 = () => __async(null, null, function* () {
3195
+ const model = JSON.parse(required4("ANALYTICS_MODEL"));
3196
+ for (const statement of modelStatements(model, required4("ANALYTICS_DATABASE"), required4("ANALYTICS_BUCKET"))) {
3197
+ yield execute2(statement);
3198
+ }
3199
+ });
3200
+
3201
+ // processors/analytics-view-processor.ts
3202
+ import { AthenaClient as AthenaClient4, GetQueryExecutionCommand as GetQueryExecutionCommand4, StartQueryExecutionCommand as StartQueryExecutionCommand4 } from "@aws-sdk/client-athena";
3203
+ var athena4 = new AthenaClient4();
3204
+ function required5(name) {
3205
+ const value = process.env[name];
3206
+ if (!value) throw new Error(`${name} is required.`);
3207
+ return value;
3208
+ }
3209
+ function quote2(identifier) {
3210
+ return `"${identifier.replaceAll('"', '""')}"`;
3211
+ }
3212
+ var handler6 = () => __async(null, null, function* () {
3213
+ var _a, _b;
3214
+ const view = JSON.parse(required5("ANALYTICS_VIEW"));
3215
+ const started = yield athena4.send(new StartQueryExecutionCommand4({
3216
+ QueryString: `CREATE OR REPLACE VIEW ${quote2(required5("ANALYTICS_DATABASE"))}.${quote2(view.name.replaceAll("-", "_"))} AS ${view.sql}`,
3217
+ WorkGroup: required5("ANALYTICS_WORKGROUP"),
3218
+ QueryExecutionContext: { Database: required5("ANALYTICS_DATABASE") },
3219
+ ResultConfiguration: { OutputLocation: required5("ANALYTICS_ATHENA_OUTPUT") }
3220
+ }));
3221
+ if (!started.QueryExecutionId) throw new Error("Athena did not return a query execution id.");
3222
+ for (; ; ) {
3223
+ const status = (_a = (yield athena4.send(new GetQueryExecutionCommand4({ QueryExecutionId: started.QueryExecutionId }))).QueryExecution) == null ? void 0 : _a.Status;
3224
+ if ((status == null ? void 0 : status.State) === "SUCCEEDED") return;
3225
+ if ((status == null ? void 0 : status.State) === "FAILED" || (status == null ? void 0 : status.State) === "CANCELLED") {
3226
+ throw new Error(`Analytics view ${view.name} ${status.State}: ${(_b = status.StateChangeReason) != null ? _b : "no reason provided"}`);
3227
+ }
3228
+ yield new Promise((resolve) => setTimeout(resolve, 1e3));
3229
+ }
3230
+ });
3231
+
2886
3232
  // processors/mutual-processor.ts
2887
3233
  import { TransactionCanceledException as TransactionCanceledException3 } from "@aws-sdk/client-dynamodb";
2888
3234
  var processEntities = (entityIds, action) => __async(null, null, function* () {
2889
3235
  return Promise.allSettled(entityIds.map(action));
2890
3236
  });
2891
- var handler5 = (container) => (ev) => __async(null, null, function* () {
3237
+ var handler7 = (container) => (ev) => __async(null, null, function* () {
2892
3238
  const batchItemFailures = [];
2893
3239
  const { entityRepository, mutualRepository, publishEvent: publishEvent2 } = container;
2894
3240
  yield Promise.allSettled(
@@ -3229,7 +3575,7 @@ function publishToSubscribers(_0) {
3229
3575
  );
3230
3576
  });
3231
3577
  }
3232
- var handler6 = (container) => (ev) => __async(null, null, function* () {
3578
+ var handler8 = (container) => (ev) => __async(null, null, function* () {
3233
3579
  var _a, _b, _c, _d, _e, _f, _g, _h;
3234
3580
  const batchItemFailures = [];
3235
3581
  const { mutualRepository, publishEvent: publishEvent2 } = container;
@@ -3282,7 +3628,7 @@ var handler6 = (container) => (ev) => __async(null, null, function* () {
3282
3628
 
3283
3629
  // processors/replication-processor.ts
3284
3630
  import { ConditionalCheckFailedException as ConditionalCheckFailedException2 } from "@aws-sdk/client-dynamodb";
3285
- var handler7 = (container) => (event) => __async(null, null, function* () {
3631
+ var handler9 = (container) => (event) => __async(null, null, function* () {
3286
3632
  var _a, _b, _c, _d, _e, _f, _g;
3287
3633
  const TableName = process.env.DDB_TABLE || container.coreTable;
3288
3634
  const batchItemFailures = [];
@@ -3546,7 +3892,7 @@ function batchUpdateTags(_0) {
3546
3892
  yield Promise.all(addPromises);
3547
3893
  });
3548
3894
  }
3549
- var handler8 = (container) => (ev) => __async(null, null, function* () {
3895
+ var handler10 = (container) => (ev) => __async(null, null, function* () {
3550
3896
  var _a;
3551
3897
  const batchItemFailures = [];
3552
3898
  for (const record of ev.Records) {
@@ -3688,7 +4034,7 @@ var EventUtils = class {
3688
4034
 
3689
4035
  // controllers/entity/create-entity.controller.ts
3690
4036
  import { createMiddleware as createMiddleware3 } from "hono/factory";
3691
- import httpStatus4 from "http-status";
4037
+ import httpStatus5 from "http-status";
3692
4038
  var CreateEntityController = class {
3693
4039
  constructor(entityService) {
3694
4040
  this.entityService = entityService;
@@ -3707,11 +4053,11 @@ var CreateEntityController = class {
3707
4053
  createAndUpdateDatetime: body.createdAt
3708
4054
  }
3709
4055
  });
3710
- c.status(httpStatus4.OK);
4056
+ c.status(httpStatus5.OK);
3711
4057
  return c.json(entity);
3712
4058
  } catch (err) {
3713
4059
  if (((_a = err.constructor) == null ? void 0 : _a.name) === "ZodError") {
3714
- c.status(httpStatus4.BAD_REQUEST);
4060
+ c.status(httpStatus5.BAD_REQUEST);
3715
4061
  return c.json({
3716
4062
  code: "API_VALIDATION_ERROR",
3717
4063
  message: "API validation failed",
@@ -3719,11 +4065,11 @@ var CreateEntityController = class {
3719
4065
  });
3720
4066
  }
3721
4067
  if (err instanceof StandardError && err.code === StandardErrorCode.EMAIL_EXISTS) {
3722
- c.status(httpStatus4.BAD_REQUEST);
4068
+ c.status(httpStatus5.BAD_REQUEST);
3723
4069
  return c.json(__spreadValues({}, err.toJSON()));
3724
4070
  }
3725
4071
  if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
3726
- c.status(httpStatus4.BAD_REQUEST);
4072
+ c.status(httpStatus5.BAD_REQUEST);
3727
4073
  return c.json(__spreadValues({}, err.toJSON()));
3728
4074
  }
3729
4075
  console.log("===create-entity error:", {
@@ -3741,7 +4087,7 @@ var CreateEntityController = class {
3741
4087
 
3742
4088
  // controllers/entity/delete-entity.controller.ts
3743
4089
  import { createMiddleware as createMiddleware4 } from "hono/factory";
3744
- import httpStatus5 from "http-status";
4090
+ import httpStatus6 from "http-status";
3745
4091
  var DeleteEntityController = class {
3746
4092
  constructor(entityService) {
3747
4093
  this.entityService = entityService;
@@ -3757,7 +4103,7 @@ var DeleteEntityController = class {
3757
4103
  return c.json({ message: "entity deleted" });
3758
4104
  } catch (err) {
3759
4105
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_NOT_FOUND) {
3760
- c.status(httpStatus5.NOT_FOUND);
4106
+ c.status(httpStatus6.NOT_FOUND);
3761
4107
  return c.json(__spreadValues({}, err.toJSON()));
3762
4108
  }
3763
4109
  throw err;
@@ -3768,7 +4114,7 @@ var DeleteEntityController = class {
3768
4114
 
3769
4115
  // controllers/entity/get-entity-by-unique-field-value.controller.ts
3770
4116
  import { createMiddleware as createMiddleware5 } from "hono/factory";
3771
- import httpStatus6 from "http-status";
4117
+ import httpStatus7 from "http-status";
3772
4118
  var GetEntityByUniqueFieldValueController = class {
3773
4119
  constructor(entityRepository) {
3774
4120
  this.entityRepository = entityRepository;
@@ -3783,7 +4129,7 @@ var GetEntityByUniqueFieldValueController = class {
3783
4129
  return c.json(entity);
3784
4130
  } catch (err) {
3785
4131
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
3786
- c.status(httpStatus6.NOT_FOUND);
4132
+ c.status(httpStatus7.NOT_FOUND);
3787
4133
  return c.json({
3788
4134
  code: "ENTITY_NOT_FOUND",
3789
4135
  message: "Entity not found"
@@ -3797,7 +4143,7 @@ var GetEntityByUniqueFieldValueController = class {
3797
4143
 
3798
4144
  // controllers/entity/get-entity.controller.ts
3799
4145
  import { createMiddleware as createMiddleware6 } from "hono/factory";
3800
- import httpStatus7 from "http-status";
4146
+ import httpStatus8 from "http-status";
3801
4147
  var GetEntityController = class {
3802
4148
  constructor(entityRepository) {
3803
4149
  this.entityRepository = entityRepository;
@@ -3808,11 +4154,11 @@ var GetEntityController = class {
3808
4154
  entityType,
3809
4155
  entityId
3810
4156
  );
3811
- c.status(httpStatus7.OK);
4157
+ c.status(httpStatus8.OK);
3812
4158
  return c.json(entity);
3813
4159
  } catch (err) {
3814
4160
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
3815
- c.status(httpStatus7.NOT_FOUND);
4161
+ c.status(httpStatus8.NOT_FOUND);
3816
4162
  return c.json({
3817
4163
  code: "ENTITY_NOT_FOUND",
3818
4164
  message: "Entity not found"
@@ -7792,12 +8138,12 @@ var ListEntitiesController = class {
7792
8138
  throw new Error("multiple account-id detected");
7793
8139
  }
7794
8140
  const params = c.req.param();
7795
- const queries = c.req.query();
8141
+ const queries2 = c.req.query();
7796
8142
  errorContext.accountId = accountId;
7797
8143
  errorContext.params = params;
7798
- errorContext.query = queries;
8144
+ errorContext.query = queries2;
7799
8145
  const { entityType } = params;
7800
- const { lastKey, query, limit, start, end } = querySchema.parse(queries);
8146
+ const { lastKey, query, limit, start, end } = querySchema.parse(queries2);
7801
8147
  if (query) {
7802
8148
  const results2 = yield this.entityRepository.queryEntities(
7803
8149
  entityType,
@@ -7833,7 +8179,7 @@ var ListEntitiesController = class {
7833
8179
 
7834
8180
  // controllers/entity/update-entity.controller.ts
7835
8181
  import { createMiddleware as createMiddleware8 } from "hono/factory";
7836
- import httpStatus8 from "http-status";
8182
+ import httpStatus9 from "http-status";
7837
8183
  var UpdateEntityController = class {
7838
8184
  constructor(entityService) {
7839
8185
  this.entityService = entityService;
@@ -7845,7 +8191,7 @@ var UpdateEntityController = class {
7845
8191
  const _a = body, { $condition: condition, $where: where } = _a, entityPayload = __objRest(_a, ["$condition", "$where"]);
7846
8192
  if (condition !== void 0) {
7847
8193
  if (typeof condition !== "string" || condition.trim().length === 0) {
7848
- c.status(httpStatus8.BAD_REQUEST);
8194
+ c.status(httpStatus9.BAD_REQUEST);
7849
8195
  return c.json({
7850
8196
  code: "API_VALIDATION_ERROR",
7851
8197
  message: "$condition must be a non-empty string"
@@ -7867,31 +8213,31 @@ var UpdateEntityController = class {
7867
8213
  where
7868
8214
  });
7869
8215
  errorContext.entity = entity;
7870
- c.status(httpStatus8.OK);
8216
+ c.status(httpStatus9.OK);
7871
8217
  return c.json(entity);
7872
8218
  } catch (err) {
7873
8219
  if (((_b = err.constructor) == null ? void 0 : _b.name) === "ZodError") {
7874
- c.status(httpStatus8.BAD_REQUEST);
8220
+ c.status(httpStatus9.BAD_REQUEST);
7875
8221
  return c.json({
7876
8222
  code: "API_VALIDATION_ERROR",
7877
8223
  message: "API validation failed",
7878
8224
  details: err.flatten()
7879
8225
  });
7880
8226
  }
7881
- if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_NOT_FOUND) {
7882
- c.status(httpStatus8.NOT_FOUND);
8227
+ if (err instanceof StandardError && (err.code === StandardErrorCode.ENTITY_NOT_FOUND || err.code === StandardErrorCode.ENTITY_IS_UNDEFINED)) {
8228
+ c.status(httpStatus9.NOT_FOUND);
7883
8229
  return c.json(__spreadValues({}, err.toJSON()));
7884
8230
  }
7885
8231
  if (err instanceof StandardError && err.code === StandardErrorCode.INVALID_CONDITION) {
7886
- c.status(httpStatus8.BAD_REQUEST);
8232
+ c.status(httpStatus9.BAD_REQUEST);
7887
8233
  return c.json(__spreadValues({}, err.toJSON()));
7888
8234
  }
7889
8235
  if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
7890
- c.status(httpStatus8.BAD_REQUEST);
8236
+ c.status(httpStatus9.BAD_REQUEST);
7891
8237
  return c.json(__spreadValues({}, err.toJSON()));
7892
8238
  }
7893
8239
  if (err instanceof StandardError && err.code === StandardErrorCode.CONDITIONAL_CHECK_FAILED) {
7894
- c.status(httpStatus8.CONFLICT);
8240
+ c.status(httpStatus9.CONFLICT);
7895
8241
  return c.json(__spreadValues({}, err.toJSON()));
7896
8242
  }
7897
8243
  console.log(
@@ -7907,7 +8253,7 @@ var UpdateEntityController = class {
7907
8253
 
7908
8254
  // controllers/entity/adjust-entity.controller.ts
7909
8255
  import { createMiddleware as createMiddleware9 } from "hono/factory";
7910
- import httpStatus9 from "http-status";
8256
+ import httpStatus10 from "http-status";
7911
8257
  var AdjustEntityController = class {
7912
8258
  constructor(entityService) {
7913
8259
  this.entityService = entityService;
@@ -7919,7 +8265,7 @@ var AdjustEntityController = class {
7919
8265
  const _a = body, { $condition: condition } = _a, adjustments = __objRest(_a, ["$condition"]);
7920
8266
  if (condition !== void 0) {
7921
8267
  if (typeof condition !== "string" || condition.trim().length === 0) {
7922
- c.status(httpStatus9.BAD_REQUEST);
8268
+ c.status(httpStatus10.BAD_REQUEST);
7923
8269
  return c.json({
7924
8270
  code: "API_VALIDATION_ERROR",
7925
8271
  message: "$condition must be a non-empty string"
@@ -7928,7 +8274,7 @@ var AdjustEntityController = class {
7928
8274
  }
7929
8275
  for (const [key, value] of Object.entries(adjustments)) {
7930
8276
  if (typeof value !== "number") {
7931
- c.status(httpStatus9.BAD_REQUEST);
8277
+ c.status(httpStatus10.BAD_REQUEST);
7932
8278
  return c.json({
7933
8279
  code: "API_VALIDATION_ERROR",
7934
8280
  message: `Field "${key}" must be a number, got ${typeof value}`
@@ -7943,19 +8289,19 @@ var AdjustEntityController = class {
7943
8289
  accountId,
7944
8290
  condition
7945
8291
  });
7946
- c.status(httpStatus9.OK);
8292
+ c.status(httpStatus10.OK);
7947
8293
  return c.json(entity.toJSON());
7948
8294
  } catch (err) {
7949
8295
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
7950
- c.status(httpStatus9.NOT_FOUND);
8296
+ c.status(httpStatus10.NOT_FOUND);
7951
8297
  return c.json(__spreadValues({}, err.toJSON()));
7952
8298
  }
7953
8299
  if (err instanceof StandardError && err.code === StandardErrorCode.INVALID_CONDITION) {
7954
- c.status(httpStatus9.BAD_REQUEST);
8300
+ c.status(httpStatus10.BAD_REQUEST);
7955
8301
  return c.json(__spreadValues({}, err.toJSON()));
7956
8302
  }
7957
8303
  if ((err == null ? void 0 : err.name) === "ConditionalCheckFailedException" || ((_b = err == null ? void 0 : err.__type) == null ? void 0 : _b.includes("ConditionalCheckFailed"))) {
7958
- c.status(httpStatus9.CONFLICT);
8304
+ c.status(httpStatus10.CONFLICT);
7959
8305
  return c.json({
7960
8306
  code: "ADJUSTMENT_CONSTRAINT_VIOLATED",
7961
8307
  message: "Adjustment would violate entity constraints"
@@ -7970,28 +8316,37 @@ var AdjustEntityController = class {
7970
8316
 
7971
8317
  // controllers/entity/upsert-entity.controller.ts
7972
8318
  import { createMiddleware as createMiddleware10 } from "hono/factory";
7973
- import httpStatus10 from "http-status";
8319
+ import httpStatus11 from "http-status";
7974
8320
  var UpsertEntityController = class {
7975
8321
  constructor(EntityConfig, entityRepository, publishEvent2) {
7976
8322
  this.EntityConfig = EntityConfig;
7977
8323
  this.entityRepository = entityRepository;
7978
8324
  this.publishEvent = publishEvent2;
7979
8325
  this.controller = createMiddleware10((c) => __async(this, null, function* () {
7980
- var _a, _b;
8326
+ var _a;
7981
8327
  const accountId = c.req.header("account-id");
7982
8328
  const { entityType, entityId } = c.req.param();
7983
8329
  try {
7984
- const entitySchema = this.EntityConfig[entityType].createSchema || this.EntityConfig[entityType].baseSchema;
7985
- const mutualSchema = (_a = this.EntityConfig[entityType].mutual) == null ? void 0 : _a.mutualSchema;
8330
+ const entityConfig = this.EntityConfig[entityType];
8331
+ const entitySchema = entityConfig.createSchema || entityConfig.baseSchema;
8332
+ const mutual = entityConfig.mutual;
8333
+ const mutualSchema = mutual == null ? void 0 : mutual.mutualSchema;
7986
8334
  if (!entitySchema || !mutualSchema) {
7987
8335
  throw new StandardError(
7988
8336
  StandardErrorCode.INVALID_ENTITY_TYPE,
7989
8337
  "Invalid entity type"
7990
8338
  );
7991
8339
  }
8340
+ const isCreate = (mutual == null ? void 0 : mutual.createMutualSchema) ? yield this.entityRepository.getEntity(entityType, entityId).then(() => false).catch((err) => {
8341
+ if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
8342
+ return true;
8343
+ }
8344
+ throw err;
8345
+ }) : false;
8346
+ const effectiveMutualSchema = isCreate ? (_a = entityConfig.effectiveMutualSchema) != null ? _a : mutualSchema : mutualSchema;
7992
8347
  const body = yield c.req.json();
7993
8348
  const parsedEntityPayload = entitySchema.parse(body);
7994
- const parsedMutualPayload = mutualSchema.parse(body);
8349
+ const parsedMutualPayload = effectiveMutualSchema.parse(body);
7995
8350
  const entity = yield this.entityRepository.upsertEntity(
7996
8351
  entityType,
7997
8352
  entityId,
@@ -8002,7 +8357,7 @@ var UpsertEntityController = class {
8002
8357
  const byEntityId = entity.entityId;
8003
8358
  const publishEventPromises = [];
8004
8359
  for (const [fieldKey, config] of Object.entries(
8005
- ((_b = this.EntityConfig[entityType].mutual) == null ? void 0 : _b.mutualFields) || {}
8360
+ (mutual == null ? void 0 : mutual.mutualFields) || {}
8006
8361
  )) {
8007
8362
  publishEventPromises.push(
8008
8363
  this.publishEvent({
@@ -8032,7 +8387,7 @@ var UpsertEntityController = class {
8032
8387
  return c.json(entity);
8033
8388
  } catch (err) {
8034
8389
  if (err instanceof ZodError) {
8035
- c.status(httpStatus10.BAD_REQUEST);
8390
+ c.status(httpStatus11.BAD_REQUEST);
8036
8391
  return c.json({
8037
8392
  code: "API_VALIDATION_ERROR",
8038
8393
  message: "API validation failed",
@@ -8040,7 +8395,7 @@ var UpsertEntityController = class {
8040
8395
  });
8041
8396
  }
8042
8397
  if (err instanceof StandardError && err.code === StandardErrorCode.EMAIL_EXISTS) {
8043
- c.status(httpStatus10.BAD_REQUEST);
8398
+ c.status(httpStatus11.BAD_REQUEST);
8044
8399
  return c.json(__spreadValues({}, err.toJSON()));
8045
8400
  }
8046
8401
  throw err;
@@ -8051,7 +8406,7 @@ var UpsertEntityController = class {
8051
8406
 
8052
8407
  // controllers/mutual/create-mutual.controller.ts
8053
8408
  import { createMiddleware as createMiddleware11 } from "hono/factory";
8054
- import httpStatus11 from "http-status";
8409
+ import httpStatus12 from "http-status";
8055
8410
  var CreateMutualController = class {
8056
8411
  constructor(mutualService) {
8057
8412
  this.mutualService = mutualService;
@@ -8075,7 +8430,7 @@ var CreateMutualController = class {
8075
8430
  return c.json(mutual);
8076
8431
  } catch (err) {
8077
8432
  if (err instanceof ZodError) {
8078
- c.status(httpStatus11.BAD_REQUEST);
8433
+ c.status(httpStatus12.BAD_REQUEST);
8079
8434
  return c.json({
8080
8435
  code: "API_VALIDATION_ERROR",
8081
8436
  message: "API validation failed",
@@ -8083,11 +8438,11 @@ var CreateMutualController = class {
8083
8438
  });
8084
8439
  }
8085
8440
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_EXISTS) {
8086
- c.status(httpStatus11.BAD_REQUEST);
8441
+ c.status(httpStatus12.BAD_REQUEST);
8087
8442
  return c.json(__spreadValues({}, err.toJSON()));
8088
8443
  }
8089
8444
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
8090
- c.status(httpStatus11.BAD_REQUEST);
8445
+ c.status(httpStatus12.BAD_REQUEST);
8091
8446
  return c.json(__spreadValues({}, err.toJSON()));
8092
8447
  }
8093
8448
  throw err;
@@ -8098,7 +8453,7 @@ var CreateMutualController = class {
8098
8453
 
8099
8454
  // controllers/mutual/delete-mutual.controller.ts
8100
8455
  import { createMiddleware as createMiddleware12 } from "hono/factory";
8101
- import httpStatus12 from "http-status";
8456
+ import httpStatus13 from "http-status";
8102
8457
  var DeleteMutualController = class {
8103
8458
  constructor(mutualService) {
8104
8459
  this.mutualService = mutualService;
@@ -8116,7 +8471,7 @@ var DeleteMutualController = class {
8116
8471
  return c.json(mutual);
8117
8472
  } catch (err) {
8118
8473
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_NOT_FOUND) {
8119
- c.status(httpStatus12.BAD_REQUEST);
8474
+ c.status(httpStatus13.BAD_REQUEST);
8120
8475
  return c.json(__spreadValues({}, err.toJSON()));
8121
8476
  }
8122
8477
  throw err;
@@ -8127,7 +8482,7 @@ var DeleteMutualController = class {
8127
8482
 
8128
8483
  // controllers/mutual/get-mutual.controller.ts
8129
8484
  import { createMiddleware as createMiddleware13 } from "hono/factory";
8130
- import httpStatus13 from "http-status";
8485
+ import httpStatus14 from "http-status";
8131
8486
  var GetMutualController = class {
8132
8487
  constructor(associateRepository) {
8133
8488
  this.associateRepository = associateRepository;
@@ -8143,7 +8498,7 @@ var GetMutualController = class {
8143
8498
  return c.json(associate);
8144
8499
  } catch (err) {
8145
8500
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_IS_UNDEFINED) {
8146
- c.status(httpStatus13.NOT_FOUND);
8501
+ c.status(httpStatus14.NOT_FOUND);
8147
8502
  return c.json({
8148
8503
  code: "MUTUAL_NOT_FOUND",
8149
8504
  message: "Mutual not found"
@@ -8219,7 +8574,7 @@ var ListEntitiesByEntityController = class {
8219
8574
 
8220
8575
  // controllers/mutual/update-mutual.controller.ts
8221
8576
  import { createMiddleware as createMiddleware15 } from "hono/factory";
8222
- import httpStatus14 from "http-status";
8577
+ import httpStatus15 from "http-status";
8223
8578
  var UpdateMutualController = class {
8224
8579
  constructor(mutualService) {
8225
8580
  this.mutualService = mutualService;
@@ -8242,7 +8597,7 @@ var UpdateMutualController = class {
8242
8597
  return c.json(mutual);
8243
8598
  } catch (err) {
8244
8599
  if (err instanceof ZodError) {
8245
- c.status(httpStatus14.BAD_REQUEST);
8600
+ c.status(httpStatus15.BAD_REQUEST);
8246
8601
  return c.json({
8247
8602
  code: "API_VALIDATION_ERROR",
8248
8603
  message: "API validation failed",
@@ -8250,7 +8605,7 @@ var UpdateMutualController = class {
8250
8605
  });
8251
8606
  }
8252
8607
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_NOT_FOUND) {
8253
- c.status(httpStatus14.BAD_REQUEST);
8608
+ c.status(httpStatus15.BAD_REQUEST);
8254
8609
  return c.json(__spreadValues({}, err.toJSON()));
8255
8610
  }
8256
8611
  throw err;
@@ -8958,7 +9313,7 @@ var ListTagsController = class {
8958
9313
 
8959
9314
  // controllers/transaction/execute-transaction.controller.ts
8960
9315
  import { createMiddleware as createMiddleware17 } from "hono/factory";
8961
- import httpStatus15 from "http-status";
9316
+ import httpStatus16 from "http-status";
8962
9317
  var ExecuteTransactionController = class {
8963
9318
  constructor(transactionService) {
8964
9319
  this.transactionService = transactionService;
@@ -8969,7 +9324,7 @@ var ExecuteTransactionController = class {
8969
9324
  try {
8970
9325
  const body = yield c.req.json();
8971
9326
  if (!body.operations || !Array.isArray(body.operations)) {
8972
- c.status(httpStatus15.BAD_REQUEST);
9327
+ c.status(httpStatus16.BAD_REQUEST);
8973
9328
  return c.json({
8974
9329
  code: "API_VALIDATION_ERROR",
8975
9330
  message: 'Request body must contain an "operations" array'
@@ -8979,11 +9334,11 @@ var ExecuteTransactionController = class {
8979
9334
  body.operations,
8980
9335
  accountId
8981
9336
  );
8982
- c.status(httpStatus15.OK);
9337
+ c.status(httpStatus16.OK);
8983
9338
  return c.json(result);
8984
9339
  } catch (err) {
8985
9340
  if (((_a = err.constructor) == null ? void 0 : _a.name) === "ZodError") {
8986
- c.status(httpStatus15.BAD_REQUEST);
9341
+ c.status(httpStatus16.BAD_REQUEST);
8987
9342
  return c.json({
8988
9343
  code: "API_VALIDATION_ERROR",
8989
9344
  message: "Validation failed",
@@ -8991,7 +9346,7 @@ var ExecuteTransactionController = class {
8991
9346
  });
8992
9347
  }
8993
9348
  if (err instanceof SyntaxError) {
8994
- c.status(httpStatus15.BAD_REQUEST);
9349
+ c.status(httpStatus16.BAD_REQUEST);
8995
9350
  return c.json({
8996
9351
  code: "API_VALIDATION_ERROR",
8997
9352
  message: "Request body must be valid JSON"
@@ -9000,15 +9355,15 @@ var ExecuteTransactionController = class {
9000
9355
  if (err instanceof StandardError) {
9001
9356
  const code = err.code;
9002
9357
  if (code === StandardErrorCode.ENTITY_IS_UNDEFINED || code === StandardErrorCode.ENTITY_NOT_FOUND) {
9003
- c.status(httpStatus15.NOT_FOUND);
9358
+ c.status(httpStatus16.NOT_FOUND);
9004
9359
  return c.json(__spreadValues({}, err.toJSON()));
9005
9360
  }
9006
9361
  if (code === StandardErrorCode.TRANSACTION_EMPTY || code === StandardErrorCode.TRANSACTION_ITEM_LIMIT_EXCEEDED || code === StandardErrorCode.TRANSACTION_UNIQUE_FIELD_UPDATE || code === StandardErrorCode.TRANSACTION_INVALID_OPERATION || code === StandardErrorCode.TRANSACTION_VALIDATION_ERROR || code === StandardErrorCode.INVALID_ENTITY_TYPE || code === StandardErrorCode.INVALID_CONDITION || code === StandardErrorCode.INVALID_UNIQUE_VALUE_TYPE) {
9007
- c.status(httpStatus15.BAD_REQUEST);
9362
+ c.status(httpStatus16.BAD_REQUEST);
9008
9363
  return c.json(__spreadValues({}, err.toJSON()));
9009
9364
  }
9010
9365
  if (code === StandardErrorCode.TRANSACTION_FAILED || code === StandardErrorCode.CONDITIONAL_CHECK_FAILED || code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
9011
- c.status(httpStatus15.CONFLICT);
9366
+ c.status(httpStatus16.CONFLICT);
9012
9367
  return c.json(__spreadValues({}, err.toJSON()));
9013
9368
  }
9014
9369
  }
@@ -9027,8 +9382,9 @@ var EntityServiceLifeCycle = class {
9027
9382
  }
9028
9383
  afterCreateEntityHook(entity, entityPayload, accountId) {
9029
9384
  return __async(this, null, function* () {
9030
- var _a;
9031
- const mutualSchema = (_a = this.EntityConfig[entity.entityType].mutual) == null ? void 0 : _a.mutualSchema;
9385
+ var _a, _b;
9386
+ const config = this.EntityConfig[entity.entityType];
9387
+ const mutualSchema = (_b = config == null ? void 0 : config.effectiveMutualSchema) != null ? _b : (_a = config == null ? void 0 : config.mutual) == null ? void 0 : _a.mutualSchema;
9032
9388
  const parsedMutualPayload = mutualSchema == null ? void 0 : mutualSchema.parse(entityPayload);
9033
9389
  if (parsedMutualPayload) {
9034
9390
  yield this.eventUtils.publishCreateMutualsEvent({
@@ -9423,16 +9779,16 @@ var TransactionService = class {
9423
9779
  };
9424
9780
  }
9425
9781
  collectCreateEvents(entity, payload, accountId) {
9426
- var _a, _b;
9782
+ var _a, _b, _c;
9427
9783
  const events = [];
9428
9784
  const publishedAt = entity.updatedAt || (/* @__PURE__ */ new Date()).toISOString();
9429
9785
  const config = this.EntityConfig[entity.entityType];
9430
- const mutualSchema = (_a = config == null ? void 0 : config.mutual) == null ? void 0 : _a.mutualSchema;
9786
+ const mutualSchema = (_b = config == null ? void 0 : config.effectiveMutualSchema) != null ? _b : (_a = config == null ? void 0 : config.mutual) == null ? void 0 : _a.mutualSchema;
9431
9787
  if (mutualSchema) {
9432
9788
  const parsedMutualPayload = mutualSchema.parse(payload);
9433
9789
  if (parsedMutualPayload) {
9434
9790
  for (const [fieldKey, fieldConfig] of Object.entries(
9435
- ((_b = config.mutual) == null ? void 0 : _b.mutualFields) || {}
9791
+ ((_c = config.mutual) == null ? void 0 : _c.mutualFields) || {}
9436
9792
  )) {
9437
9793
  const toMutualIds = fieldConfig.toMutualIds;
9438
9794
  const mutualPayload = parsedMutualPayload[fieldKey];
@@ -9744,13 +10100,13 @@ var CoreFactory = class {
9744
10100
  const dependencyContainer = new DependencyContainer(this.config);
9745
10101
  this.dependencyContainer = dependencyContainer;
9746
10102
  this.setupCommonRoutes = setupCommonRoutes(dependencyContainer);
9747
- this.mutualProcessor = handler5(dependencyContainer);
9748
- this.replicationProcessor = handler7(dependencyContainer);
10103
+ this.mutualProcessor = handler7(dependencyContainer);
10104
+ this.replicationProcessor = handler9(dependencyContainer);
9749
10105
  this.createEntityProcessor = handler(dependencyContainer);
9750
10106
  this.analyticsProcessor = handler2(this.config.EntityConfig);
9751
10107
  this.analyticsBackfillProcessor = handler3(this.config.EntityConfig);
9752
- this.prejoinProcessor = handler6(dependencyContainer);
9753
- this.tagProcessor = handler8(dependencyContainer);
10108
+ this.prejoinProcessor = handler8(dependencyContainer);
10109
+ this.tagProcessor = handler10(dependencyContainer);
9754
10110
  this.appHandler = appHandler(dependencyContainer);
9755
10111
  }
9756
10112
  };
@@ -9770,16 +10126,19 @@ export {
9770
10126
  TransactionService,
9771
10127
  handler3 as analyticsBackfillProcessor,
9772
10128
  handler4 as analyticsMaterializationProcessor,
10129
+ handler5 as analyticsModelProcessor,
9773
10130
  handler2 as analyticsProcessor,
10131
+ analyticsQueryHandler,
10132
+ handler6 as analyticsViewProcessor,
9774
10133
  appHandler,
9775
10134
  handler as createEntityProcessor,
9776
10135
  index_default as default,
9777
- handler5 as mutualProcessor,
9778
- handler6 as prejoinProcessor,
9779
- handler7 as replicationProcessor,
10136
+ handler7 as mutualProcessor,
10137
+ handler8 as prejoinProcessor,
10138
+ handler9 as replicationProcessor,
9780
10139
  setupCommonRoutes,
9781
10140
  startBackfill as startAnalyticsBackfill,
9782
- handler8 as tagProcessor,
10141
+ handler10 as tagProcessor,
9783
10142
  transactional
9784
10143
  };
9785
10144
  //# sourceMappingURL=index.js.map