monorise 1.6.4 → 1.7.0-dev.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.
@@ -4,6 +4,7 @@ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
6
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
7
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
9
  var __spreadValues = (a, b) => {
9
10
  for (var prop in b || (b = {}))
@@ -53,6 +54,7 @@ var __async = (__this, __arguments, generator) => {
53
54
  step((generator = generator.apply(__this, __arguments)).next());
54
55
  });
55
56
  };
57
+ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
56
58
 
57
59
  // controllers/setupRoutes.ts
58
60
  import { Hono } from "hono";
@@ -2313,6 +2315,153 @@ var appHandler = (container) => ({ routes }) => {
2313
2315
  return handle(app);
2314
2316
  };
2315
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 { handle as handle2 } from "hono/aws-lambda";
2328
+ import { Hono as Hono3 } from "hono";
2329
+ import httpStatus4 from "http-status";
2330
+ var athena = new AthenaClient();
2331
+ var dynamo = new DynamoDBClient();
2332
+ function required(name) {
2333
+ const value = process.env[name];
2334
+ if (!value) throw new Error(`${name} is required.`);
2335
+ return value;
2336
+ }
2337
+ function queries() {
2338
+ return JSON.parse(required("ANALYTICS_QUERIES"));
2339
+ }
2340
+ function validParameter(value, type) {
2341
+ if (type === "string" && typeof value === "string") return value;
2342
+ if (type === "number" && typeof value === "number" && Number.isFinite(value)) return String(value);
2343
+ if (type === "boolean" && typeof value === "boolean") return String(value);
2344
+ if (type === "date" && typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
2345
+ if (type === "timestamp" && typeof value === "string" && !Number.isNaN(Date.parse(value))) return value;
2346
+ return void 0;
2347
+ }
2348
+ function apiKeys() {
2349
+ return process.env.ANALYTICS_API_KEYS ? JSON.parse(process.env.ANALYTICS_API_KEYS) : [];
2350
+ }
2351
+ function ownedExecution(id) {
2352
+ return __async(this, null, function* () {
2353
+ const item = yield dynamo.send(new GetItemCommand({
2354
+ TableName: required("ANALYTICS_EXECUTIONS_TABLE"),
2355
+ Key: { id: { S: id } },
2356
+ ConsistentRead: true
2357
+ }));
2358
+ return Boolean(item.Item);
2359
+ });
2360
+ }
2361
+ var analyticsQueryHandler = () => {
2362
+ const app = new Hono3().basePath("/analytics");
2363
+ app.use("*", (c, next) => __async(null, null, function* () {
2364
+ const key = c.req.header("x-api-key");
2365
+ if (!key || !apiKeys().includes(key)) {
2366
+ return c.json({ status: httpStatus4.UNAUTHORIZED, message: httpStatus4["401_MESSAGE"] }, httpStatus4.UNAUTHORIZED);
2367
+ }
2368
+ return next();
2369
+ }));
2370
+ app.get("/queries", (c) => c.json({
2371
+ queries: Object.entries(queries()).map(([name, query]) => {
2372
+ var _a;
2373
+ return { name, parameters: (_a = query.parameters) != null ? _a : {} };
2374
+ })
2375
+ }));
2376
+ app.post("/queries/:name/executions", (c) => __async(null, null, function* () {
2377
+ var _a;
2378
+ const query = queries()[c.req.param("name")];
2379
+ if (!query) return c.json({ message: "Unknown analytics query." }, httpStatus4.NOT_FOUND);
2380
+ const body = yield c.req.json().catch(() => ({}));
2381
+ const declared = (_a = query.parameters) != null ? _a : {};
2382
+ if (Object.keys(body).some((name) => !(name in declared))) {
2383
+ return c.json({ message: "Unexpected query parameter." }, httpStatus4.BAD_REQUEST);
2384
+ }
2385
+ const parameters = Object.entries(declared).map(([name, definition]) => {
2386
+ const value = validParameter(body[name], definition.type);
2387
+ if (value === void 0) throw new Error(`Invalid or missing parameter: ${name}.`);
2388
+ return value;
2389
+ });
2390
+ try {
2391
+ const started = yield athena.send(new StartQueryExecutionCommand({
2392
+ QueryString: query.sql,
2393
+ ExecutionParameters: parameters,
2394
+ WorkGroup: required("ANALYTICS_WORKGROUP"),
2395
+ QueryExecutionContext: { Database: required("ANALYTICS_DATABASE") },
2396
+ ResultConfiguration: { OutputLocation: required("ANALYTICS_ATHENA_OUTPUT") },
2397
+ ResultReuseConfiguration: query.resultReuse ? { ResultReuseByAgeConfiguration: { Enabled: true, MaxAgeInMinutes: query.resultReuse.maxAgeMinutes } } : void 0
2398
+ }));
2399
+ if (!started.QueryExecutionId) throw new Error("Athena did not return a query execution id.");
2400
+ yield dynamo.send(new PutItemCommand({
2401
+ TableName: required("ANALYTICS_EXECUTIONS_TABLE"),
2402
+ Item: {
2403
+ id: { S: started.QueryExecutionId },
2404
+ queryName: { S: c.req.param("name") },
2405
+ expiresAt: { N: String(Math.floor(Date.now() / 1e3) + 86400) }
2406
+ }
2407
+ }));
2408
+ return c.json({ queryExecutionId: started.QueryExecutionId, state: "QUEUED" }, httpStatus4.ACCEPTED);
2409
+ } catch (error) {
2410
+ if (error instanceof Error && error.message.startsWith("Invalid or missing parameter:")) {
2411
+ return c.json({ message: error.message }, httpStatus4.BAD_REQUEST);
2412
+ }
2413
+ throw error;
2414
+ }
2415
+ }));
2416
+ app.get("/executions/:id", (c) => __async(null, null, function* () {
2417
+ var _a, _b, _c, _d, _e;
2418
+ const id = c.req.param("id");
2419
+ if (!(yield ownedExecution(id))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
2420
+ const execution = yield athena.send(new GetQueryExecutionCommand({ QueryExecutionId: id }));
2421
+ const status = (_a = execution.QueryExecution) == null ? void 0 : _a.Status;
2422
+ return c.json({
2423
+ queryExecutionId: id,
2424
+ state: status == null ? void 0 : status.State,
2425
+ reason: status == null ? void 0 : status.StateChangeReason,
2426
+ statistics: (_b = execution.QueryExecution) == null ? void 0 : _b.Statistics,
2427
+ reusedPreviousResult: (_e = (_d = (_c = execution.QueryExecution) == null ? void 0 : _c.Statistics) == null ? void 0 : _d.ResultReuseInformation) == null ? void 0 : _e.ReusedPreviousResult
2428
+ });
2429
+ }));
2430
+ app.get("/executions/:id/results", (c) => __async(null, null, function* () {
2431
+ var _a, _b, _c, _d, _e, _f;
2432
+ const id = c.req.param("id");
2433
+ if (!(yield ownedExecution(id))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
2434
+ const requested = Number((_a = c.req.query("maxResults")) != null ? _a : 100);
2435
+ const maxResults = Number.isFinite(requested) ? Math.min(Math.max(requested, 1), 1e3) : 100;
2436
+ const nextToken = c.req.query("nextToken");
2437
+ const results = yield athena.send(new GetQueryResultsCommand({
2438
+ QueryExecutionId: id,
2439
+ NextToken: nextToken,
2440
+ MaxResults: maxResults
2441
+ }));
2442
+ const rows = (_c = (_b = results.ResultSet) == null ? void 0 : _b.Rows) != null ? _c : [];
2443
+ const columns = ((_f = (_e = (_d = results.ResultSet) == null ? void 0 : _d.ResultSetMetadata) == null ? void 0 : _e.ColumnInfo) != null ? _f : []).map((column) => column.Name);
2444
+ return c.json({
2445
+ columns,
2446
+ rows: rows.slice(nextToken ? 0 : 1).map((row) => {
2447
+ var _a2;
2448
+ return ((_a2 = row.Data) != null ? _a2 : []).map((value) => {
2449
+ var _a3;
2450
+ return (_a3 = value.VarCharValue) != null ? _a3 : null;
2451
+ });
2452
+ }),
2453
+ nextToken: results.NextToken
2454
+ });
2455
+ }));
2456
+ app.post("/executions/:id/cancel", (c) => __async(null, null, function* () {
2457
+ const id = c.req.param("id");
2458
+ if (!(yield ownedExecution(id))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
2459
+ yield athena.send(new StopQueryExecutionCommand({ QueryExecutionId: id }));
2460
+ return c.body(null, httpStatus4.NO_CONTENT);
2461
+ }));
2462
+ return handle2(app);
2463
+ };
2464
+
2316
2465
  // processors/create-entity-processor.ts
2317
2466
  var handler = (container) => (ev) => __async(null, null, function* () {
2318
2467
  const { entityService } = container;
@@ -2349,12 +2498,653 @@ var handler = (container) => (ev) => __async(null, null, function* () {
2349
2498
  return { batchItemFailures };
2350
2499
  });
2351
2500
 
2501
+ // processors/analytics-processor.ts
2502
+ import {
2503
+ FirehoseClient,
2504
+ PutRecordBatchCommand
2505
+ } from "@aws-sdk/client-firehose";
2506
+ import { unmarshall as unmarshall4 } from "@aws-sdk/util-dynamodb";
2507
+ var firehose = new FirehoseClient();
2508
+ function encodeAnalyticsEvent(event) {
2509
+ return {
2510
+ event_id: event.eventId,
2511
+ idempotency_key: event.idempotencyKey,
2512
+ ordering_key: event.orderingKey,
2513
+ sequence_number: event.sequenceNumber,
2514
+ operation: event.operation,
2515
+ occurred_at: event.occurredAt,
2516
+ dataset: event.dataset,
2517
+ kind: event.kind,
2518
+ path: event.path,
2519
+ before: event.before ? JSON.stringify(event.before) : void 0,
2520
+ after: event.after ? JSON.stringify(event.after) : void 0
2521
+ };
2522
+ }
2523
+ function omitTopLevelFields(value, fields) {
2524
+ if (!value) return value;
2525
+ return Object.fromEntries(
2526
+ Object.entries(value).filter(([key]) => !fields.has(key))
2527
+ );
2528
+ }
2529
+ function sanitizeItem(item, omittedFields) {
2530
+ if (!item) return item;
2531
+ return __spreadProps(__spreadValues({}, item), {
2532
+ data: omitTopLevelFields(
2533
+ item.data,
2534
+ omittedFields
2535
+ ),
2536
+ mutualData: omitTopLevelFields(
2537
+ item.mutualData,
2538
+ omittedFields
2539
+ )
2540
+ });
2541
+ }
2542
+ function parseAnalyticsManifest() {
2543
+ const raw = process.env.ANALYTICS_MANIFEST;
2544
+ if (!raw) throw new Error("ANALYTICS_MANIFEST is required.");
2545
+ return JSON.parse(raw);
2546
+ }
2547
+ function datasetForRecord(record, manifest2, config) {
2548
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2549
+ const image = (_c = (_a = record.dynamodb) == null ? void 0 : _a.NewImage) != null ? _c : (_b = record.dynamodb) == null ? void 0 : _b.OldImage;
2550
+ if (!((_d = image == null ? void 0 : image.PK) == null ? void 0 : _d.S) || ((_e = image.SK) == null ? void 0 : _e.S) !== "#METADATA#") return void 0;
2551
+ if (!image.PK.S.startsWith("MUTUAL#")) {
2552
+ const entityType = (_f = image.entityType) == null ? void 0 : _f.S;
2553
+ const dataset = manifest2.datasets.find(
2554
+ (candidate) => candidate.kind === "entity" && candidate.name === entityType
2555
+ );
2556
+ return dataset && {
2557
+ name: dataset.name,
2558
+ kind: dataset.kind,
2559
+ granularity: dataset.partition.granularity
2560
+ };
2561
+ }
2562
+ const item = unmarshall4(image);
2563
+ const pair = [item.byEntityType, item.entityType].sort().join("::");
2564
+ for (const entityConfig of Object.values(config)) {
2565
+ for (const field of Object.values(
2566
+ (_h = (_g = entityConfig.mutual) == null ? void 0 : _g.mutualFields) != null ? _h : {}
2567
+ )) {
2568
+ const mutual = field.mutual;
2569
+ if (!(mutual == null ? void 0 : mutual.name)) continue;
2570
+ if ([entityConfig.name, field.entityType].sort().join("::") !== pair) continue;
2571
+ const dataset = manifest2.datasets.find(
2572
+ (candidate) => candidate.kind === "mutual" && candidate.name === mutual.name
2573
+ );
2574
+ return dataset && {
2575
+ name: dataset.name,
2576
+ kind: dataset.kind,
2577
+ granularity: dataset.partition.granularity
2578
+ };
2579
+ }
2580
+ }
2581
+ }
2582
+ var handler2 = (config) => (event) => __async(null, null, function* () {
2583
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
2584
+ const streamName = process.env.ANALYTICS_DELIVERY_STREAM;
2585
+ if (!streamName) throw new Error("ANALYTICS_DELIVERY_STREAM is required.");
2586
+ const manifest2 = parseAnalyticsManifest();
2587
+ const omittedFields = new Set(
2588
+ JSON.parse((_a = process.env.ANALYTICS_OMIT_FIELDS) != null ? _a : "[]")
2589
+ );
2590
+ const failures = [];
2591
+ const events = [];
2592
+ for (const record of event.Records) {
2593
+ try {
2594
+ const dataset = datasetForRecord(record, manifest2, config);
2595
+ if (!dataset || !record.eventName || !record.eventID) continue;
2596
+ const occurredAt = new Date(
2597
+ Number(
2598
+ (_c = (_b = record.dynamodb) == null ? void 0 : _b.ApproximateCreationDateTime) != null ? _c : Date.now() / 1e3
2599
+ ) * 1e3
2600
+ );
2601
+ const eventDate = occurredAt.toISOString().slice(0, 10);
2602
+ const eventHour = occurredAt.toISOString().slice(11, 13);
2603
+ const path = `${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/event_date=${eventDate}${dataset.granularity === "hour" ? `/event_hour=${eventHour}` : ""}`;
2604
+ events.push({
2605
+ record,
2606
+ event: {
2607
+ eventId: record.eventID,
2608
+ idempotencyKey: record.eventID,
2609
+ orderingKey: (_e = (_d = record.dynamodb) == null ? void 0 : _d.SequenceNumber) != null ? _e : record.eventID,
2610
+ sequenceNumber: (_f = record.dynamodb) == null ? void 0 : _f.SequenceNumber,
2611
+ operation: record.eventName,
2612
+ occurredAt: occurredAt.toISOString(),
2613
+ dataset: dataset.name,
2614
+ kind: dataset.kind,
2615
+ path,
2616
+ before: sanitizeItem(
2617
+ ((_g = record.dynamodb) == null ? void 0 : _g.OldImage) ? unmarshall4(record.dynamodb.OldImage) : void 0,
2618
+ omittedFields
2619
+ ),
2620
+ after: sanitizeItem(
2621
+ ((_h = record.dynamodb) == null ? void 0 : _h.NewImage) ? unmarshall4(record.dynamodb.NewImage) : void 0,
2622
+ omittedFields
2623
+ )
2624
+ }
2625
+ });
2626
+ } catch (error) {
2627
+ console.error("Unable to normalize analytics stream record", error);
2628
+ failures.push({ itemIdentifier: (_j = (_i = record.dynamodb) == null ? void 0 : _i.SequenceNumber) != null ? _j : "" });
2629
+ }
2630
+ }
2631
+ for (let index = 0; index < events.length; index += 500) {
2632
+ const batch = events.slice(index, index + 500);
2633
+ const result = yield firehose.send(
2634
+ new PutRecordBatchCommand({
2635
+ DeliveryStreamName: streamName,
2636
+ Records: batch.map(({ event: value }) => ({
2637
+ Data: Buffer.from(`${JSON.stringify(encodeAnalyticsEvent(value))}
2638
+ `)
2639
+ }))
2640
+ })
2641
+ );
2642
+ (_k = result.RequestResponses) == null ? void 0 : _k.forEach((response, responseIndex) => {
2643
+ var _a2, _b2, _c2;
2644
+ if (!response.ErrorCode) return;
2645
+ failures.push({
2646
+ itemIdentifier: (_c2 = (_b2 = (_a2 = batch[responseIndex]) == null ? void 0 : _a2.record.dynamodb) == null ? void 0 : _b2.SequenceNumber) != null ? _c2 : ""
2647
+ });
2648
+ });
2649
+ }
2650
+ return { batchItemFailures: failures };
2651
+ });
2652
+
2653
+ // processors/analytics-backfill-processor.ts
2654
+ import {
2655
+ DeleteItemCommand,
2656
+ DynamoDBClient as DynamoDBClient2,
2657
+ ExportTableToPointInTimeCommand,
2658
+ GetItemCommand as GetItemCommand2,
2659
+ PutItemCommand as PutItemCommand2,
2660
+ UpdateItemCommand
2661
+ } from "@aws-sdk/client-dynamodb";
2662
+ import { FirehoseClient as FirehoseClient2, PutRecordBatchCommand as PutRecordBatchCommand2 } from "@aws-sdk/client-firehose";
2663
+ import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
2664
+ import { marshall as marshall5, unmarshall as unmarshall5 } from "@aws-sdk/util-dynamodb";
2665
+ import { gunzipSync } from "zlib";
2666
+ var dynamodb = new DynamoDBClient2();
2667
+ var firehose2 = new FirehoseClient2();
2668
+ var s3 = new S3Client();
2669
+ var backfillMarker = { PK: "#ANALYTICS#", SK: "#BACKFILL#" };
2670
+ function required2(name) {
2671
+ const value = process.env[name];
2672
+ if (!value) throw new Error(`${name} is required.`);
2673
+ return value;
2674
+ }
2675
+ function exportTimestamp() {
2676
+ const value = process.env.ANALYTICS_EXPORT_TIME;
2677
+ const timestamp = value ? new Date(value) : /* @__PURE__ */ new Date();
2678
+ if (Number.isNaN(timestamp.getTime())) {
2679
+ throw new Error("ANALYTICS_EXPORT_TIME must be an ISO-8601 timestamp.");
2680
+ }
2681
+ return timestamp;
2682
+ }
2683
+ function startBackfill(reconcile = false) {
2684
+ return __async(this, null, function* () {
2685
+ var _a, _b, _c;
2686
+ const timestamp = exportTimestamp();
2687
+ const tableName = required2("ANALYTICS_BACKFILL_MARKER_TABLE");
2688
+ const marker = marshall5(__spreadProps(__spreadValues({}, backfillMarker), { exportTime: timestamp.toISOString(), state: "starting" }));
2689
+ let createdMarker = false;
2690
+ try {
2691
+ yield dynamodb.send(new PutItemCommand2({ TableName: tableName, Item: marker, ConditionExpression: "attribute_not_exists(PK)" }));
2692
+ createdMarker = true;
2693
+ } catch (error) {
2694
+ if (error.name !== "ConditionalCheckFailedException") throw error;
2695
+ if (reconcile) {
2696
+ yield dynamodb.send(new UpdateItemCommand({
2697
+ TableName: tableName,
2698
+ Key: marshall5(backfillMarker),
2699
+ UpdateExpression: "SET exportTime = :exportTime, #state = :state REMOVE exportArn",
2700
+ ExpressionAttributeNames: { "#state": "state" },
2701
+ ExpressionAttributeValues: marshall5({ ":exportTime": timestamp.toISOString(), ":state": "starting" })
2702
+ }));
2703
+ } else {
2704
+ const existing = yield dynamodb.send(new GetItemCommand2({ TableName: tableName, Key: marshall5(backfillMarker), ConsistentRead: true }));
2705
+ const value = existing.Item ? unmarshall5(existing.Item) : {};
2706
+ return { exportArn: value.exportArn, exportTime: value.exportTime, started: false };
2707
+ }
2708
+ }
2709
+ let result;
2710
+ try {
2711
+ result = yield dynamodb.send(new ExportTableToPointInTimeCommand({
2712
+ TableArn: required2("ANALYTICS_TABLE_ARN"),
2713
+ S3Bucket: required2("ANALYTICS_BACKFILL_BUCKET"),
2714
+ S3Prefix: (_a = process.env.ANALYTICS_BACKFILL_PREFIX) != null ? _a : "backfill",
2715
+ ExportTime: timestamp,
2716
+ ExportFormat: "DYNAMODB_JSON"
2717
+ }));
2718
+ } catch (error) {
2719
+ if (createdMarker) {
2720
+ yield dynamodb.send(new DeleteItemCommand({
2721
+ TableName: tableName,
2722
+ Key: marshall5(backfillMarker),
2723
+ ConditionExpression: "exportTime = :exportTime",
2724
+ ExpressionAttributeValues: marshall5({ ":exportTime": timestamp.toISOString() })
2725
+ }));
2726
+ } else {
2727
+ yield dynamodb.send(new UpdateItemCommand({
2728
+ TableName: tableName,
2729
+ Key: marshall5(backfillMarker),
2730
+ UpdateExpression: "SET #state = :state",
2731
+ ConditionExpression: "exportTime = :exportTime",
2732
+ ExpressionAttributeNames: { "#state": "state" },
2733
+ ExpressionAttributeValues: marshall5({ ":state": "failed", ":exportTime": timestamp.toISOString() })
2734
+ }));
2735
+ }
2736
+ throw error;
2737
+ }
2738
+ yield dynamodb.send(new UpdateItemCommand({
2739
+ TableName: tableName,
2740
+ Key: marshall5(backfillMarker),
2741
+ UpdateExpression: "SET #state = :state, exportArn = :exportArn",
2742
+ ConditionExpression: "exportTime = :exportTime",
2743
+ ExpressionAttributeNames: { "#state": "state" },
2744
+ ExpressionAttributeValues: marshall5({ ":state": "started", ":exportArn": (_b = result.ExportDescription) == null ? void 0 : _b.ExportArn, ":exportTime": timestamp.toISOString() }, { removeUndefinedValues: true })
2745
+ }));
2746
+ return { exportArn: (_c = result.ExportDescription) == null ? void 0 : _c.ExportArn, exportTime: timestamp.toISOString(), started: true };
2747
+ });
2748
+ }
2749
+ function backfillTimestamp() {
2750
+ return __async(this, null, function* () {
2751
+ const tableName = process.env.ANALYTICS_BACKFILL_MARKER_TABLE;
2752
+ if (!tableName) return exportTimestamp();
2753
+ const result = yield dynamodb.send(new GetItemCommand2({ TableName: tableName, Key: marshall5(backfillMarker), ConsistentRead: true }));
2754
+ const value = result.Item ? unmarshall5(result.Item).exportTime : void 0;
2755
+ if (typeof value !== "string") throw new Error("Analytics backfill marker is missing its export timestamp.");
2756
+ const timestamp = new Date(value);
2757
+ if (Number.isNaN(timestamp.getTime())) throw new Error("Analytics backfill marker has an invalid export timestamp.");
2758
+ return timestamp;
2759
+ });
2760
+ }
2761
+ function streamToBuffer(stream) {
2762
+ return (() => __async(null, null, function* () {
2763
+ const chunks = [];
2764
+ try {
2765
+ for (var iter = __forAwait(stream), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
2766
+ const chunk = temp.value;
2767
+ chunks.push(chunk);
2768
+ }
2769
+ } catch (temp) {
2770
+ error = [temp];
2771
+ } finally {
2772
+ try {
2773
+ more && (temp = iter.return) && (yield temp.call(iter));
2774
+ } finally {
2775
+ if (error)
2776
+ throw error[0];
2777
+ }
2778
+ }
2779
+ return Buffer.concat(chunks);
2780
+ }))();
2781
+ }
2782
+ function snapshotEvent(item, config, occurredAt, omittedFields) {
2783
+ const attributes = marshall5(item, { removeUndefinedValues: true });
2784
+ const dataset = datasetForRecord({ dynamodb: { NewImage: attributes } }, parseAnalyticsManifest(), config);
2785
+ if (!dataset) return void 0;
2786
+ const after = sanitizeItem(item, omittedFields);
2787
+ const key = `${String(item.PK)}:${String(item.SK)}`;
2788
+ const path = `${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/event_date=${occurredAt.toISOString().slice(0, 10)}${dataset.granularity === "hour" ? `/event_hour=${occurredAt.toISOString().slice(11, 13)}` : ""}`;
2789
+ return {
2790
+ eventId: `snapshot:${key}:${occurredAt.toISOString()}`,
2791
+ idempotencyKey: `snapshot:${key}:${occurredAt.toISOString()}`,
2792
+ orderingKey: occurredAt.toISOString(),
2793
+ operation: "SNAPSHOT",
2794
+ occurredAt: occurredAt.toISOString(),
2795
+ dataset: dataset.name,
2796
+ kind: dataset.kind,
2797
+ path,
2798
+ after
2799
+ };
2800
+ }
2801
+ var handler3 = (config) => (event) => __async(null, null, function* () {
2802
+ var _a;
2803
+ if (!("Records" in event)) {
2804
+ if (event.action === "start") return startBackfill();
2805
+ if (event.action === "reconcile") return startBackfill(true);
2806
+ throw new Error("Unsupported analytics backfill event.");
2807
+ }
2808
+ const timestamp = yield backfillTimestamp();
2809
+ const omittedFields = new Set(JSON.parse((_a = process.env.ANALYTICS_OMIT_FIELDS) != null ? _a : "[]"));
2810
+ const deliveryStream = required2("ANALYTICS_DELIVERY_STREAM");
2811
+ let delivered = 0;
2812
+ for (const record of event.Records) {
2813
+ const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
2814
+ if (!key.endsWith(".json.gz")) continue;
2815
+ const response = yield s3.send(new GetObjectCommand({ Bucket: record.s3.bucket.name, Key: key }));
2816
+ if (!response.Body) throw new Error(`Backfill export object ${key} has no body.`);
2817
+ const content = gunzipSync(yield streamToBuffer(response.Body)).toString("utf8");
2818
+ const events = content.split("\n").filter(Boolean).flatMap((line) => {
2819
+ const attributes = JSON.parse(line).Item;
2820
+ return attributes ? [snapshotEvent(unmarshall5(attributes), config, timestamp, omittedFields)].filter(Boolean) : [];
2821
+ });
2822
+ for (let index = 0; index < events.length; index += 500) {
2823
+ const batch = events.slice(index, index + 500);
2824
+ const result = yield firehose2.send(new PutRecordBatchCommand2({ DeliveryStreamName: deliveryStream, Records: batch.map((value) => ({ Data: Buffer.from(`${JSON.stringify(encodeAnalyticsEvent(value))}
2825
+ `) })) }));
2826
+ if (result.FailedPutCount) throw new Error(`Failed to deliver ${result.FailedPutCount} backfill records; retry this export object.`);
2827
+ delivered += batch.length;
2828
+ }
2829
+ }
2830
+ return { delivered, exportTime: timestamp.toISOString() };
2831
+ });
2832
+
2833
+ // processors/analytics-materialization-processor.ts
2834
+ import {
2835
+ AthenaClient as AthenaClient2,
2836
+ GetQueryExecutionCommand as GetQueryExecutionCommand2,
2837
+ GetQueryResultsCommand as GetQueryResultsCommand2,
2838
+ StartQueryExecutionCommand as StartQueryExecutionCommand2
2839
+ } from "@aws-sdk/client-athena";
2840
+ var athena2 = new AthenaClient2();
2841
+ function required3(name) {
2842
+ const value = process.env[name];
2843
+ if (!value) throw new Error(`${name} is required.`);
2844
+ return value;
2845
+ }
2846
+ function quoteIdentifier(identifier) {
2847
+ return `"${identifier.replaceAll('"', '""')}"`;
2848
+ }
2849
+ function quoteLiteral(value) {
2850
+ return `'${value.replaceAll("'", "''")}'`;
2851
+ }
2852
+ function manifest() {
2853
+ return JSON.parse(required3("ANALYTICS_MANIFEST"));
2854
+ }
2855
+ function valueExpression(column, kind) {
2856
+ const payload = "coalesce(after, before)";
2857
+ const path = `$.${kind === "mutual" ? "mutualData" : "data"}.${column.sourceName.replaceAll('"', '\\"')}`;
2858
+ const scalar = `json_extract_scalar(payload, ${quoteLiteral(path)})`;
2859
+ switch (column.type) {
2860
+ case "boolean":
2861
+ return `try_cast(${scalar} AS boolean)`;
2862
+ case "double":
2863
+ return `try_cast(${scalar} AS double)`;
2864
+ case "timestamp":
2865
+ return `try_cast(from_iso8601_timestamp(${scalar}) AS timestamp)`;
2866
+ case "json":
2867
+ return `json_format(json_extract(payload, ${quoteLiteral(path)}))`;
2868
+ default:
2869
+ return scalar;
2870
+ }
2871
+ }
2872
+ function endpointExpression(endpoint) {
2873
+ const payload = "coalesce(after, before)";
2874
+ if (endpoint.role === "source") {
2875
+ return `json_extract_scalar(${payload}, '$.byEntityId')`;
2876
+ }
2877
+ if (endpoint.role === "target") {
2878
+ return `json_extract_scalar(${payload}, '$.entityId')`;
2879
+ }
2880
+ const entityName = quoteLiteral(endpoint.entityName);
2881
+ 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`;
2882
+ }
2883
+ function datasetSql(dataset, database, bucket) {
2884
+ var _a;
2885
+ const history = `${quoteIdentifier(database)}.${quoteIdentifier(dataset.historyTable)}`;
2886
+ const current = `${quoteIdentifier(database)}.${quoteIdentifier(dataset.currentTable)}`;
2887
+ const raw = `${quoteIdentifier(database)}.${quoteIdentifier((_a = dataset.rawTable) != null ? _a : `${dataset.historyTable}_raw`)}`;
2888
+ const typedColumns = dataset.columns.map(
2889
+ (column) => `${quoteIdentifier(column.name)} ${column.type === "json" ? "varchar" : column.type}`
2890
+ );
2891
+ const names = dataset.columns.map((column) => quoteIdentifier(column.name));
2892
+ const endpointNames = dataset.endpoints.map(
2893
+ (endpoint) => quoteIdentifier(endpoint.column)
2894
+ );
2895
+ const values = dataset.columns.map(
2896
+ (column) => valueExpression(column, dataset.kind)
2897
+ );
2898
+ const payload = "coalesce(after, before)";
2899
+ const idPath = dataset.kind === "entity" ? "$.entityId" : "$.mutualId";
2900
+ const selected = [
2901
+ "event_id",
2902
+ "idempotency_key",
2903
+ "ordering_key",
2904
+ "sequence_number",
2905
+ "operation",
2906
+ "try_cast(from_iso8601_timestamp(occurred_at) AS timestamp) AS occurred_at",
2907
+ `json_extract_scalar(${payload}, ${quoteLiteral(idPath)}) AS ${quoteIdentifier(dataset.idColumn)}`,
2908
+ "before AS before_json",
2909
+ "after AS after_json",
2910
+ ...dataset.endpoints.map(
2911
+ (endpoint) => `${endpointExpression(endpoint)} AS ${quoteIdentifier(endpoint.column)}`
2912
+ ),
2913
+ ...values.map((value, index) => `${value} AS ${names[index]}`)
2914
+ ];
2915
+ const allColumns = [
2916
+ "event_id varchar",
2917
+ "idempotency_key varchar",
2918
+ "ordering_key varchar",
2919
+ "sequence_number varchar",
2920
+ "operation varchar",
2921
+ "occurred_at timestamp",
2922
+ `${quoteIdentifier(dataset.idColumn)} varchar`,
2923
+ "before_json varchar",
2924
+ "after_json varchar",
2925
+ ...endpointNames.map((name) => `${name} varchar`),
2926
+ ...typedColumns
2927
+ ];
2928
+ const historyNames = [
2929
+ "event_id",
2930
+ "idempotency_key",
2931
+ "ordering_key",
2932
+ "sequence_number",
2933
+ "operation",
2934
+ "occurred_at",
2935
+ dataset.idColumn,
2936
+ "before_json",
2937
+ "after_json",
2938
+ ...dataset.endpoints.map((endpoint) => endpoint.column),
2939
+ ...dataset.columns.map((column) => column.name)
2940
+ ].map(quoteIdentifier).join(", ");
2941
+ const insertValues = [
2942
+ "s.event_id",
2943
+ "s.idempotency_key",
2944
+ "s.ordering_key",
2945
+ "s.sequence_number",
2946
+ "s.operation",
2947
+ "s.occurred_at",
2948
+ `s.${quoteIdentifier(dataset.idColumn)}`,
2949
+ "s.before_json",
2950
+ "s.after_json",
2951
+ ...endpointNames.map((name) => `s.${name}`),
2952
+ ...names.map((name) => `s.${name}`)
2953
+ ].join(", ");
2954
+ return [
2955
+ `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')`,
2956
+ `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})`,
2957
+ `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')`,
2958
+ `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 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(", ")}` : ""})`
2959
+ ];
2960
+ }
2961
+ function execute(statement) {
2962
+ return __async(this, null, function* () {
2963
+ var _a, _b;
2964
+ const started = yield athena2.send(
2965
+ new StartQueryExecutionCommand2({
2966
+ QueryString: statement,
2967
+ WorkGroup: required3("ANALYTICS_WORKGROUP"),
2968
+ QueryExecutionContext: { Database: required3("ANALYTICS_DATABASE") },
2969
+ ResultConfiguration: {
2970
+ OutputLocation: required3("ANALYTICS_ATHENA_OUTPUT")
2971
+ }
2972
+ })
2973
+ );
2974
+ if (!started.QueryExecutionId)
2975
+ throw new Error("Athena did not return a query execution id.");
2976
+ for (; ; ) {
2977
+ const status = (_a = (yield athena2.send(
2978
+ new GetQueryExecutionCommand2({
2979
+ QueryExecutionId: started.QueryExecutionId
2980
+ })
2981
+ )).QueryExecution) == null ? void 0 : _a.Status;
2982
+ if ((status == null ? void 0 : status.State) === "SUCCEEDED") return started.QueryExecutionId;
2983
+ if ((status == null ? void 0 : status.State) === "FAILED" || (status == null ? void 0 : status.State) === "CANCELLED") {
2984
+ throw new Error(
2985
+ `Athena materialization query ${started.QueryExecutionId} ${status.State}: ${(_b = status.StateChangeReason) != null ? _b : "no reason provided"}`
2986
+ );
2987
+ }
2988
+ yield new Promise((resolve) => setTimeout(resolve, 1e3));
2989
+ }
2990
+ });
2991
+ }
2992
+ function tableColumns(database, table) {
2993
+ return __async(this, null, function* () {
2994
+ var _a, _b;
2995
+ const queryExecutionId = yield execute(
2996
+ `SELECT column_name FROM information_schema.columns WHERE table_schema = ${quoteLiteral(database)} AND table_name = ${quoteLiteral(table)}`
2997
+ );
2998
+ const result = yield athena2.send(
2999
+ new GetQueryResultsCommand2({ QueryExecutionId: queryExecutionId })
3000
+ );
3001
+ return new Set(
3002
+ ((_b = (_a = result.ResultSet) == null ? void 0 : _a.Rows) != null ? _b : []).slice(1).map((row) => {
3003
+ var _a2, _b2;
3004
+ return (_b2 = (_a2 = row.Data) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.VarCharValue;
3005
+ }).filter((name) => Boolean(name))
3006
+ );
3007
+ });
3008
+ }
3009
+ function addMissingColumns(database, table, columns) {
3010
+ return __async(this, null, function* () {
3011
+ const existing = yield tableColumns(database, table);
3012
+ const missing = columns.filter(
3013
+ (column) => {
3014
+ var _a, _b;
3015
+ return !existing.has(
3016
+ (_b = (_a = column.match(/^"((?:[^"]|"")+)"/)) == null ? void 0 : _a[1].replaceAll('""', '"')) != null ? _b : ""
3017
+ );
3018
+ }
3019
+ );
3020
+ if (missing.length)
3021
+ yield execute(
3022
+ `ALTER TABLE ${quoteIdentifier(database)}.${quoteIdentifier(table)} ADD COLUMNS (${missing.join(", ")})`
3023
+ );
3024
+ });
3025
+ }
3026
+ function generatedColumns(dataset) {
3027
+ return [
3028
+ `${quoteIdentifier(dataset.idColumn)} varchar`,
3029
+ ...dataset.endpoints.map(
3030
+ (endpoint) => `${quoteIdentifier(endpoint.column)} varchar`
3031
+ )
3032
+ ];
3033
+ }
3034
+ var handler4 = () => __async(null, null, function* () {
3035
+ const database = required3("ANALYTICS_DATABASE");
3036
+ const bucket = required3("ANALYTICS_BUCKET");
3037
+ for (const dataset of manifest().datasets) {
3038
+ const statements = datasetSql(dataset, database, bucket);
3039
+ yield execute(statements[0]);
3040
+ yield addMissingColumns(
3041
+ database,
3042
+ dataset.historyTable,
3043
+ [...generatedColumns(dataset), ...dataset.columns.map(
3044
+ (column) => `${quoteIdentifier(column.name)} ${column.type === "json" ? "varchar" : column.type}`
3045
+ )]
3046
+ );
3047
+ yield execute(statements[2]);
3048
+ yield addMissingColumns(
3049
+ database,
3050
+ dataset.currentTable,
3051
+ [...generatedColumns(dataset), ...dataset.columns.map(
3052
+ (column) => `${quoteIdentifier(column.name)} ${column.type === "json" ? "varchar" : column.type}`
3053
+ )]
3054
+ );
3055
+ for (const statement of [statements[1], statements[3]]) {
3056
+ yield execute(statement);
3057
+ }
3058
+ }
3059
+ });
3060
+
3061
+ // processors/analytics-model-processor.ts
3062
+ import { AthenaClient as AthenaClient3, GetQueryExecutionCommand as GetQueryExecutionCommand3, StartQueryExecutionCommand as StartQueryExecutionCommand3 } from "@aws-sdk/client-athena";
3063
+ var athena3 = new AthenaClient3();
3064
+ function required4(name) {
3065
+ const value = process.env[name];
3066
+ if (!value) throw new Error(`${name} is required.`);
3067
+ return value;
3068
+ }
3069
+ function quote(identifier) {
3070
+ return `"${identifier.replaceAll('"', '""')}"`;
3071
+ }
3072
+ function execute2(statement) {
3073
+ return __async(this, null, function* () {
3074
+ var _a, _b;
3075
+ const started = yield athena3.send(new StartQueryExecutionCommand3({
3076
+ QueryString: statement,
3077
+ WorkGroup: required4("ANALYTICS_WORKGROUP"),
3078
+ QueryExecutionContext: { Database: required4("ANALYTICS_DATABASE") },
3079
+ ResultConfiguration: { OutputLocation: required4("ANALYTICS_ATHENA_OUTPUT") }
3080
+ }));
3081
+ if (!started.QueryExecutionId) throw new Error("Athena did not return a query execution id.");
3082
+ for (; ; ) {
3083
+ const status = (_a = (yield athena3.send(new GetQueryExecutionCommand3({ QueryExecutionId: started.QueryExecutionId }))).QueryExecution) == null ? void 0 : _a.Status;
3084
+ if ((status == null ? void 0 : status.State) === "SUCCEEDED") return;
3085
+ 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"}`);
3086
+ yield new Promise((resolve) => setTimeout(resolve, 1e3));
3087
+ }
3088
+ });
3089
+ }
3090
+ function modelStatements(model, database, bucket, now = /* @__PURE__ */ new Date()) {
3091
+ const table = model.name.replaceAll("-", "_");
3092
+ const end = now;
3093
+ const start = new Date(end.getTime() - model.lookbackDays * 864e5);
3094
+ const source = model.sql.replaceAll("{{windowStart}}", `'${start.toISOString().replaceAll("'", "''")}'`).replaceAll("{{windowEnd}}", `'${end.toISOString().replaceAll("'", "''")}'`);
3095
+ const target = `${quote(database)}.${quote(table)}`;
3096
+ const location = `s3://${bucket}/models/${table}/`;
3097
+ const partitionStart = start.toISOString().slice(0, 10);
3098
+ return [
3099
+ `CREATE TABLE IF NOT EXISTS ${target} WITH (table_type = 'ICEBERG', location = '${location}', partitioning = ARRAY['${model.partitionColumn}']) AS ${source}`,
3100
+ `DELETE FROM ${target} WHERE ${quote(model.partitionColumn)} >= DATE '${partitionStart}'`,
3101
+ `INSERT INTO ${target} ${source}`
3102
+ ];
3103
+ }
3104
+ var handler5 = () => __async(null, null, function* () {
3105
+ const model = JSON.parse(required4("ANALYTICS_MODEL"));
3106
+ for (const statement of modelStatements(model, required4("ANALYTICS_DATABASE"), required4("ANALYTICS_BUCKET"))) {
3107
+ yield execute2(statement);
3108
+ }
3109
+ });
3110
+
3111
+ // processors/analytics-view-processor.ts
3112
+ import { AthenaClient as AthenaClient4, GetQueryExecutionCommand as GetQueryExecutionCommand4, StartQueryExecutionCommand as StartQueryExecutionCommand4 } from "@aws-sdk/client-athena";
3113
+ var athena4 = new AthenaClient4();
3114
+ function required5(name) {
3115
+ const value = process.env[name];
3116
+ if (!value) throw new Error(`${name} is required.`);
3117
+ return value;
3118
+ }
3119
+ function quote2(identifier) {
3120
+ return `"${identifier.replaceAll('"', '""')}"`;
3121
+ }
3122
+ var handler6 = () => __async(null, null, function* () {
3123
+ var _a, _b;
3124
+ const view = JSON.parse(required5("ANALYTICS_VIEW"));
3125
+ const started = yield athena4.send(new StartQueryExecutionCommand4({
3126
+ QueryString: `CREATE OR REPLACE VIEW ${quote2(required5("ANALYTICS_DATABASE"))}.${quote2(view.name.replaceAll("-", "_"))} AS ${view.sql}`,
3127
+ WorkGroup: required5("ANALYTICS_WORKGROUP"),
3128
+ QueryExecutionContext: { Database: required5("ANALYTICS_DATABASE") },
3129
+ ResultConfiguration: { OutputLocation: required5("ANALYTICS_ATHENA_OUTPUT") }
3130
+ }));
3131
+ if (!started.QueryExecutionId) throw new Error("Athena did not return a query execution id.");
3132
+ for (; ; ) {
3133
+ const status = (_a = (yield athena4.send(new GetQueryExecutionCommand4({ QueryExecutionId: started.QueryExecutionId }))).QueryExecution) == null ? void 0 : _a.Status;
3134
+ if ((status == null ? void 0 : status.State) === "SUCCEEDED") return;
3135
+ if ((status == null ? void 0 : status.State) === "FAILED" || (status == null ? void 0 : status.State) === "CANCELLED") {
3136
+ throw new Error(`Analytics view ${view.name} ${status.State}: ${(_b = status.StateChangeReason) != null ? _b : "no reason provided"}`);
3137
+ }
3138
+ yield new Promise((resolve) => setTimeout(resolve, 1e3));
3139
+ }
3140
+ });
3141
+
2352
3142
  // processors/mutual-processor.ts
2353
3143
  import { TransactionCanceledException as TransactionCanceledException3 } from "@aws-sdk/client-dynamodb";
2354
3144
  var processEntities = (entityIds, action) => __async(null, null, function* () {
2355
3145
  return Promise.allSettled(entityIds.map(action));
2356
3146
  });
2357
- var handler2 = (container) => (ev) => __async(null, null, function* () {
3147
+ var handler7 = (container) => (ev) => __async(null, null, function* () {
2358
3148
  const batchItemFailures = [];
2359
3149
  const { entityRepository, mutualRepository, publishEvent: publishEvent2 } = container;
2360
3150
  yield Promise.allSettled(
@@ -2695,7 +3485,7 @@ function publishToSubscribers(_0) {
2695
3485
  );
2696
3486
  });
2697
3487
  }
2698
- var handler3 = (container) => (ev) => __async(null, null, function* () {
3488
+ var handler8 = (container) => (ev) => __async(null, null, function* () {
2699
3489
  var _a, _b, _c, _d, _e, _f, _g, _h;
2700
3490
  const batchItemFailures = [];
2701
3491
  const { mutualRepository, publishEvent: publishEvent2 } = container;
@@ -2748,7 +3538,7 @@ var handler3 = (container) => (ev) => __async(null, null, function* () {
2748
3538
 
2749
3539
  // processors/replication-processor.ts
2750
3540
  import { ConditionalCheckFailedException as ConditionalCheckFailedException2 } from "@aws-sdk/client-dynamodb";
2751
- var handler4 = (container) => (event) => __async(null, null, function* () {
3541
+ var handler9 = (container) => (event) => __async(null, null, function* () {
2752
3542
  var _a, _b, _c, _d, _e, _f, _g;
2753
3543
  const TableName = process.env.DDB_TABLE || container.coreTable;
2754
3544
  const batchItemFailures = [];
@@ -3012,7 +3802,7 @@ function batchUpdateTags(_0) {
3012
3802
  yield Promise.all(addPromises);
3013
3803
  });
3014
3804
  }
3015
- var handler5 = (container) => (ev) => __async(null, null, function* () {
3805
+ var handler10 = (container) => (ev) => __async(null, null, function* () {
3016
3806
  var _a;
3017
3807
  const batchItemFailures = [];
3018
3808
  for (const record of ev.Records) {
@@ -3154,7 +3944,7 @@ var EventUtils = class {
3154
3944
 
3155
3945
  // controllers/entity/create-entity.controller.ts
3156
3946
  import { createMiddleware as createMiddleware3 } from "hono/factory";
3157
- import httpStatus4 from "http-status";
3947
+ import httpStatus5 from "http-status";
3158
3948
  var CreateEntityController = class {
3159
3949
  constructor(entityService) {
3160
3950
  this.entityService = entityService;
@@ -3173,11 +3963,11 @@ var CreateEntityController = class {
3173
3963
  createAndUpdateDatetime: body.createdAt
3174
3964
  }
3175
3965
  });
3176
- c.status(httpStatus4.OK);
3966
+ c.status(httpStatus5.OK);
3177
3967
  return c.json(entity);
3178
3968
  } catch (err) {
3179
3969
  if (((_a = err.constructor) == null ? void 0 : _a.name) === "ZodError") {
3180
- c.status(httpStatus4.BAD_REQUEST);
3970
+ c.status(httpStatus5.BAD_REQUEST);
3181
3971
  return c.json({
3182
3972
  code: "API_VALIDATION_ERROR",
3183
3973
  message: "API validation failed",
@@ -3185,11 +3975,11 @@ var CreateEntityController = class {
3185
3975
  });
3186
3976
  }
3187
3977
  if (err instanceof StandardError && err.code === StandardErrorCode.EMAIL_EXISTS) {
3188
- c.status(httpStatus4.BAD_REQUEST);
3978
+ c.status(httpStatus5.BAD_REQUEST);
3189
3979
  return c.json(__spreadValues({}, err.toJSON()));
3190
3980
  }
3191
3981
  if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
3192
- c.status(httpStatus4.BAD_REQUEST);
3982
+ c.status(httpStatus5.BAD_REQUEST);
3193
3983
  return c.json(__spreadValues({}, err.toJSON()));
3194
3984
  }
3195
3985
  console.log("===create-entity error:", {
@@ -3207,7 +3997,7 @@ var CreateEntityController = class {
3207
3997
 
3208
3998
  // controllers/entity/delete-entity.controller.ts
3209
3999
  import { createMiddleware as createMiddleware4 } from "hono/factory";
3210
- import httpStatus5 from "http-status";
4000
+ import httpStatus6 from "http-status";
3211
4001
  var DeleteEntityController = class {
3212
4002
  constructor(entityService) {
3213
4003
  this.entityService = entityService;
@@ -3223,7 +4013,7 @@ var DeleteEntityController = class {
3223
4013
  return c.json({ message: "entity deleted" });
3224
4014
  } catch (err) {
3225
4015
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_NOT_FOUND) {
3226
- c.status(httpStatus5.NOT_FOUND);
4016
+ c.status(httpStatus6.NOT_FOUND);
3227
4017
  return c.json(__spreadValues({}, err.toJSON()));
3228
4018
  }
3229
4019
  throw err;
@@ -3234,7 +4024,7 @@ var DeleteEntityController = class {
3234
4024
 
3235
4025
  // controllers/entity/get-entity-by-unique-field-value.controller.ts
3236
4026
  import { createMiddleware as createMiddleware5 } from "hono/factory";
3237
- import httpStatus6 from "http-status";
4027
+ import httpStatus7 from "http-status";
3238
4028
  var GetEntityByUniqueFieldValueController = class {
3239
4029
  constructor(entityRepository) {
3240
4030
  this.entityRepository = entityRepository;
@@ -3249,7 +4039,7 @@ var GetEntityByUniqueFieldValueController = class {
3249
4039
  return c.json(entity);
3250
4040
  } catch (err) {
3251
4041
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
3252
- c.status(httpStatus6.NOT_FOUND);
4042
+ c.status(httpStatus7.NOT_FOUND);
3253
4043
  return c.json({
3254
4044
  code: "ENTITY_NOT_FOUND",
3255
4045
  message: "Entity not found"
@@ -3263,7 +4053,7 @@ var GetEntityByUniqueFieldValueController = class {
3263
4053
 
3264
4054
  // controllers/entity/get-entity.controller.ts
3265
4055
  import { createMiddleware as createMiddleware6 } from "hono/factory";
3266
- import httpStatus7 from "http-status";
4056
+ import httpStatus8 from "http-status";
3267
4057
  var GetEntityController = class {
3268
4058
  constructor(entityRepository) {
3269
4059
  this.entityRepository = entityRepository;
@@ -3274,11 +4064,11 @@ var GetEntityController = class {
3274
4064
  entityType,
3275
4065
  entityId
3276
4066
  );
3277
- c.status(httpStatus7.OK);
4067
+ c.status(httpStatus8.OK);
3278
4068
  return c.json(entity);
3279
4069
  } catch (err) {
3280
4070
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
3281
- c.status(httpStatus7.NOT_FOUND);
4071
+ c.status(httpStatus8.NOT_FOUND);
3282
4072
  return c.json({
3283
4073
  code: "ENTITY_NOT_FOUND",
3284
4074
  message: "Entity not found"
@@ -7258,12 +8048,12 @@ var ListEntitiesController = class {
7258
8048
  throw new Error("multiple account-id detected");
7259
8049
  }
7260
8050
  const params = c.req.param();
7261
- const queries = c.req.query();
8051
+ const queries2 = c.req.query();
7262
8052
  errorContext.accountId = accountId;
7263
8053
  errorContext.params = params;
7264
- errorContext.query = queries;
8054
+ errorContext.query = queries2;
7265
8055
  const { entityType } = params;
7266
- const { lastKey, query, limit, start, end } = querySchema.parse(queries);
8056
+ const { lastKey, query, limit, start, end } = querySchema.parse(queries2);
7267
8057
  if (query) {
7268
8058
  const results2 = yield this.entityRepository.queryEntities(
7269
8059
  entityType,
@@ -7299,7 +8089,7 @@ var ListEntitiesController = class {
7299
8089
 
7300
8090
  // controllers/entity/update-entity.controller.ts
7301
8091
  import { createMiddleware as createMiddleware8 } from "hono/factory";
7302
- import httpStatus8 from "http-status";
8092
+ import httpStatus9 from "http-status";
7303
8093
  var UpdateEntityController = class {
7304
8094
  constructor(entityService) {
7305
8095
  this.entityService = entityService;
@@ -7311,7 +8101,7 @@ var UpdateEntityController = class {
7311
8101
  const _a = body, { $condition: condition, $where: where } = _a, entityPayload = __objRest(_a, ["$condition", "$where"]);
7312
8102
  if (condition !== void 0) {
7313
8103
  if (typeof condition !== "string" || condition.trim().length === 0) {
7314
- c.status(httpStatus8.BAD_REQUEST);
8104
+ c.status(httpStatus9.BAD_REQUEST);
7315
8105
  return c.json({
7316
8106
  code: "API_VALIDATION_ERROR",
7317
8107
  message: "$condition must be a non-empty string"
@@ -7333,11 +8123,11 @@ var UpdateEntityController = class {
7333
8123
  where
7334
8124
  });
7335
8125
  errorContext.entity = entity;
7336
- c.status(httpStatus8.OK);
8126
+ c.status(httpStatus9.OK);
7337
8127
  return c.json(entity);
7338
8128
  } catch (err) {
7339
8129
  if (((_b = err.constructor) == null ? void 0 : _b.name) === "ZodError") {
7340
- c.status(httpStatus8.BAD_REQUEST);
8130
+ c.status(httpStatus9.BAD_REQUEST);
7341
8131
  return c.json({
7342
8132
  code: "API_VALIDATION_ERROR",
7343
8133
  message: "API validation failed",
@@ -7345,19 +8135,19 @@ var UpdateEntityController = class {
7345
8135
  });
7346
8136
  }
7347
8137
  if (err instanceof StandardError && (err.code === StandardErrorCode.ENTITY_NOT_FOUND || err.code === StandardErrorCode.ENTITY_IS_UNDEFINED)) {
7348
- c.status(httpStatus8.NOT_FOUND);
8138
+ c.status(httpStatus9.NOT_FOUND);
7349
8139
  return c.json(__spreadValues({}, err.toJSON()));
7350
8140
  }
7351
8141
  if (err instanceof StandardError && err.code === StandardErrorCode.INVALID_CONDITION) {
7352
- c.status(httpStatus8.BAD_REQUEST);
8142
+ c.status(httpStatus9.BAD_REQUEST);
7353
8143
  return c.json(__spreadValues({}, err.toJSON()));
7354
8144
  }
7355
8145
  if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
7356
- c.status(httpStatus8.BAD_REQUEST);
8146
+ c.status(httpStatus9.BAD_REQUEST);
7357
8147
  return c.json(__spreadValues({}, err.toJSON()));
7358
8148
  }
7359
8149
  if (err instanceof StandardError && err.code === StandardErrorCode.CONDITIONAL_CHECK_FAILED) {
7360
- c.status(httpStatus8.CONFLICT);
8150
+ c.status(httpStatus9.CONFLICT);
7361
8151
  return c.json(__spreadValues({}, err.toJSON()));
7362
8152
  }
7363
8153
  console.log(
@@ -7373,7 +8163,7 @@ var UpdateEntityController = class {
7373
8163
 
7374
8164
  // controllers/entity/adjust-entity.controller.ts
7375
8165
  import { createMiddleware as createMiddleware9 } from "hono/factory";
7376
- import httpStatus9 from "http-status";
8166
+ import httpStatus10 from "http-status";
7377
8167
  var AdjustEntityController = class {
7378
8168
  constructor(entityService) {
7379
8169
  this.entityService = entityService;
@@ -7385,7 +8175,7 @@ var AdjustEntityController = class {
7385
8175
  const _a = body, { $condition: condition } = _a, adjustments = __objRest(_a, ["$condition"]);
7386
8176
  if (condition !== void 0) {
7387
8177
  if (typeof condition !== "string" || condition.trim().length === 0) {
7388
- c.status(httpStatus9.BAD_REQUEST);
8178
+ c.status(httpStatus10.BAD_REQUEST);
7389
8179
  return c.json({
7390
8180
  code: "API_VALIDATION_ERROR",
7391
8181
  message: "$condition must be a non-empty string"
@@ -7394,7 +8184,7 @@ var AdjustEntityController = class {
7394
8184
  }
7395
8185
  for (const [key, value] of Object.entries(adjustments)) {
7396
8186
  if (typeof value !== "number") {
7397
- c.status(httpStatus9.BAD_REQUEST);
8187
+ c.status(httpStatus10.BAD_REQUEST);
7398
8188
  return c.json({
7399
8189
  code: "API_VALIDATION_ERROR",
7400
8190
  message: `Field "${key}" must be a number, got ${typeof value}`
@@ -7409,19 +8199,19 @@ var AdjustEntityController = class {
7409
8199
  accountId,
7410
8200
  condition
7411
8201
  });
7412
- c.status(httpStatus9.OK);
8202
+ c.status(httpStatus10.OK);
7413
8203
  return c.json(entity.toJSON());
7414
8204
  } catch (err) {
7415
8205
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
7416
- c.status(httpStatus9.NOT_FOUND);
8206
+ c.status(httpStatus10.NOT_FOUND);
7417
8207
  return c.json(__spreadValues({}, err.toJSON()));
7418
8208
  }
7419
8209
  if (err instanceof StandardError && err.code === StandardErrorCode.INVALID_CONDITION) {
7420
- c.status(httpStatus9.BAD_REQUEST);
8210
+ c.status(httpStatus10.BAD_REQUEST);
7421
8211
  return c.json(__spreadValues({}, err.toJSON()));
7422
8212
  }
7423
8213
  if ((err == null ? void 0 : err.name) === "ConditionalCheckFailedException" || ((_b = err == null ? void 0 : err.__type) == null ? void 0 : _b.includes("ConditionalCheckFailed"))) {
7424
- c.status(httpStatus9.CONFLICT);
8214
+ c.status(httpStatus10.CONFLICT);
7425
8215
  return c.json({
7426
8216
  code: "ADJUSTMENT_CONSTRAINT_VIOLATED",
7427
8217
  message: "Adjustment would violate entity constraints"
@@ -7436,7 +8226,7 @@ var AdjustEntityController = class {
7436
8226
 
7437
8227
  // controllers/entity/upsert-entity.controller.ts
7438
8228
  import { createMiddleware as createMiddleware10 } from "hono/factory";
7439
- import httpStatus10 from "http-status";
8229
+ import httpStatus11 from "http-status";
7440
8230
  var UpsertEntityController = class {
7441
8231
  constructor(EntityConfig, entityRepository, publishEvent2) {
7442
8232
  this.EntityConfig = EntityConfig;
@@ -7498,7 +8288,7 @@ var UpsertEntityController = class {
7498
8288
  return c.json(entity);
7499
8289
  } catch (err) {
7500
8290
  if (err instanceof ZodError) {
7501
- c.status(httpStatus10.BAD_REQUEST);
8291
+ c.status(httpStatus11.BAD_REQUEST);
7502
8292
  return c.json({
7503
8293
  code: "API_VALIDATION_ERROR",
7504
8294
  message: "API validation failed",
@@ -7506,7 +8296,7 @@ var UpsertEntityController = class {
7506
8296
  });
7507
8297
  }
7508
8298
  if (err instanceof StandardError && err.code === StandardErrorCode.EMAIL_EXISTS) {
7509
- c.status(httpStatus10.BAD_REQUEST);
8299
+ c.status(httpStatus11.BAD_REQUEST);
7510
8300
  return c.json(__spreadValues({}, err.toJSON()));
7511
8301
  }
7512
8302
  throw err;
@@ -7517,7 +8307,7 @@ var UpsertEntityController = class {
7517
8307
 
7518
8308
  // controllers/mutual/create-mutual.controller.ts
7519
8309
  import { createMiddleware as createMiddleware11 } from "hono/factory";
7520
- import httpStatus11 from "http-status";
8310
+ import httpStatus12 from "http-status";
7521
8311
  var CreateMutualController = class {
7522
8312
  constructor(mutualService) {
7523
8313
  this.mutualService = mutualService;
@@ -7541,7 +8331,7 @@ var CreateMutualController = class {
7541
8331
  return c.json(mutual);
7542
8332
  } catch (err) {
7543
8333
  if (err instanceof ZodError) {
7544
- c.status(httpStatus11.BAD_REQUEST);
8334
+ c.status(httpStatus12.BAD_REQUEST);
7545
8335
  return c.json({
7546
8336
  code: "API_VALIDATION_ERROR",
7547
8337
  message: "API validation failed",
@@ -7549,11 +8339,11 @@ var CreateMutualController = class {
7549
8339
  });
7550
8340
  }
7551
8341
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_EXISTS) {
7552
- c.status(httpStatus11.BAD_REQUEST);
8342
+ c.status(httpStatus12.BAD_REQUEST);
7553
8343
  return c.json(__spreadValues({}, err.toJSON()));
7554
8344
  }
7555
8345
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
7556
- c.status(httpStatus11.BAD_REQUEST);
8346
+ c.status(httpStatus12.BAD_REQUEST);
7557
8347
  return c.json(__spreadValues({}, err.toJSON()));
7558
8348
  }
7559
8349
  throw err;
@@ -7564,7 +8354,7 @@ var CreateMutualController = class {
7564
8354
 
7565
8355
  // controllers/mutual/delete-mutual.controller.ts
7566
8356
  import { createMiddleware as createMiddleware12 } from "hono/factory";
7567
- import httpStatus12 from "http-status";
8357
+ import httpStatus13 from "http-status";
7568
8358
  var DeleteMutualController = class {
7569
8359
  constructor(mutualService) {
7570
8360
  this.mutualService = mutualService;
@@ -7582,7 +8372,7 @@ var DeleteMutualController = class {
7582
8372
  return c.json(mutual);
7583
8373
  } catch (err) {
7584
8374
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_NOT_FOUND) {
7585
- c.status(httpStatus12.BAD_REQUEST);
8375
+ c.status(httpStatus13.BAD_REQUEST);
7586
8376
  return c.json(__spreadValues({}, err.toJSON()));
7587
8377
  }
7588
8378
  throw err;
@@ -7593,7 +8383,7 @@ var DeleteMutualController = class {
7593
8383
 
7594
8384
  // controllers/mutual/get-mutual.controller.ts
7595
8385
  import { createMiddleware as createMiddleware13 } from "hono/factory";
7596
- import httpStatus13 from "http-status";
8386
+ import httpStatus14 from "http-status";
7597
8387
  var GetMutualController = class {
7598
8388
  constructor(associateRepository) {
7599
8389
  this.associateRepository = associateRepository;
@@ -7609,7 +8399,7 @@ var GetMutualController = class {
7609
8399
  return c.json(associate);
7610
8400
  } catch (err) {
7611
8401
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_IS_UNDEFINED) {
7612
- c.status(httpStatus13.NOT_FOUND);
8402
+ c.status(httpStatus14.NOT_FOUND);
7613
8403
  return c.json({
7614
8404
  code: "MUTUAL_NOT_FOUND",
7615
8405
  message: "Mutual not found"
@@ -7685,7 +8475,7 @@ var ListEntitiesByEntityController = class {
7685
8475
 
7686
8476
  // controllers/mutual/update-mutual.controller.ts
7687
8477
  import { createMiddleware as createMiddleware15 } from "hono/factory";
7688
- import httpStatus14 from "http-status";
8478
+ import httpStatus15 from "http-status";
7689
8479
  var UpdateMutualController = class {
7690
8480
  constructor(mutualService) {
7691
8481
  this.mutualService = mutualService;
@@ -7708,7 +8498,7 @@ var UpdateMutualController = class {
7708
8498
  return c.json(mutual);
7709
8499
  } catch (err) {
7710
8500
  if (err instanceof ZodError) {
7711
- c.status(httpStatus14.BAD_REQUEST);
8501
+ c.status(httpStatus15.BAD_REQUEST);
7712
8502
  return c.json({
7713
8503
  code: "API_VALIDATION_ERROR",
7714
8504
  message: "API validation failed",
@@ -7716,7 +8506,7 @@ var UpdateMutualController = class {
7716
8506
  });
7717
8507
  }
7718
8508
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_NOT_FOUND) {
7719
- c.status(httpStatus14.BAD_REQUEST);
8509
+ c.status(httpStatus15.BAD_REQUEST);
7720
8510
  return c.json(__spreadValues({}, err.toJSON()));
7721
8511
  }
7722
8512
  throw err;
@@ -7726,10 +8516,10 @@ var UpdateMutualController = class {
7726
8516
  };
7727
8517
 
7728
8518
  // services/entity.service.ts
7729
- import { marshall as marshall6 } from "@aws-sdk/util-dynamodb";
8519
+ import { marshall as marshall7 } from "@aws-sdk/util-dynamodb";
7730
8520
 
7731
8521
  // data/utils/build-condition-expression.ts
7732
- import { marshall as marshall5 } from "@aws-sdk/util-dynamodb";
8522
+ import { marshall as marshall6 } from "@aws-sdk/util-dynamodb";
7733
8523
  function buildConditionExpression(where) {
7734
8524
  const conditions = ["attribute_exists(PK)"];
7735
8525
  const expressionAttributeNames = { "#data": "data" };
@@ -7785,7 +8575,7 @@ function buildConditionExpression(where) {
7785
8575
  return {
7786
8576
  ConditionExpression: conditions.join(" AND "),
7787
8577
  ExpressionAttributeNames: expressionAttributeNames,
7788
- ExpressionAttributeValues: marshall5(expressionAttributeValues)
8578
+ ExpressionAttributeValues: marshall6(expressionAttributeValues)
7789
8579
  };
7790
8580
  }
7791
8581
 
@@ -8118,7 +8908,7 @@ var EntityService = class {
8118
8908
  return {
8119
8909
  ConditionExpression: conditionParts.join(" AND "),
8120
8910
  ExpressionAttributeNames: names,
8121
- ExpressionAttributeValues: marshall6(values)
8911
+ ExpressionAttributeValues: marshall7(values)
8122
8912
  };
8123
8913
  }
8124
8914
  };
@@ -8424,7 +9214,7 @@ var ListTagsController = class {
8424
9214
 
8425
9215
  // controllers/transaction/execute-transaction.controller.ts
8426
9216
  import { createMiddleware as createMiddleware17 } from "hono/factory";
8427
- import httpStatus15 from "http-status";
9217
+ import httpStatus16 from "http-status";
8428
9218
  var ExecuteTransactionController = class {
8429
9219
  constructor(transactionService) {
8430
9220
  this.transactionService = transactionService;
@@ -8435,7 +9225,7 @@ var ExecuteTransactionController = class {
8435
9225
  try {
8436
9226
  const body = yield c.req.json();
8437
9227
  if (!body.operations || !Array.isArray(body.operations)) {
8438
- c.status(httpStatus15.BAD_REQUEST);
9228
+ c.status(httpStatus16.BAD_REQUEST);
8439
9229
  return c.json({
8440
9230
  code: "API_VALIDATION_ERROR",
8441
9231
  message: 'Request body must contain an "operations" array'
@@ -8445,11 +9235,11 @@ var ExecuteTransactionController = class {
8445
9235
  body.operations,
8446
9236
  accountId
8447
9237
  );
8448
- c.status(httpStatus15.OK);
9238
+ c.status(httpStatus16.OK);
8449
9239
  return c.json(result);
8450
9240
  } catch (err) {
8451
9241
  if (((_a = err.constructor) == null ? void 0 : _a.name) === "ZodError") {
8452
- c.status(httpStatus15.BAD_REQUEST);
9242
+ c.status(httpStatus16.BAD_REQUEST);
8453
9243
  return c.json({
8454
9244
  code: "API_VALIDATION_ERROR",
8455
9245
  message: "Validation failed",
@@ -8457,7 +9247,7 @@ var ExecuteTransactionController = class {
8457
9247
  });
8458
9248
  }
8459
9249
  if (err instanceof SyntaxError) {
8460
- c.status(httpStatus15.BAD_REQUEST);
9250
+ c.status(httpStatus16.BAD_REQUEST);
8461
9251
  return c.json({
8462
9252
  code: "API_VALIDATION_ERROR",
8463
9253
  message: "Request body must be valid JSON"
@@ -8466,15 +9256,15 @@ var ExecuteTransactionController = class {
8466
9256
  if (err instanceof StandardError) {
8467
9257
  const code = err.code;
8468
9258
  if (code === StandardErrorCode.ENTITY_IS_UNDEFINED || code === StandardErrorCode.ENTITY_NOT_FOUND) {
8469
- c.status(httpStatus15.NOT_FOUND);
9259
+ c.status(httpStatus16.NOT_FOUND);
8470
9260
  return c.json(__spreadValues({}, err.toJSON()));
8471
9261
  }
8472
9262
  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) {
8473
- c.status(httpStatus15.BAD_REQUEST);
9263
+ c.status(httpStatus16.BAD_REQUEST);
8474
9264
  return c.json(__spreadValues({}, err.toJSON()));
8475
9265
  }
8476
9266
  if (code === StandardErrorCode.TRANSACTION_FAILED || code === StandardErrorCode.CONDITIONAL_CHECK_FAILED || code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
8477
- c.status(httpStatus15.CONFLICT);
9267
+ c.status(httpStatus16.CONFLICT);
8478
9268
  return c.json(__spreadValues({}, err.toJSON()));
8479
9269
  }
8480
9270
  }
@@ -9210,11 +10000,13 @@ var CoreFactory = class {
9210
10000
  const dependencyContainer = new DependencyContainer(this.config);
9211
10001
  this.dependencyContainer = dependencyContainer;
9212
10002
  this.setupCommonRoutes = setupCommonRoutes(dependencyContainer);
9213
- this.mutualProcessor = handler2(dependencyContainer);
9214
- this.replicationProcessor = handler4(dependencyContainer);
10003
+ this.mutualProcessor = handler7(dependencyContainer);
10004
+ this.replicationProcessor = handler9(dependencyContainer);
9215
10005
  this.createEntityProcessor = handler(dependencyContainer);
9216
- this.prejoinProcessor = handler3(dependencyContainer);
9217
- this.tagProcessor = handler5(dependencyContainer);
10006
+ this.analyticsProcessor = handler2(this.config.EntityConfig);
10007
+ this.analyticsBackfillProcessor = handler3(this.config.EntityConfig);
10008
+ this.prejoinProcessor = handler8(dependencyContainer);
10009
+ this.tagProcessor = handler10(dependencyContainer);
9218
10010
  this.appHandler = appHandler(dependencyContainer);
9219
10011
  }
9220
10012
  };
@@ -9232,14 +10024,21 @@ export {
9232
10024
  StandardErrorCode,
9233
10025
  TagRepository,
9234
10026
  TransactionService,
10027
+ handler3 as analyticsBackfillProcessor,
10028
+ handler4 as analyticsMaterializationProcessor,
10029
+ handler5 as analyticsModelProcessor,
10030
+ handler2 as analyticsProcessor,
10031
+ analyticsQueryHandler,
10032
+ handler6 as analyticsViewProcessor,
9235
10033
  appHandler,
9236
10034
  handler as createEntityProcessor,
9237
10035
  index_default as default,
9238
- handler2 as mutualProcessor,
9239
- handler3 as prejoinProcessor,
9240
- handler4 as replicationProcessor,
10036
+ handler7 as mutualProcessor,
10037
+ handler8 as prejoinProcessor,
10038
+ handler9 as replicationProcessor,
9241
10039
  setupCommonRoutes,
9242
- handler5 as tagProcessor,
10040
+ startBackfill as startAnalyticsBackfill,
10041
+ handler10 as tagProcessor,
9243
10042
  transactional
9244
10043
  };
9245
10044
  //# sourceMappingURL=index.js.map