@signaliz/sdk 1.0.67 → 1.0.69

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.
package/dist/index.js CHANGED
@@ -74,8 +74,6 @@ function publicRetryDetails(body) {
74
74
  ...body?.retry_strategy !== void 0 ? { retry_strategy: body.retry_strategy } : {},
75
75
  ...body?.credits_used !== void 0 ? { credits_used: body.credits_used } : {},
76
76
  ...body?.credits_charged !== void 0 ? { credits_charged: body.credits_charged } : {},
77
- ...body?.live_provider_called !== void 0 ? { live_provider_called: body.live_provider_called } : {},
78
- ...body?.estimated_external_cost_usd !== void 0 ? { estimated_external_cost_usd: body.estimated_external_cost_usd } : {},
79
77
  ...body?.job_id !== void 0 ? { job_id: body.job_id } : {},
80
78
  ...body?.idempotency_key !== void 0 ? { idempotency_key: body.idempotency_key } : {},
81
79
  ...body?.verification_run_id !== void 0 ? { verification_run_id: body.verification_run_id } : {},
@@ -228,10 +226,10 @@ var HttpClient = class {
228
226
  }),
229
227
  signal: controller.signal
230
228
  });
231
- const text = await res.text();
232
- const data = safeJson(text);
229
+ const text2 = await res.text();
230
+ const data = safeJson(text2);
233
231
  if (!res.ok) {
234
- const err = parseError(res.status, data ?? { message: text });
232
+ const err = parseError(res.status, data ?? { message: text2 });
235
233
  if (err.isRetryable && attempt < this.maxRetries) {
236
234
  if (err.details?.retry_strategy === "same_run_recovery") throw err;
237
235
  lastError = err;
@@ -245,7 +243,7 @@ var HttpClient = class {
245
243
  code: "INVALID_JSON",
246
244
  message: "MCP response was not valid JSON",
247
245
  errorType: "provider_error",
248
- details: { responseText: text.slice(0, 500) }
246
+ details: { responseText: text2.slice(0, 500) }
249
247
  });
250
248
  }
251
249
  const responseError = isRecord(data) && isRecord(data.error) ? data.error : null;
@@ -330,9 +328,9 @@ function requestIdempotencyKey(body, automaticIdempotency) {
330
328
  function sleep(ms) {
331
329
  return new Promise((r) => setTimeout(r, ms));
332
330
  }
333
- function safeJson(text) {
331
+ function safeJson(text2) {
334
332
  try {
335
- return JSON.parse(text);
333
+ return JSON.parse(text2);
336
334
  } catch {
337
335
  return null;
338
336
  }
@@ -368,10 +366,10 @@ function unwrapMcpResponse(data) {
368
366
  }
369
367
  const content = isRecord(result) ? result.content : void 0;
370
368
  const firstContent = Array.isArray(content) ? content[0] : void 0;
371
- const text = isRecord(firstContent) ? firstContent.text : void 0;
372
- if (typeof text === "string") {
373
- const parsed = safeJson(text);
374
- return unwrapMcpPayload(parsed ?? text);
369
+ const text2 = isRecord(firstContent) ? firstContent.text : void 0;
370
+ if (typeof text2 === "string") {
371
+ const parsed = safeJson(text2);
372
+ return unwrapMcpPayload(parsed ?? text2);
375
373
  }
376
374
  return unwrapMcpPayload(result);
377
375
  }
@@ -518,8 +516,8 @@ function assertCompanySignalRows(body) {
518
516
  );
519
517
  if (Array.isArray(body.signal_types)) {
520
518
  body.signal_types.forEach(
521
- (signalType, index) => assertStringBytes(
522
- signalType,
519
+ (signalType2, index) => assertStringBytes(
520
+ signalType2,
523
521
  `signal_types[${index}]`,
524
522
  SIGNAL_TYPE_MAX_UTF8_BYTES,
525
523
  index
@@ -529,9 +527,11 @@ function assertCompanySignalRows(body) {
529
527
  requests.forEach((value, index) => {
530
528
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
531
529
  const request = value;
530
+ const domain = request.domain ?? request.company_domain;
531
+ const domainField = request.domain !== void 0 ? "domain" : "company_domain";
532
532
  assertStringBytes(
533
- request.company_domain,
534
- `requests[${index}].company_domain`,
533
+ domain,
534
+ `requests[${index}].${domainField}`,
535
535
  DOMAIN_MAX_UTF8_BYTES,
536
536
  index
537
537
  );
@@ -611,6 +611,190 @@ function assertLargeCoreProductInputBounds(path, body) {
611
611
  );
612
612
  }
613
613
 
614
+ // src/public-signal-row.ts
615
+ var PUBLIC_COMPANY_SIGNAL_MAX_COVERAGE_COUNT = 10;
616
+ function recordValue(value) {
617
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
618
+ }
619
+ function text(value) {
620
+ return typeof value === "string" ? value.trim() : "";
621
+ }
622
+ function dateOnly(value) {
623
+ const raw = text(value);
624
+ const match = raw.match(/^\d{4}-\d{2}-\d{2}/);
625
+ if (!match) return "";
626
+ const parsed = /* @__PURE__ */ new Date(`${match[0]}T00:00:00.000Z`);
627
+ return Number.isFinite(parsed.getTime()) && parsed.toISOString().slice(0, 10) === match[0] ? match[0] : "";
628
+ }
629
+ function classificationSlug(value) {
630
+ const direct = text(value);
631
+ if (direct) return direct;
632
+ const classification = recordValue(value);
633
+ return text(classification.slug || classification.type || classification.name);
634
+ }
635
+ function signalType(signal) {
636
+ const raw = recordValue(signal.raw_data);
637
+ const generic = /* @__PURE__ */ new Set(["unclassified", "unknown", "other", "news", "signal"]);
638
+ for (const value of [
639
+ signal.signal_type,
640
+ classificationSlug(signal.signal_classification),
641
+ classificationSlug(signal.classification),
642
+ raw.signal_type,
643
+ classificationSlug(raw.signal_classification),
644
+ classificationSlug(raw.classification),
645
+ signal.type,
646
+ signal.category,
647
+ signal.event_type,
648
+ raw.type,
649
+ raw.category,
650
+ raw.event_type
651
+ ]) {
652
+ const candidate = text(value);
653
+ if (candidate && !generic.has(candidate.toLowerCase())) return candidate;
654
+ }
655
+ return "";
656
+ }
657
+ function verifiedHttpsUrl(value) {
658
+ const candidate = text(value);
659
+ if (!candidate || /\s/.test(candidate)) return "";
660
+ try {
661
+ const parsed = new URL(candidate);
662
+ return parsed.protocol === "https:" && Boolean(parsed.hostname) && !parsed.username && !parsed.password ? candidate : "";
663
+ } catch {
664
+ return "";
665
+ }
666
+ }
667
+ function normalizedDomain(value) {
668
+ const normalized = text(value).toLowerCase().replace(/^https?:\/\//, "").replace(/^www\./, "").split(/[/?#]/)[0].replace(/\.$/, "");
669
+ return /^(?=.{3,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(normalized) ? normalized : "";
670
+ }
671
+ function firstValid(values, normalize) {
672
+ for (const value of values) {
673
+ const normalized = normalize(value);
674
+ if (normalized) return normalized;
675
+ }
676
+ return "";
677
+ }
678
+ function publicSignalRow(value, fallbackCompany) {
679
+ const signal = recordValue(value);
680
+ const raw = recordValue(signal.raw_data);
681
+ const company = recordValue(signal.company);
682
+ const rawCompany = recordValue(raw.company);
683
+ const fallback = recordValue(fallbackCompany);
684
+ const row = {
685
+ signal_type: signalType(signal),
686
+ signal_title: firstValid([
687
+ signal.signal_title,
688
+ raw.signal_title,
689
+ signal.title,
690
+ raw.title,
691
+ signal.headline,
692
+ raw.headline,
693
+ signal.name,
694
+ raw.name
695
+ ], text),
696
+ signal_summary: firstValid([
697
+ signal.signal_summary,
698
+ raw.signal_summary,
699
+ signal.summary,
700
+ raw.summary,
701
+ signal.signal_content,
702
+ raw.signal_content,
703
+ signal.content,
704
+ raw.content,
705
+ signal.description,
706
+ raw.description
707
+ ], text),
708
+ source: firstValid([
709
+ signal.canonical_source_url,
710
+ signal.source_url,
711
+ signal.verified_source_url,
712
+ signal.signal_source,
713
+ signal.source,
714
+ signal.url,
715
+ raw.canonical_source_url,
716
+ raw.source_url,
717
+ raw.verified_source_url,
718
+ raw.signal_source,
719
+ raw.source,
720
+ raw.url
721
+ ], verifiedHttpsUrl),
722
+ date: firstValid([
723
+ signal.date,
724
+ signal.event_date,
725
+ signal.signal_date,
726
+ signal.published_date,
727
+ signal.published_at,
728
+ signal.detected_at,
729
+ signal.observed_at,
730
+ raw.date,
731
+ raw.event_date,
732
+ raw.signal_date,
733
+ raw.published_date,
734
+ raw.published_at,
735
+ raw.detected_at,
736
+ raw.observed_at
737
+ ], dateOnly),
738
+ company_name: text(
739
+ signal.company_name || company.name || company.company_name || raw.company_name || rawCompany.name || rawCompany.company_name || fallback.company_name || fallback.name
740
+ ),
741
+ domain: firstValid([
742
+ signal.company_domain,
743
+ signal.domain,
744
+ company.domain,
745
+ company.company_domain,
746
+ raw.company_domain,
747
+ raw.domain,
748
+ rawCompany.domain,
749
+ rawCompany.company_domain,
750
+ fallback.company_domain,
751
+ fallback.domain
752
+ ], normalizedDomain)
753
+ };
754
+ return row.signal_type && row.source && row.date && row.company_name && row.domain ? row : null;
755
+ }
756
+ function publicSignalRows(value, fallbackCompany) {
757
+ if (!Array.isArray(value)) return [];
758
+ return value.flatMap((item) => {
759
+ const row = publicSignalRow(item, fallbackCompany);
760
+ return row ? [row] : [];
761
+ });
762
+ }
763
+ function companySignalEventIdentities(value, row) {
764
+ const signal = recordValue(value);
765
+ const raw = recordValue(signal.raw_data);
766
+ const eventId = text(
767
+ signal.event_id || signal.eventId || signal.fact_id || signal.factId || raw.event_id || raw.eventId || raw.fact_id || raw.factId
768
+ ).toLowerCase();
769
+ return [
770
+ ...eventId ? [`event:${eventId}`] : [],
771
+ `source:${row.source.toLowerCase()}`
772
+ ];
773
+ }
774
+ function publicCompanySignalRows(value, fallbackCompany) {
775
+ if (!Array.isArray(value)) return [];
776
+ const seenEvents = /* @__PURE__ */ new Set();
777
+ const rows = [];
778
+ for (const item of value) {
779
+ const row = publicSignalRow(item, fallbackCompany);
780
+ if (!row) continue;
781
+ const identities = companySignalEventIdentities(item, row);
782
+ if (identities.some((identity) => seenEvents.has(identity))) continue;
783
+ identities.forEach((identity) => seenEvents.add(identity));
784
+ rows.push(row);
785
+ if (rows.length >= PUBLIC_COMPANY_SIGNAL_MAX_COVERAGE_COUNT) break;
786
+ }
787
+ return rows;
788
+ }
789
+ function oneSignalPerCompany(rows) {
790
+ const seen = /* @__PURE__ */ new Set();
791
+ return rows.filter((row) => {
792
+ if (seen.has(row.domain)) return false;
793
+ seen.add(row.domain);
794
+ return true;
795
+ });
796
+ }
797
+
614
798
  // ../../supabase/functions/_shared/find-email-identity.ts
615
799
  var LINKEDIN_PERSON_PROFILE_URL_PATTERN = "^[hH][tT][tT][pP][sS]://(?:[A-Za-z0-9-]+\\.)*[lL][iI][nN][kK][eE][dD][iI][nN]\\.[cC][oO][mM]/[iI][nN]/[^/?#]+/?(?:[?#].*)?$";
616
800
  var LINKEDIN_PERSON_PROFILE_URL_REGEX = new RegExp(LINKEDIN_PERSON_PROFILE_URL_PATTERN);
@@ -642,6 +826,27 @@ var Signaliz = class {
642
826
  constructor(config) {
643
827
  this.client = new HttpClient(config);
644
828
  }
829
+ /**
830
+ * The canonical Signal Awareness control plane used by the CLI and MCP.
831
+ * Manual runs accept a stable retry key and return an explicit billing
832
+ * receipt, including zero-credit available-data reuse.
833
+ */
834
+ async signalAwareness(request) {
835
+ const data = await this.client.post(
836
+ "api/v1/signal-awareness",
837
+ signalAwarenessRequestBody(request)
838
+ );
839
+ return normalizeSignalAwarenessResponse(data);
840
+ }
841
+ async createSignalMonitor(monitor) {
842
+ return this.signalAwareness({ action: "create", monitor });
843
+ }
844
+ async listSignalMonitors(limit, offset) {
845
+ return this.signalAwareness({ action: "list", limit, offset });
846
+ }
847
+ async runSignalMonitor(monitorId, idempotencyKey) {
848
+ return this.signalAwareness({ action: "manual_run", monitorId, idempotencyKey });
849
+ }
645
850
  async findEmail(params) {
646
851
  const request = findEmailRequestBody(params);
647
852
  assertFindEmailRequestIdentity(request);
@@ -711,14 +916,12 @@ var Signaliz = class {
711
916
  error,
712
917
  error_code: "INPUT_001",
713
918
  retry_eligible: false,
714
- credits_used: 0,
715
- live_provider_called: false
919
+ credits_used: 0
716
920
  });
717
921
  }
718
922
  const request = compact({
719
923
  email: email || void 0,
720
924
  verification_run_id: options?.verificationRunId,
721
- skip_cache: options?.skipCache,
722
925
  dry_run: options?.dryRun,
723
926
  idempotency_key: options?.idempotencyKey
724
927
  });
@@ -803,19 +1006,38 @@ var Signaliz = class {
803
1006
  );
804
1007
  return normalizeSignalDiscoveryResult(params, data);
805
1008
  }
1009
+ /** Signals First is the customer-facing name for open-ended discovery. */
1010
+ async discoverSignalsFirst(params) {
1011
+ return this.discoverSignals(params);
1012
+ }
1013
+ async startFlow(params) {
1014
+ validateSignalizFlowParams(params);
1015
+ const data = await this.client.post(
1016
+ "api/v1/flow",
1017
+ signalizFlowRequestBody(params)
1018
+ );
1019
+ return data.dry_run === true ? normalizeSignalizFlowPlanResult(data) : normalizeSignalizFlowStartResult(data);
1020
+ }
1021
+ async getFlow(runId) {
1022
+ const normalizedRunId = runId.trim();
1023
+ if (!normalizedRunId || normalizedRunId.length > 200) {
1024
+ throw new RangeError("runId must contain between 1 and 200 characters");
1025
+ }
1026
+ const data = await this.client.post(
1027
+ "api/v1/flow",
1028
+ { run_id: normalizedRunId },
1029
+ { automaticIdempotency: false }
1030
+ );
1031
+ return normalizeSignalizFlowStatus(data);
1032
+ }
806
1033
  async enrichCompanies(companies, options) {
807
1034
  validateBatchSize(companies);
808
1035
  companies.forEach(validateCompanySignalParams);
809
1036
  const requests = companies.map(companySignalRequestBody);
810
- if (companies.length > 25 && requests.some((request) => request.include_candidate_evidence === true)) {
811
- throw new RangeError(
812
- "includeCandidateEvidence is not supported in Company Signals batches larger than 25 because rejected evidence diagnostics are intentionally excluded from durable scale storage; split diagnostic requests into batches of at most 25."
813
- );
814
- }
815
1037
  const largeBatch = companySignalLargeBatchSubmission(requests);
816
1038
  if (companies.length > 25 && !largeBatch) {
817
1039
  throw new RangeError(
818
- "Company Signals batches larger than 25 require homogeneous new-enrichment rows with company identity only and uniform controls; split recovery or mixed-control rows into batches of at most 25."
1040
+ "Company Signals batches larger than 25 require homogeneous new-enrichment rows with a domain only; split recovery or mixed-context rows into batches of at most 25."
819
1041
  );
820
1042
  }
821
1043
  if (options?.dryRun === true) {
@@ -866,14 +1088,14 @@ var Signaliz = class {
866
1088
  if (total !== companies.length) {
867
1089
  throw new Error(`Company Signals batch returned ${total} results for ${companies.length} requests`);
868
1090
  }
869
- const batch = finalizeCoreBatch(
1091
+ const batch2 = finalizeCoreBatch(
870
1092
  companies.length,
871
1093
  startedAt,
872
1094
  recoverableRowsToRound(rows, "Company Signals"),
873
1095
  (item) => normalizeCompanySignalResult(companies[item.index], item.raw)
874
1096
  );
875
1097
  return compactKnownDuplicateBatch(
876
- batch,
1098
+ batch2,
877
1099
  dedupeExactBatchItems(
878
1100
  requests,
879
1101
  (request) => coreProductBatchRequestKey("api/v1/company-signals", request)
@@ -894,15 +1116,21 @@ var Signaliz = class {
894
1116
  return batchItemFailure(item.index, error instanceof Error ? error.message : String(error), item.raw);
895
1117
  }
896
1118
  });
897
- const compactedResults = compactExactDuplicateResults(results, options?.compactDuplicates === true);
898
- const succeeded = compactedResults.filter((item) => item.success).length;
899
- return {
1119
+ const batch = {
900
1120
  total: companies.length,
901
- succeeded,
902
- failed: companies.length - succeeded,
1121
+ succeeded: results.filter((item) => item.success).length,
1122
+ failed: companies.length - results.filter((item) => item.success).length,
903
1123
  durationMs: Date.now() - startedAt,
904
- results: compactedResults
1124
+ results
905
1125
  };
1126
+ return compactKnownDuplicateBatch(
1127
+ batch,
1128
+ dedupeExactBatchItems(
1129
+ requests,
1130
+ (request) => coreProductBatchRequestKey("api/v1/company-signals", request)
1131
+ ).sourceIndexByInput,
1132
+ options?.compactDuplicates === true
1133
+ );
906
1134
  }
907
1135
  async resumeCompanySignalBatch(jobId, options) {
908
1136
  const startedAt = Date.now();
@@ -931,7 +1159,7 @@ var Signaliz = class {
931
1159
  async createSignalCopyBatch(requests, options) {
932
1160
  validateBatchSize(requests);
933
1161
  requests.forEach(validateSignalToCopyParams);
934
- validateLargeAvailableDataSignalCopyBatch(requests);
1162
+ validateLargeSignalCopyBatch(requests);
935
1163
  if (options?.dryRun === true) {
936
1164
  return this.runCoreProductDryRun(
937
1165
  "api/v1/signal-to-copy",
@@ -944,7 +1172,7 @@ var Signaliz = class {
944
1172
  if (options?.waitForResult === false) {
945
1173
  return this.submitRecoverableCoreBatchJob(
946
1174
  "api/v1/signal-to-copy",
947
- requests.map(availableDataSignalCopyRequestBody),
1175
+ requests.map(durableSignalCopyRequestBody),
948
1176
  "Signal to Copy",
949
1177
  options.idempotencyKey,
950
1178
  requests.map((_, index) => index)
@@ -952,7 +1180,7 @@ var Signaliz = class {
952
1180
  }
953
1181
  const job = await this.submitRecoverableCoreBatchJob(
954
1182
  "api/v1/signal-to-copy",
955
- requests.map(availableDataSignalCopyRequestBody),
1183
+ requests.map(durableSignalCopyRequestBody),
956
1184
  "Signal to Copy",
957
1185
  options?.idempotencyKey,
958
1186
  requests.map((_, index) => index)
@@ -1490,8 +1718,6 @@ function batchItemFailure(index, error, raw) {
1490
1718
  const retryStrategy = raw?.retry_strategy ?? raw?.retryStrategy;
1491
1719
  const creditsUsed = raw?.credits_used ?? raw?.creditsUsed;
1492
1720
  const creditsCharged = raw?.credits_charged ?? raw?.creditsCharged;
1493
- const liveProviderCalled = raw?.live_provider_called ?? raw?.liveProviderCalled;
1494
- const estimatedExternalCostUsd = raw?.estimated_external_cost_usd ?? raw?.estimatedExternalCostUsd;
1495
1721
  const runId = [raw?.run_id, raw?.runId, raw?.signal_run_id, raw?.signalRunId].find((value) => typeof value === "string" && value.trim());
1496
1722
  const verificationRunId = raw?.verification_run_id ?? raw?.verificationRunId;
1497
1723
  const jobId = raw?.job_id ?? raw?.jobId;
@@ -1506,8 +1732,6 @@ function batchItemFailure(index, error, raw) {
1506
1732
  ...["new_idempotency_key", "same_run_recovery"].includes(String(retryStrategy)) ? { retryStrategy } : {},
1507
1733
  ...creditsUsed === 0 ? { creditsUsed: 0 } : {},
1508
1734
  ...creditsCharged === 0 ? { creditsCharged: 0 } : {},
1509
- ...liveProviderCalled === false ? { liveProviderCalled: false } : {},
1510
- ...estimatedExternalCostUsd === 0 ? { estimatedExternalCostUsd: 0 } : {},
1511
1735
  ...typeof runId === "string" && runId.trim() ? { runId: runId.trim() } : {},
1512
1736
  ...typeof verificationRunId === "string" && verificationRunId.trim() ? { verificationRunId: verificationRunId.trim() } : {},
1513
1737
  ...typeof jobId === "string" && jobId.trim() ? { jobId: jobId.trim() } : {},
@@ -1563,6 +1787,51 @@ function newBatchIdempotencyKey(label) {
1563
1787
  function compact(input) {
1564
1788
  return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0));
1565
1789
  }
1790
+ var INTERNAL_PRODUCT_RESULT_KEYS = /* @__PURE__ */ new Set([
1791
+ "billing_metadata",
1792
+ "historical_billing_metadata",
1793
+ "result_returned_from",
1794
+ "fresh_enrichment_used",
1795
+ "live_provider_called",
1796
+ "openrouter_called",
1797
+ "byo_openrouter_used",
1798
+ "ai_provider_called",
1799
+ "byo_ai_used",
1800
+ "estimated_external_cost_usd",
1801
+ "included_provider_cost_usd",
1802
+ "would_have_charged_credits",
1803
+ "available_data_only",
1804
+ "available_data_input_count",
1805
+ "unique_available_data_input_count"
1806
+ ]);
1807
+ var PUBLIC_PRODUCT_DATA_MEMO = /* @__PURE__ */ new WeakMap();
1808
+ function publicProductData(value, capability = "") {
1809
+ if (Array.isArray(value)) return value.map((item) => publicProductData(item, capability));
1810
+ if (!value || typeof value !== "object") return value;
1811
+ const source = value;
1812
+ const inferredCapability = String(source.capability || capability).toLowerCase();
1813
+ const cachedByCapability = PUBLIC_PRODUCT_DATA_MEMO.get(source);
1814
+ if (cachedByCapability?.has(inferredCapability)) return cachedByCapability.get(inferredCapability);
1815
+ const result = Object.fromEntries(Object.entries(source).flatMap(([key, raw]) => {
1816
+ const normalizedKey = key.toLowerCase();
1817
+ if (INTERNAL_PRODUCT_RESULT_KEYS.has(normalizedKey) || normalizedKey.includes("cache")) return [];
1818
+ if (typeof raw === "string" && (raw.toLowerCase().includes("cache") || raw === "available_data")) {
1819
+ if (["error", "message", "suggested_action", "failure_reason"].includes(normalizedKey)) {
1820
+ return [[key, "The result could not be finalized. Retry safely using the existing run or job ID."]];
1821
+ }
1822
+ if (["source", "email_source", "email_source_label", "verification_source", "provider_status"].includes(normalizedKey)) {
1823
+ const sourceLabel = inferredCapability.includes("verify") ? "email_verification" : inferredCapability.includes("find") ? "email_finder" : inferredCapability.includes("signal_to_copy") ? "signal_to_copy" : "company_signal_enrichment";
1824
+ return [[key, sourceLabel]];
1825
+ }
1826
+ return [];
1827
+ }
1828
+ return [[key, publicProductData(raw, inferredCapability)]];
1829
+ }));
1830
+ const memo = cachedByCapability || /* @__PURE__ */ new Map();
1831
+ memo.set(inferredCapability, result);
1832
+ if (!cachedByCapability) PUBLIC_PRODUCT_DATA_MEMO.set(source, memo);
1833
+ return result;
1834
+ }
1566
1835
  function findEmailRequestBody(params) {
1567
1836
  return compact({
1568
1837
  run_id: params.runId,
@@ -1572,7 +1841,7 @@ function findEmailRequestBody(params) {
1572
1841
  last_name: params.lastName,
1573
1842
  linkedin_url: params.linkedinUrl,
1574
1843
  company_name: params.companyName,
1575
- skip_cache: params.skipCache,
1844
+ wait_for_result: params.waitForResult,
1576
1845
  dry_run: params.dryRun,
1577
1846
  idempotency_key: params.idempotencyKey
1578
1847
  });
@@ -1587,11 +1856,10 @@ function assertFindEmailRequestIdentity(request) {
1587
1856
  }
1588
1857
  function verifyEmailBatchRequestBody(input, options) {
1589
1858
  if (typeof input === "string") {
1590
- return compact({ email: input, skip_cache: options?.skipCache });
1859
+ return compact({ email: input });
1591
1860
  }
1592
1861
  return compact({
1593
1862
  email: input.email,
1594
- skip_cache: input.skipCache ?? options?.skipCache,
1595
1863
  idempotency_key: input.idempotencyKey
1596
1864
  });
1597
1865
  }
@@ -1623,6 +1891,7 @@ function normalizeCoreProductDryRunResult(data) {
1623
1891
  };
1624
1892
  }
1625
1893
  function normalizeFindEmailResult(data) {
1894
+ data = publicProductData(data, "find_email");
1626
1895
  const processing = String(data.status || "").toLowerCase() === "processing";
1627
1896
  const failed = coreProductResponseFailed(data);
1628
1897
  const rawEmail = typeof data.email === "string" && data.email.trim() ? data.email.trim() : null;
@@ -1639,7 +1908,6 @@ function normalizeFindEmailResult(data) {
1639
1908
  const verificationAgeDays = typeof data.verification_age_days === "number" && Number.isFinite(data.verification_age_days) ? data.verification_age_days : null;
1640
1909
  const providerUsed = data.provider_used ?? data.provider ?? data.email_source ?? data.source ?? "unknown";
1641
1910
  const verificationSource = data.verification_source ?? providerUsed;
1642
- const billingMetadata = data.billing_metadata && typeof data.billing_metadata === "object" && !Array.isArray(data.billing_metadata) ? data.billing_metadata : void 0;
1643
1911
  return {
1644
1912
  success: processing || !failed && found,
1645
1913
  found,
@@ -1662,22 +1930,10 @@ function normalizeFindEmailResult(data) {
1662
1930
  verificationSource,
1663
1931
  verificationObservedAt: typeof data.verification_observed_at === "string" ? data.verification_observed_at : void 0,
1664
1932
  failureReason: data.failure_reason ?? (failed || !found ? "no_verified_email_found" : "none"),
1665
- creditsUsed: data.credits_used ?? billingMetadata?.credits_used,
1666
- creditsCharged: data.credits_charged ?? billingMetadata?.credits_charged,
1667
- estimatedExternalCostUsd: data.estimated_external_cost_usd ?? billingMetadata?.estimated_external_cost_usd,
1668
- billingMetadata,
1933
+ creditsUsed: data.credits_used,
1934
+ creditsCharged: data.credits_charged,
1669
1935
  billingReplayed: data.billing_replayed,
1670
1936
  idempotencyReplayed: data.idempotency_replayed,
1671
- historicalBillingMetadata: data.historical_billing_metadata,
1672
- resultReturnedFrom: data.result_returned_from ?? billingMetadata?.result_returned_from,
1673
- cacheHit: typeof data.cache_hit === "boolean" ? data.cache_hit : billingMetadata?.cache_hit,
1674
- negativeCacheHit: data.negative_cache_hit,
1675
- negativeCacheTtlSeconds: data.negative_cache_ttl_seconds,
1676
- cacheTier: data.cache_tier,
1677
- freshEnrichmentUsed: typeof data.fresh_enrichment_used === "boolean" ? data.fresh_enrichment_used : billingMetadata?.fresh_enrichment_used,
1678
- liveProviderCalled: typeof data.live_provider_called === "boolean" ? data.live_provider_called : billingMetadata?.live_provider_called,
1679
- openrouterCalled: typeof data.openrouter_called === "boolean" ? data.openrouter_called : billingMetadata?.openrouter_called,
1680
- byoOpenrouterUsed: typeof data.byo_openrouter_used === "boolean" ? data.byo_openrouter_used : billingMetadata?.byo_openrouter_used,
1681
1937
  error: processing || found ? void 0 : coreProductErrorMessage(data) ?? "No verified email found",
1682
1938
  errorCode: processing || found ? void 0 : coreProductErrorCode(data) ?? "EMAIL_NOT_FOUND",
1683
1939
  status: processing ? "processing" : "completed",
@@ -1689,18 +1945,17 @@ function normalizeFindEmailResult(data) {
1689
1945
  doNotAutoResubmit: data.do_not_auto_resubmit === true,
1690
1946
  recoveryMode: data.recovery_mode === "same_run" ? "same_run" : void 0,
1691
1947
  recoveryStatus: ["pending", "completed"].includes(String(data.recovery_status)) ? data.recovery_status : void 0,
1692
- cachePublicationStatus: data.cache_publication_status,
1693
- cachePublicationRetryEligible: data.cache_publication_retry_eligible,
1694
1948
  raw: data
1695
1949
  };
1696
1950
  }
1697
1951
  function normalizeVerifyEmailResult(email, data) {
1952
+ data = publicProductData(data, "verify_email");
1698
1953
  const failed = coreProductResponseFailed(data);
1699
1954
  const malformed = data.is_malformed === true || data.verification_verdict === "malformed" || data.verification_status === "malformed" || data.deliverability_status === "malformed";
1700
- const verificationStatus = String(
1955
+ const verificationStatus = normalizeVerifyEmailStatus(
1701
1956
  failed ? malformed ? "malformed" : "error" : data.verification_status ?? data.verification_verdict ?? data.deliverability_status ?? "unknown"
1702
- ).toLowerCase();
1703
- const deliverabilityStatus = String(data.deliverability_status ?? verificationStatus).toLowerCase();
1957
+ );
1958
+ const deliverabilityStatus = normalizeVerifyEmailStatus(data.deliverability_status ?? verificationStatus);
1704
1959
  const verified = !failed && (data.email_verified === true || ["valid", "deliverable"].includes(verificationStatus));
1705
1960
  const isCatchAll = data.email_is_catch_all ?? data.is_catch_all ?? data.catch_all ?? data.diagnostics?.is_catch_all ?? false;
1706
1961
  const verifiedForSending = !failed && data.verified_for_sending === true;
@@ -1721,10 +1976,12 @@ function normalizeVerifyEmailResult(email, data) {
1721
1976
  verifiedForSending,
1722
1977
  verificationStatus,
1723
1978
  deliverabilityStatus,
1724
- verificationVerdict: failed ? malformed ? "malformed" : "error" : data.verification_verdict ?? data.verification_status ?? "unknown",
1979
+ verificationVerdict: normalizeVerifyEmailStatus(
1980
+ failed ? malformed ? "malformed" : "error" : data.verification_verdict ?? verificationStatus
1981
+ ),
1725
1982
  isRoleAccount: data.is_role_account === true || data.email_is_role_account === true || data.role === true,
1726
1983
  quality: typeof data.quality === "string" ? data.quality : null,
1727
- recommendation: typeof data.recommendation === "string" ? data.recommendation : verifiedForSending ? "send" : ["unknown", "verifier_error"].includes(verificationStatus) ? "manual_review" : "do_not_send",
1984
+ recommendation: normalizeVerifyEmailRecommendation(data.recommendation, verificationStatus, verifiedForSending),
1728
1985
  smtpStatus: data.smtp_status ?? (isCatchAll ? "accept_all" : verifiedForSending ? "accepted" : "not_checked"),
1729
1986
  providerStatus: data.provider_status ?? verificationStatus,
1730
1987
  failureReason: data.failure_reason ?? (verifiedForSending ? "none" : isCatchAll ? "catch_all_domain_not_send_safe" : "verification_not_send_safe"),
@@ -1735,53 +1992,47 @@ function normalizeVerifyEmailResult(email, data) {
1735
1992
  billingReplayed: data.billing_replayed,
1736
1993
  idempotencyReplayed: data.idempotency_replayed,
1737
1994
  creditsUsed: data.credits_used,
1738
- billingMetadata: data.billing_metadata,
1739
- historicalBillingMetadata: data.historical_billing_metadata,
1740
- resultReturnedFrom: data.result_returned_from,
1741
- cacheHit: data.cache_hit,
1742
- negativeCacheHit: data.negative_cache_hit,
1743
- negativeCacheTtlSeconds: data.negative_cache_ttl_seconds,
1744
- cacheTier: data.cache_tier,
1745
- freshEnrichmentUsed: data.fresh_enrichment_used,
1746
- liveProviderCalled: data.live_provider_called,
1747
- openrouterCalled: data.openrouter_called,
1748
- byoOpenrouterUsed: data.byo_openrouter_used,
1749
- estimatedExternalCostUsd: data.estimated_external_cost_usd,
1750
1995
  runId: data.run_id ?? verificationRunId,
1751
- cachePublicationStatus: data.cache_publication_status,
1752
- cachePublicationRetryEligible: data.cache_publication_retry_eligible,
1753
1996
  suggestedAction: data.suggested_action,
1754
1997
  raw: data
1755
1998
  };
1756
1999
  }
2000
+ function normalizeVerifyEmailStatus(value) {
2001
+ const status = String(value ?? "").trim().toLowerCase();
2002
+ if (status === "deliverable" || status === "accepted" || status === "verified") return "valid";
2003
+ if (status === "undeliverable" || status === "rejected") return "invalid";
2004
+ if ([
2005
+ "valid",
2006
+ "invalid",
2007
+ "catch_all",
2008
+ "role",
2009
+ "disposable",
2010
+ "unknown",
2011
+ "verifier_error",
2012
+ "malformed",
2013
+ "error"
2014
+ ].includes(status)) return status;
2015
+ return "unknown";
2016
+ }
2017
+ function normalizeVerifyEmailRecommendation(value, verificationStatus, verifiedForSending) {
2018
+ const recommendation = String(value ?? "").trim().toLowerCase();
2019
+ if (recommendation === "send" || recommendation === "do_not_send" || recommendation === "manual_review") {
2020
+ return recommendation;
2021
+ }
2022
+ if (verifiedForSending) return "send";
2023
+ return verificationStatus === "unknown" || verificationStatus === "verifier_error" ? "manual_review" : "do_not_send";
2024
+ }
1757
2025
  function companySignalRequestBody(params) {
1758
- const online = params.online ?? true;
1759
2026
  return compact({
1760
2027
  signal_run_id: params.signalRunId,
1761
- company_domain: params.companyDomain,
1762
- company_name: params.companyName,
1763
- research_prompt: params.researchPrompt,
1764
- signal_types: params.signalTypes,
1765
- target_signal_count: params.targetSignalCount,
1766
- lookback_days: params.lookbackDays,
1767
- online,
1768
- enable_deep_search: params.enableDeepSearch ?? online,
1769
- search_mode: params.searchMode ?? "balanced",
1770
- include_summary: params.includeSummary,
1771
- enable_outreach_intelligence: params.enableOutreachIntelligence,
1772
- enable_predictive_intelligence: params.enablePredictiveIntelligence,
1773
- skip_cache: params.skipCache,
1774
- include_candidate_evidence: params.includeCandidateEvidence,
1775
- wait_for_result: true,
1776
- max_wait_ms: params.maxWaitMs,
2028
+ domain: params.domain ?? params.companyDomain,
1777
2029
  dry_run: params.dryRun,
1778
2030
  idempotency_key: params.idempotencyKey
1779
2031
  });
1780
2032
  }
1781
2033
  function validateCompanySignalParams(params) {
1782
- validateCoreProductMaxWaitMs(params.maxWaitMs);
1783
- if (params.targetSignalCount !== void 0 && (!Number.isInteger(params.targetSignalCount) || params.targetSignalCount < 1 || params.targetSignalCount > 15)) {
1784
- throw new RangeError("targetSignalCount must be an integer between 1 and 15");
2034
+ if (!params.signalRunId && !(params.domain ?? params.companyDomain)?.trim()) {
2035
+ throw new TypeError("Company Signals requires domain");
1785
2036
  }
1786
2037
  if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
1787
2038
  throw new RangeError("lookbackDays must be an integer between 1 and 365");
@@ -1789,25 +2040,11 @@ function validateCompanySignalParams(params) {
1789
2040
  }
1790
2041
  function companySignalParamsFromRecoveredRow(row) {
1791
2042
  return {
1792
- companyDomain: row.company?.domain ?? row.company_domain,
1793
- companyName: row.company?.name ?? row.company_name,
2043
+ domain: row.company?.domain ?? row.company_domain,
1794
2044
  signalRunId: row.signal_run_id ?? row.run_id
1795
2045
  };
1796
2046
  }
1797
- var COMPANY_SIGNAL_LARGE_BATCH_CONTROL_FIELDS = [
1798
- "research_prompt",
1799
- "signal_types",
1800
- "target_signal_count",
1801
- "lookback_days",
1802
- "online",
1803
- "enable_deep_search",
1804
- "search_mode",
1805
- "include_summary",
1806
- "enable_outreach_intelligence",
1807
- "enable_predictive_intelligence",
1808
- "skip_cache",
1809
- "include_candidate_evidence"
1810
- ];
2047
+ var COMPANY_SIGNAL_LARGE_BATCH_CONTROL_FIELDS = [];
1811
2048
  function companySignalLargeBatchSubmission(requests) {
1812
2049
  if (requests.length <= 25) return null;
1813
2050
  if (requests.some(
@@ -1824,67 +2061,158 @@ function companySignalLargeBatchSubmission(requests) {
1824
2061
  COMPANY_SIGNAL_LARGE_BATCH_CONTROL_FIELDS.filter((field) => request[field] !== void 0).map((field) => [field, request[field]])
1825
2062
  );
1826
2063
  if (JSON.stringify(requestControls) !== controlKey) return null;
1827
- const hasIdentity = typeof request.company_domain === "string" && request.company_domain.trim() || typeof request.company_name === "string" && request.company_name.trim();
2064
+ const hasIdentity = typeof request.domain === "string" && request.domain.trim();
1828
2065
  if (!hasIdentity) return null;
1829
2066
  }
1830
2067
  return {
1831
- requests: requests.map((request) => compact({
1832
- company_domain: request.company_domain,
1833
- company_name: request.company_name
1834
- })),
2068
+ requests: requests.map((request) => compact({ domain: request.domain })),
1835
2069
  submissionFields
1836
2070
  };
1837
2071
  }
1838
2072
  function normalizeCompanySignalResult(params, data) {
2073
+ data = publicProductData(data, "company_signals");
1839
2074
  const failed = coreProductResponseFailed(data);
1840
2075
  const rawSignals = failed ? [] : data.signals ?? data.signal_feed ?? [];
2076
+ const fallbackCompany = {
2077
+ name: data.company_name ?? data.company?.name ?? params.domain ?? params.companyDomain ?? null,
2078
+ domain: data.company_domain ?? data.domain ?? data.company?.domain ?? params.domain ?? params.companyDomain ?? null
2079
+ };
2080
+ const signalRows = publicCompanySignalRows(rawSignals, fallbackCompany);
2081
+ const company = {
2082
+ name: fallbackCompany.name ?? signalRows[0]?.company_name ?? null,
2083
+ domain: fallbackCompany.domain ?? signalRows[0]?.domain ?? null
2084
+ };
2085
+ const signals = signalRows.map(companySignalOutputRow);
1841
2086
  return {
1842
2087
  success: !failed,
1843
2088
  error: failed ? coreProductErrorMessage(data) : void 0,
1844
2089
  errorCode: failed ? coreProductErrorCode(data) : void 0,
1845
2090
  status: data.status,
1846
2091
  signalRunId: data.signal_run_id ?? data.run_id ?? params.signalRunId,
1847
- company: {
1848
- name: data.company?.name ?? params.companyName ?? null,
1849
- domain: data.company?.domain ?? params.companyDomain ?? null
1850
- },
1851
- signals: rawSignals.map((signal) => {
1852
- return {
1853
- id: signal.id,
1854
- title: signal.title ?? "",
1855
- type: signal.type ?? signal.signal_type ?? "unknown",
1856
- content: signal.content ?? signal.description ?? "",
1857
- date: signal.date ?? null,
1858
- detectedAt: signal.detected_at ?? null,
1859
- datePrecision: signal.date_precision,
1860
- sourceUrl: signal.source_url ?? signal.url ?? null,
1861
- sourceType: signal.source_type,
1862
- confidence: signal.confidence ?? signal.confidence_score ?? null,
1863
- signalFamily: signal.signal_family,
1864
- eventType: signal.signal_event_type,
1865
- eventLabel: signal.signal_event_label,
1866
- classification: signal.signal_classification ?? null
1867
- };
1868
- }),
1869
- signalCount: failed ? 0 : data.signal_count ?? data.total_signals ?? rawSignals.length,
1870
- signalSummary: failed ? null : data.signal_summary ?? null,
1871
- intelligence: failed ? null : data.intelligence ?? null,
1872
- copyFuel: failed ? null : data.copy_fuel ?? null,
1873
- evidenceValidation: failed ? void 0 : data.evidence_validation,
1874
- evidenceSources: failed ? [] : data.metadata?.evidence_sources ?? data.evidence_sources,
1875
- evidenceCount: failed ? 0 : data.evidence_count,
1876
- evidenceCountTotal: failed ? 0 : data.evidence_count_total,
1877
- evidenceSourcesOmitted: failed ? 0 : data.evidence_sources_omitted,
1878
- evidenceScope: failed ? void 0 : data.evidence_scope,
1879
- billingMetadata: data.billing_metadata,
1880
- resultReturnedFrom: data.result_returned_from,
1881
- cacheHit: data.cache_hit,
1882
- freshEnrichmentUsed: data.fresh_enrichment_used,
1883
- creditsUsed: data.credits_used,
1884
- liveProviderCalled: data.live_provider_called,
1885
- aiProviderCalled: data.ai_provider_called,
1886
- byoAiUsed: data.byo_ai_used,
1887
- raw: data
2092
+ company,
2093
+ signals,
2094
+ signalCount: signals.length,
2095
+ creditsUsed: data.credits_used
2096
+ };
2097
+ }
2098
+ function companySignalOutputRow(row) {
2099
+ return {
2100
+ date: row.date,
2101
+ signal_type: row.signal_type,
2102
+ signal_title: row.signal_title,
2103
+ signal_summary: row.signal_summary,
2104
+ source: row.source
2105
+ };
2106
+ }
2107
+ function validateSignalizFlowParams(params) {
2108
+ const query = typeof params.signalQuery === "string" ? params.signalQuery.trim() : "";
2109
+ const offer = typeof params.campaignOffer === "string" ? params.campaignOffer.trim() : "";
2110
+ if (query.length < 2 || query.length > 2e3) throw new RangeError("signalQuery must contain between 2 and 2000 characters");
2111
+ if (!offer || offer.length > 4e3) throw new RangeError("campaignOffer must contain between 1 and 4000 characters");
2112
+ if (params.signalLimit !== void 0 && (!Number.isInteger(params.signalLimit) || params.signalLimit < 1 || params.signalLimit > 25)) {
2113
+ throw new RangeError("signalLimit must be an integer between 1 and 25");
2114
+ }
2115
+ if (params.peoplePerCompany !== void 0 && (!Number.isInteger(params.peoplePerCompany) || params.peoplePerCompany < 1 || params.peoplePerCompany > 5)) {
2116
+ throw new RangeError("peoplePerCompany must be an integer between 1 and 5");
2117
+ }
2118
+ if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
2119
+ throw new RangeError("lookbackDays must be an integer between 1 and 365");
2120
+ }
2121
+ if (params.peopleTitles !== void 0 && (!Array.isArray(params.peopleTitles) || params.peopleTitles.length > 20 || params.peopleTitles.some((title) => typeof title !== "string" || !title.trim()))) {
2122
+ throw new TypeError("peopleTitles must contain at most 20 non-empty titles");
2123
+ }
2124
+ }
2125
+ function signalizFlowRequestBody(params) {
2126
+ const requestedFlowId = typeof params.flowId === "string" ? params.flowId.trim() : "";
2127
+ const requestedIdempotencyKey = typeof params.idempotencyKey === "string" ? params.idempotencyKey.trim() : "";
2128
+ const flowId = requestedFlowId || requestedIdempotencyKey || `sdk-flow-${globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(16).slice(2)}`}`;
2129
+ const idempotencyKey = requestedIdempotencyKey || `signaliz-flow:${flowId}`;
2130
+ return compact({
2131
+ signal_query: params.signalQuery.trim(),
2132
+ campaign_offer: params.campaignOffer.trim(),
2133
+ signal_limit: params.signalLimit,
2134
+ lookback_days: params.lookbackDays,
2135
+ icp_context: params.icpContext?.trim(),
2136
+ people_titles: params.peopleTitles?.map((title) => title.trim()),
2137
+ people_per_company: params.peoplePerCompany,
2138
+ copy_research_prompt: params.copyResearchPrompt?.trim(),
2139
+ approval_required: params.approvalRequired,
2140
+ flow_id: flowId,
2141
+ idempotency_key: idempotencyKey,
2142
+ dry_run: params.dryRun
2143
+ });
2144
+ }
2145
+ function normalizeSignalizFlowPlan(data) {
2146
+ const plan = data.plan && typeof data.plan === "object" ? data.plan : {};
2147
+ const billing = plan.billing && typeof plan.billing === "object" ? plan.billing : {};
2148
+ return {
2149
+ plannedCompanyCount: Number(plan.planned_company_count ?? 0),
2150
+ plannedPeoplePerCompany: Number(plan.planned_people_per_company ?? 0),
2151
+ maximumReviewCandidates: Number(plan.maximum_review_candidates ?? 0),
2152
+ safeguards: Array.isArray(plan.safeguards) ? plan.safeguards.filter((value) => typeof value === "string") : [],
2153
+ billing: { additionalFlowFeeCredits: Number(billing.additional_flow_fee_credits ?? 0), chargeBasis: String(billing.charge_basis ?? "") }
2154
+ };
2155
+ }
2156
+ function normalizeSignalizFlowPlanResult(data) {
2157
+ if (data.success !== true) throw new Error(String(data.error || "Signaliz Flow plan is unavailable."));
2158
+ return { success: true, dryRun: true, status: "PLANNED", flowId: String(data.flow_id ?? ""), plan: normalizeSignalizFlowPlan(data), creditsCharged: 0 };
2159
+ }
2160
+ function normalizeSignalizFlowStartResult(data) {
2161
+ if (data.success !== true || typeof data.run_id !== "string" || !data.run_id.trim()) {
2162
+ throw new Error(String(data.error || "Signaliz Flow could not be started."));
2163
+ }
2164
+ return { success: true, flowId: String(data.flow_id ?? ""), runId: data.run_id, status: "TRIGGERED", statusEndpoint: "api/v1/flow", message: String(data.message ?? "") };
2165
+ }
2166
+ var FLOW_SIGNAL_LIST_KEYS = /* @__PURE__ */ new Set(["signals", "signal_feed", "company_signals", "signal_results"]);
2167
+ var FLOW_SINGLE_SIGNAL_KEYS = /* @__PURE__ */ new Set(["signal", "source_signal"]);
2168
+ function publicSignalizFlowResult(value) {
2169
+ if (Array.isArray(value)) return value.map(publicSignalizFlowResult);
2170
+ if (!value || typeof value !== "object") return value;
2171
+ const source = value;
2172
+ return Object.fromEntries(Object.entries(source).flatMap(([key, raw]) => {
2173
+ const normalizedKey = key.toLowerCase();
2174
+ if (normalizedKey === "raw" || normalizedKey === "raw_data") return [];
2175
+ if (FLOW_SIGNAL_LIST_KEYS.has(normalizedKey)) {
2176
+ return [[key, oneSignalPerCompany(publicSignalRows(raw))]];
2177
+ }
2178
+ if (FLOW_SINGLE_SIGNAL_KEYS.has(normalizedKey)) {
2179
+ const row = publicSignalRow(raw);
2180
+ return row ? [[key, row]] : [];
2181
+ }
2182
+ return [[key, publicSignalizFlowResult(raw)]];
2183
+ }));
2184
+ }
2185
+ function normalizeSignalizFlowBilling(value) {
2186
+ if (!value || typeof value !== "object") return void 0;
2187
+ const billing = value;
2188
+ return {
2189
+ creditsCharged: Number(billing.credits_charged ?? 0),
2190
+ billingStatus: billing.billing_status === "charged" ? "charged" : "included_or_waived",
2191
+ chargeBasis: String(billing.charge_basis ?? ""),
2192
+ receipt: Array.isArray(billing.receipt) ? billing.receipt.map((line) => ({
2193
+ capability: line.capability,
2194
+ successfulResults: Number(line.successful_results ?? 0),
2195
+ creditsCharged: Number(line.credits_charged ?? 0)
2196
+ })).filter((line) => ["company_signals", "find_email", "signal_to_copy"].includes(line.capability)) : []
2197
+ };
2198
+ }
2199
+ function normalizeSignalizFlowStatus(data) {
2200
+ if (data.success !== true || typeof data.run_id !== "string" || !data.run_id.trim()) {
2201
+ throw new Error(String(data.error || "Signaliz Flow status is unavailable."));
2202
+ }
2203
+ const publicData = publicProductData(data, "signaliz_flow");
2204
+ const result = publicData.result && typeof publicData.result === "object" ? publicSignalizFlowResult(publicData.result) : {};
2205
+ const billing = normalizeSignalizFlowBilling(result.billing);
2206
+ if (billing) result.billing = billing;
2207
+ const status = String(publicData.status || "").toLowerCase();
2208
+ return {
2209
+ success: true,
2210
+ runId: String(publicData.run_id),
2211
+ status: status === "completed" || status === "failed" ? status : "running",
2212
+ result,
2213
+ createdAt: typeof publicData.created_at === "string" ? publicData.created_at : void 0,
2214
+ updatedAt: typeof publicData.updated_at === "string" ? publicData.updated_at : void 0,
2215
+ completedAt: typeof publicData.completed_at === "string" ? publicData.completed_at : void 0
1888
2216
  };
1889
2217
  }
1890
2218
  var SIGNAL_DISCOVERY_SOURCES = /* @__PURE__ */ new Set(["web", "news"]);
@@ -1917,10 +2245,32 @@ function validateSignalDiscoveryParams(params) {
1917
2245
  if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
1918
2246
  throw new RangeError("lookbackDays must be an integer between 1 and 365");
1919
2247
  }
2248
+ validateSignalDateWindow(params);
1920
2249
  if (params.sources !== void 0 && (!Array.isArray(params.sources) || params.sources.length < 1 || params.sources.length > 2 || params.sources.some((source) => !SIGNAL_DISCOVERY_SOURCES.has(source)))) {
1921
2250
  throw new TypeError("sources must contain only web or news");
1922
2251
  }
1923
2252
  }
2253
+ function validateSignalDateWindow(params) {
2254
+ const afterDate = params.afterDate?.trim();
2255
+ const beforeDate = params.beforeDate?.trim();
2256
+ if ((afterDate || beforeDate) && params.lookbackDays !== void 0) {
2257
+ throw new RangeError("afterDate/beforeDate cannot be combined with lookbackDays");
2258
+ }
2259
+ const parseDate = (value, field) => {
2260
+ if (value === void 0) return void 0;
2261
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) throw new RangeError(`${field} must use YYYY-MM-DD format`);
2262
+ const timestamp = Date.parse(`${value}T00:00:00Z`);
2263
+ if (!Number.isFinite(timestamp) || new Date(timestamp).toISOString().slice(0, 10) !== value) {
2264
+ throw new RangeError(`${field} must be a valid calendar date`);
2265
+ }
2266
+ return timestamp;
2267
+ };
2268
+ const afterTimestamp = parseDate(afterDate, "afterDate");
2269
+ const beforeTimestamp = parseDate(beforeDate, "beforeDate");
2270
+ if (afterTimestamp !== void 0 && beforeTimestamp !== void 0 && beforeTimestamp < afterTimestamp) {
2271
+ throw new RangeError("beforeDate must be on or after afterDate");
2272
+ }
2273
+ }
1924
2274
  function signalDiscoveryRequestBody(params) {
1925
2275
  const runId = typeof params.signalSearchRunId === "string" ? params.signalSearchRunId.trim() : "";
1926
2276
  if (runId) {
@@ -1929,6 +2279,8 @@ function signalDiscoveryRequestBody(params) {
1929
2279
  // An explicit limit expands or narrows the retained qualified cohort;
1930
2280
  // omitting it preserves the original preview size.
1931
2281
  limit: params.limit,
2282
+ after_date: params.afterDate?.trim(),
2283
+ before_date: params.beforeDate?.trim(),
1932
2284
  dry_run: params.dryRun,
1933
2285
  idempotency_key: params.idempotencyKey
1934
2286
  });
@@ -1939,6 +2291,8 @@ function signalDiscoveryRequestBody(params) {
1939
2291
  limit: params.limit ?? 100,
1940
2292
  sources: params.sources,
1941
2293
  lookback_days: params.lookbackDays,
2294
+ after_date: params.afterDate?.trim(),
2295
+ before_date: params.beforeDate?.trim(),
1942
2296
  dry_run: params.dryRun,
1943
2297
  idempotency_key: params.idempotencyKey
1944
2298
  });
@@ -1947,106 +2301,25 @@ function normalizeSignalDiscoveryResult(params, data) {
1947
2301
  const rawSignals = Array.isArray(data.signals) ? data.signals : [];
1948
2302
  const rawStatus = String(data.status || "").toLowerCase();
1949
2303
  const status = SIGNAL_DISCOVERY_STATUSES.has(rawStatus) ? rawStatus : rawSignals.length > 0 ? "completed" : "failed";
1950
- const signals = rawSignals.map(normalizeSignalDiscoverySignal);
2304
+ const requestedCount = Number(data.requested_count ?? params.limit);
2305
+ const signals = oneSignalPerCompany(publicSignalRows(rawSignals)).slice(
2306
+ 0,
2307
+ Number.isFinite(requestedCount) && requestedCount > 0 ? requestedCount : void 0
2308
+ );
1951
2309
  return {
1952
2310
  success: data.success !== false,
1953
2311
  status,
1954
2312
  capability: "signals_everything",
1955
2313
  signalSearchRunId: String(data.signal_search_run_id ?? params.signalSearchRunId ?? ""),
1956
2314
  query: String(data.query ?? params.query ?? ""),
1957
- requestedCount: Number(data.requested_count ?? params.limit ?? 100),
2315
+ ...Number.isFinite(requestedCount) && requestedCount > 0 ? { requestedCount } : {},
1958
2316
  nextPollAfterSeconds: typeof data.next_poll_after_seconds === "number" ? data.next_poll_after_seconds : void 0,
1959
2317
  signals,
1960
2318
  signalCount: signals.length,
1961
- availableCompanySignalCount: Number.isFinite(Number(data.available_company_signal_count)) ? Number(data.available_company_signal_count) : void 0,
1962
- sourceLanes: Array.isArray(data.source_lanes) ? data.source_lanes.filter((lane) => typeof lane === "string") : void 0,
1963
- evidenceValidation: data.evidence_validation && typeof data.evidence_validation === "object" ? data.evidence_validation : void 0,
1964
- discoveryDiagnostics: data.discovery_diagnostics && typeof data.discovery_diagnostics === "object" ? data.discovery_diagnostics : void 0,
1965
- identityResolution: data.identity_resolution && typeof data.identity_resolution === "object" ? data.identity_resolution : void 0,
1966
- costGuardrail: normalizeSignalDiscoveryCostGuardrail(data.cost_guardrail),
1967
- warnings: Array.isArray(data.warnings) ? data.warnings.filter((warning) => typeof warning === "string") : void 0,
1968
- raw: data
1969
- };
1970
- }
1971
- function normalizeSignalDiscoveryCostGuardrail(value) {
1972
- if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
1973
- const guardrail = value;
1974
- const maxCost = Number(guardrail.max_cost_per_qualified_signal_usd);
1975
- const withinLimit = guardrail.within_limit === true;
1976
- if (!Number.isFinite(maxCost)) return void 0;
1977
- const numberOrNullable = (candidate) => {
1978
- if (candidate === null) return null;
1979
- const numeric = Number(candidate);
1980
- return Number.isFinite(numeric) ? numeric : void 0;
1981
- };
1982
- const numberOrUndefined = (candidate) => {
1983
- const numeric = Number(candidate);
1984
- return Number.isFinite(numeric) ? numeric : void 0;
1985
- };
1986
- return {
1987
- maxCostPerQualifiedSignalUsd: maxCost,
1988
- projectedSourceCostUsd: numberOrNullable(guardrail.projected_source_cost_usd),
1989
- maxSourceCostUsd: numberOrNullable(guardrail.max_source_cost_usd),
1990
- projectedCostPerRequestedCompanySignalUsd: numberOrNullable(
1991
- guardrail.projected_cost_per_requested_company_signal_usd
1992
- ),
1993
- sourceCostUsd: numberOrNullable(guardrail.source_cost_usd),
1994
- costSource: ["observed", "catalog_preflight", "catalog_bounded", "mixed", "unavailable"].includes(String(guardrail.cost_source)) ? String(guardrail.cost_source) : void 0,
1995
- identityResolutionCostUsd: numberOrNullable(guardrail.identity_resolution_cost_usd),
1996
- identityCostSource: [
1997
- "observed_zero_credit_receipts",
1998
- "contractual_zero_cost",
1999
- "not_used",
2000
- "unavailable"
2001
- ].includes(String(guardrail.identity_cost_source)) ? String(guardrail.identity_cost_source) : void 0,
2002
- identityProviderRequests: numberOrUndefined(guardrail.identity_provider_requests),
2003
- qualifiedCompanySignalCount: numberOrUndefined(guardrail.qualified_company_signal_count),
2004
- returnedCompanySignalCount: numberOrUndefined(guardrail.returned_company_signal_count),
2005
- availableCompanySignalCount: numberOrUndefined(guardrail.available_company_signal_count),
2006
- acquisitionCandidateLimit: numberOrUndefined(guardrail.acquisition_candidate_limit),
2007
- minimumQualifiedCompanySignals: numberOrUndefined(guardrail.minimum_qualified_company_signals),
2008
- costPerQualifiedSignalUsd: numberOrNullable(guardrail.cost_per_qualified_signal_usd),
2009
- withinLimit
2010
- };
2011
- }
2012
- function normalizeSignalDiscoverySignal(value) {
2013
- const signal = value && typeof value === "object" && !Array.isArray(value) ? value : {};
2014
- const company = signal.company && typeof signal.company === "object" && !Array.isArray(signal.company) ? signal.company : {};
2015
- const companyName = String(company.name ?? signal.company_name ?? "").trim();
2016
- const companyDomain = String(company.domain ?? signal.company_domain ?? "").trim();
2017
- if (!companyName || !companyDomain) {
2018
- throw new Error("Signals Everything response violated the company attribution contract.");
2019
- }
2020
- const eventDate = String(signal.event_date ?? signal.date ?? signal.signal_date ?? "").trim();
2021
- const sourceUrl = String(signal.source_url ?? signal.url ?? "").trim();
2022
- const evidence = Array.isArray(signal.evidence) ? signal.evidence.map((item) => ({
2023
- url: String(item?.url ?? "").trim(),
2024
- publishedAt: String(item?.published_at ?? item?.publishedAt ?? "").trim(),
2025
- source: String(item?.source ?? "").trim()
2026
- })).filter((item) => Boolean(item.url)) : [];
2027
- if (!eventDate || !sourceUrl || !evidence.some((item) => item.url === sourceUrl && item.publishedAt === eventDate)) {
2028
- throw new Error("Signals Everything response violated the dated-evidence and source-URL contract.");
2029
- }
2030
- return {
2031
- id: signal.id,
2032
- company: {
2033
- name: companyName,
2034
- domain: companyDomain,
2035
- linkedinUrl: company.linkedin_url ?? signal.company_linkedin_url ?? void 0
2036
- },
2037
- title: signal.title ?? "",
2038
- type: signal.type ?? signal.signal_type ?? "unknown",
2039
- summary: signal.summary ?? signal.content ?? signal.description ?? "",
2040
- eventDate,
2041
- evidence,
2042
- content: signal.summary ?? signal.content ?? signal.description ?? "",
2043
- date: signal.event_date ?? signal.date ?? signal.signal_date ?? null,
2044
- detectedAt: signal.event_date ?? signal.detected_at ?? null,
2045
- sourceUrl,
2046
- sourceType: signal.source_type ?? null,
2047
- confidence: signal.confidence ?? signal.confidence_score ?? null,
2048
- classification: signal.signal_classification ?? signal.classification ?? null,
2049
- raw: signal
2319
+ creditsUsed: Number.isFinite(Number(data.credits_used)) ? Number(data.credits_used) : 0,
2320
+ creditsCharged: Number.isFinite(Number(data.credits_charged)) ? Number(data.credits_charged) : 0,
2321
+ billingStatus: data.billing_status === "included" ? "included" : void 0,
2322
+ idempotencyReplayed: typeof data.idempotency_replayed === "boolean" ? data.idempotency_replayed : void 0
2050
2323
  };
2051
2324
  }
2052
2325
  function validateBatchSize(items) {
@@ -2100,9 +2373,6 @@ function normalizedBatchDomain(value) {
2100
2373
  function normalizedBatchLinkedIn(value) {
2101
2374
  return normalizedBatchText(value).replace(/\/+$/, "");
2102
2375
  }
2103
- function normalizedBatchList(value) {
2104
- return Array.isArray(value) ? value.map(normalizedBatchText).filter(Boolean).sort() : [];
2105
- }
2106
2376
  function normalizedFindEmailBatchName(request) {
2107
2377
  const fullName = normalizedBatchText(request.full_name);
2108
2378
  const componentName = [normalizedBatchText(request.first_name), normalizedBatchText(request.last_name)].filter(Boolean).join(" ");
@@ -2117,39 +2387,24 @@ function coreProductBatchRequestKey(path, request) {
2117
2387
  normalizedBatchDomain(request.company_domain),
2118
2388
  normalizedBatchLinkedIn(request.linkedin_url),
2119
2389
  normalizedBatchText(request.company_name),
2120
- request.skip_cache === true || request.bypass_cache === true,
2121
2390
  normalizedBatchIdempotencyKey(request.idempotency_key)
2122
2391
  ]);
2123
2392
  }
2124
2393
  if (path === "api/v1/verify-email") {
2125
2394
  return JSON.stringify([
2126
2395
  normalizedBatchText(request.email),
2127
- request.skip_cache === true || request.bypass_cache === true,
2128
2396
  request.skip_catch_all_verification === true,
2129
2397
  request.skip_esp_check === true,
2130
2398
  normalizedBatchIdempotencyKey(request.idempotency_key)
2131
2399
  ]);
2132
2400
  }
2133
2401
  if (path === "api/v1/company-signals") {
2134
- const online = request.online !== false;
2135
- const deepSearch = request.enable_deep_search === void 0 ? online : request.enable_deep_search !== false;
2136
2402
  return JSON.stringify([
2137
2403
  normalizedBatchText(request.signal_run_id),
2138
2404
  normalizedBatchDomain(request.company_domain || request.domain),
2139
2405
  normalizedBatchText(request.company_name),
2140
- normalizedBatchText(request.company_id),
2141
- normalizedBatchLinkedIn(request.linkedin_url),
2142
- normalizedBatchText(request.industry),
2143
2406
  typeof request.research_prompt === "string" ? request.research_prompt.trim() : "",
2144
- normalizedBatchList(request.signal_types),
2145
- Number(request.target_signal_count) || null,
2146
2407
  Number(request.lookback_days) || null,
2147
- online,
2148
- deepSearch,
2149
- normalizedBatchText(request.search_mode || "balanced"),
2150
- request.enable_outreach_intelligence === true,
2151
- request.enable_predictive_intelligence === true,
2152
- request.skip_cache === true || request.bypass_cache === true,
2153
2408
  normalizedBatchIdempotencyKey(request.idempotency_key)
2154
2409
  ]);
2155
2410
  }
@@ -2159,9 +2414,12 @@ function coreProductBatchRequestKey(path, request) {
2159
2414
  typeof request.title === "string" ? request.title.trim() : "",
2160
2415
  typeof request.campaign_offer === "string" ? request.campaign_offer.trim() : "",
2161
2416
  typeof request.research_prompt === "string" ? request.research_prompt.trim() : "",
2417
+ normalizedBatchText(request.copy_evidence_mode),
2162
2418
  Number(request.lookback_days) || null,
2163
2419
  typeof request.signal_run_id === "string" ? request.signal_run_id.trim() : "",
2164
- request.skip_cache === true,
2420
+ typeof request.signal_search_run_id === "string" ? request.signal_search_run_id.trim() : "",
2421
+ typeof request.fact_id === "string" ? request.fact_id.trim() : "",
2422
+ typeof request.event_id === "string" ? request.event_id.trim() : "",
2165
2423
  request.enable_deep_search === true,
2166
2424
  normalizedBatchIdempotencyKey(request.idempotency_key)
2167
2425
  ]);
@@ -2266,43 +2524,60 @@ function signalToCopyRequestBody(params) {
2266
2524
  person_name: params.personName,
2267
2525
  title: params.title,
2268
2526
  campaign_offer: params.campaignOffer,
2269
- research_prompt: params.researchPrompt,
2270
- lookback_days: params.lookbackDays,
2527
+ copy_evidence_mode: params.copyEvidenceMode,
2528
+ lookback_days: 365,
2271
2529
  signal_run_id: params.signalRunId,
2272
- skip_cache: params.skipCache,
2530
+ signal_search_run_id: params.signalSearchRunId,
2531
+ fact_id: params.factId,
2532
+ event_id: params.eventId,
2273
2533
  enable_deep_search: params.enableDeepSearch,
2274
2534
  max_wait_ms: params.maxWaitMs,
2275
2535
  dry_run: params.dryRun,
2276
2536
  idempotency_key: params.idempotencyKey
2277
2537
  });
2278
2538
  }
2279
- function validateLargeAvailableDataSignalCopyBatch(requests) {
2539
+ function validateLargeSignalCopyBatch(requests) {
2280
2540
  if (requests.length <= 25) return;
2281
2541
  const invalidIndex = requests.findIndex(
2282
- (request) => request.skipCache === true || request.enableDeepSearch === true || Boolean(request.idempotencyKey?.trim()) || request.maxWaitMs !== void 0 || request.pollIntervalMs !== void 0 || request.waitForResult === false || !request.companyDomain?.trim() || !request.personName?.trim() || !request.title?.trim() || !request.campaignOffer?.trim()
2542
+ (request) => Boolean(request.idempotencyKey?.trim()) || request.maxWaitMs !== void 0 || request.pollIntervalMs !== void 0 || request.waitForResult === false || Boolean(request.signalSearchRunId?.trim()) || Boolean(request.factId?.trim()) || Boolean(request.eventId?.trim()) || !request.companyDomain?.trim() || !request.personName?.trim() || !request.title?.trim() || !request.campaignOffer?.trim()
2283
2543
  );
2284
2544
  if (invalidIndex >= 0) {
2285
2545
  throw new RangeError(
2286
- `Signal to Copy batches larger than 25 are available-data-only; row ${invalidIndex} requests fresh/deep/synchronous controls or lacks required recipient fields. Split fresh requests into batches of at most 25.`
2546
+ `Signal to Copy batch row ${invalidIndex} uses canonical references (supported only in synchronous batches of 25 or fewer), uses unsupported row-level execution controls, or lacks required recipient fields. Put wait and idempotency controls in the batch options.`
2287
2547
  );
2288
2548
  }
2289
2549
  }
2290
- function availableDataSignalCopyRequestBody(params) {
2550
+ function durableSignalCopyRequestBody(params) {
2291
2551
  return compact({
2292
2552
  company_domain: params.companyDomain,
2293
2553
  person_name: params.personName,
2294
2554
  title: params.title,
2295
2555
  campaign_offer: params.campaignOffer,
2296
- research_prompt: params.researchPrompt,
2297
- lookback_days: params.lookbackDays,
2298
- signal_run_id: params.signalRunId
2556
+ copy_evidence_mode: params.copyEvidenceMode,
2557
+ lookback_days: 365,
2558
+ signal_run_id: params.signalRunId,
2559
+ signal_search_run_id: params.signalSearchRunId,
2560
+ fact_id: params.factId,
2561
+ event_id: params.eventId,
2562
+ enable_deep_search: params.enableDeepSearch
2299
2563
  });
2300
2564
  }
2301
2565
  function validateSignalToCopyParams(params) {
2302
2566
  validateCoreProductMaxWaitMs(params.maxWaitMs);
2567
+ if (params.copyEvidenceMode !== void 0 && !["signal_led", "firmographic"].includes(params.copyEvidenceMode)) {
2568
+ throw new RangeError("copyEvidenceMode must be signal_led or firmographic");
2569
+ }
2303
2570
  if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
2304
2571
  throw new RangeError("lookbackDays must be an integer between 1 and 365");
2305
2572
  }
2573
+ if (params.signalSearchRunId !== void 0 && !params.signalSearchRunId.trim()) {
2574
+ throw new TypeError("signalSearchRunId must be a non-empty string");
2575
+ }
2576
+ for (const [field, value] of [["factId", params.factId], ["eventId", params.eventId]]) {
2577
+ if (value !== void 0 && !/^[0-9a-f]{64}$/.test(value.trim())) {
2578
+ throw new TypeError(`${field} must be a lowercase 64-character SHA-256 identifier`);
2579
+ }
2580
+ }
2306
2581
  if (typeof params.signalRunId === "string" && params.signalRunId.trim()) return;
2307
2582
  const missing = [
2308
2583
  ["companyDomain", params.companyDomain],
@@ -2321,6 +2596,7 @@ function validateCoreProductMaxWaitMs(value) {
2321
2596
  }
2322
2597
  }
2323
2598
  function normalizeSignalToCopyResult(data) {
2599
+ data = publicProductData(data, "signal_to_copy");
2324
2600
  const failed = coreProductResponseFailed(data);
2325
2601
  return {
2326
2602
  success: !failed,
@@ -2329,6 +2605,11 @@ function normalizeSignalToCopyResult(data) {
2329
2605
  status: data.status,
2330
2606
  runId: data.run_id ?? data.signal_run_id,
2331
2607
  companySignalRunId: data.company_signal_run_id,
2608
+ signalSearchRunId: data.signal_search_run_id,
2609
+ factId: data.fact_id,
2610
+ eventId: data.event_id,
2611
+ canonicalSourceUrl: data.canonical_source_url,
2612
+ evidenceReuse: data.evidence_reuse,
2332
2613
  resumeContextPersisted: data.resume_context_persisted,
2333
2614
  strongestSignal: failed ? "" : data.strongest_signal ?? "",
2334
2615
  whyNow: failed ? "" : data.why_now ?? "",
@@ -2337,17 +2618,11 @@ function normalizeSignalToCopyResult(data) {
2337
2618
  confidence: failed ? 0 : data.confidence ?? 0,
2338
2619
  evidenceUrl: failed ? "" : data.evidence_url ?? "",
2339
2620
  researchPrompt: data.research_prompt,
2621
+ copyEvidenceMode: data.copy_evidence_mode,
2340
2622
  empty: data.empty,
2341
2623
  emptyReason: data.empty_reason,
2342
2624
  researchMetadata: failed ? void 0 : data.research_metadata,
2343
- billingMetadata: data.billing_metadata,
2344
- resultReturnedFrom: data.result_returned_from,
2345
- cacheHit: data.cache_hit,
2346
- freshEnrichmentUsed: data.fresh_enrichment_used,
2347
2625
  creditsUsed: data.credits_used,
2348
- liveProviderCalled: data.live_provider_called,
2349
- aiProviderCalled: data.ai_provider_called,
2350
- byoAiUsed: data.byo_ai_used,
2351
2626
  unlimitedSignalToCopy: data.unlimited_signal_to_copy,
2352
2627
  signalToCopyEntitlement: data.signal_to_copy_entitlement,
2353
2628
  variations: (failed ? [] : data.variations ?? []).map((variation) => ({
@@ -2361,6 +2636,117 @@ function normalizeSignalToCopyResult(data) {
2361
2636
  raw: data
2362
2637
  };
2363
2638
  }
2639
+ function signalAwarenessMonitorRequest(monitor) {
2640
+ return compact({
2641
+ company_name: monitor.companyName,
2642
+ domain: monitor.domain,
2643
+ template: monitor.template,
2644
+ signal_config: monitor.signalConfig,
2645
+ schedule_cron: monitor.scheduleCron,
2646
+ webhook_url: monitor.webhookUrl
2647
+ });
2648
+ }
2649
+ function signalAwarenessRequestBody(request) {
2650
+ return compact({
2651
+ action: request.action,
2652
+ monitor_id: request.monitorId,
2653
+ monitor: request.monitor ? signalAwarenessMonitorRequest(request.monitor) : void 0,
2654
+ monitors: request.monitors?.map(signalAwarenessMonitorRequest),
2655
+ defaults: request.defaults,
2656
+ updates: request.updates,
2657
+ limit: request.limit,
2658
+ offset: request.offset,
2659
+ idempotency_key: request.idempotencyKey,
2660
+ dry_run: request.dryRun
2661
+ });
2662
+ }
2663
+ function normalizeSignalAwarenessResponse(data) {
2664
+ const payload = data.data && typeof data.data === "object" ? data.data : data;
2665
+ const signals = Array.isArray(payload.signals) ? oneSignalPerCompany(payload.signals.flatMap(normalizeSignalAwarenessSignal)) : void 0;
2666
+ const monitors = Array.isArray(payload.monitors) ? payload.monitors.map(normalizeSignalAwarenessMonitor).filter((value) => value !== void 0) : void 0;
2667
+ const monitor = normalizeSignalAwarenessMonitor(payload.monitor);
2668
+ const run = normalizeSignalAwarenessRun(payload.run);
2669
+ const billing = payload.billing && typeof payload.billing === "object" ? payload.billing : {};
2670
+ const creditsUsed = Number(payload.credits_used ?? billing.credits_used);
2671
+ return {
2672
+ success: data.success !== false,
2673
+ ...monitors ? { monitors } : {},
2674
+ ...monitor ? { monitor } : {},
2675
+ ...signals ? { signals } : {},
2676
+ ...signals ? { signalCount: signals.length } : {},
2677
+ ...typeof payload.monitor_id === "string" ? { monitorId: payload.monitor_id } : {},
2678
+ ...typeof payload.run_id === "string" ? { runId: payload.run_id } : {},
2679
+ ...run ? { run } : {},
2680
+ ...Number.isInteger(creditsUsed) && creditsUsed >= 0 ? { creditsUsed } : {},
2681
+ ...Number.isFinite(Number(payload.created)) ? { created: Number(payload.created) } : {},
2682
+ ...Number.isFinite(Number(payload.skipped)) ? { skipped: Number(payload.skipped) } : {},
2683
+ ...Number.isFinite(Number(payload.total)) ? { total: Number(payload.total) } : {},
2684
+ ...Number.isFinite(Number(payload.limit)) ? { limit: Number(payload.limit) } : {},
2685
+ ...Number.isFinite(Number(payload.offset)) ? { offset: Number(payload.offset) } : {},
2686
+ ...typeof payload.has_more === "boolean" ? { hasMore: payload.has_more } : {},
2687
+ ...payload.idempotent_replay === true ? { idempotentReplay: true } : {}
2688
+ };
2689
+ }
2690
+ function signalAwarenessRecord(value) {
2691
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
2692
+ }
2693
+ function signalAwarenessText(value, maximum = 500) {
2694
+ return typeof value === "string" && value.trim() && value.trim().length <= maximum ? value.trim() : void 0;
2695
+ }
2696
+ function signalAwarenessCount(value) {
2697
+ const numeric = Number(value);
2698
+ return Number.isInteger(numeric) && numeric >= 0 ? numeric : void 0;
2699
+ }
2700
+ function normalizeSignalAwarenessMonitor(value) {
2701
+ const monitor = signalAwarenessRecord(value);
2702
+ const result = {};
2703
+ const id = signalAwarenessText(monitor.id, 200);
2704
+ const companyName = signalAwarenessText(monitor.company_name, 300);
2705
+ const domain = signalAwarenessText(monitor.domain, 253);
2706
+ const status = signalAwarenessText(monitor.status, 80);
2707
+ const schedule = signalAwarenessText(monitor.schedule, 120);
2708
+ if (id) result.id = id;
2709
+ if (companyName) result.company_name = companyName;
2710
+ if (domain) result.domain = domain;
2711
+ if (status) result.status = status;
2712
+ if (schedule) result.schedule = schedule;
2713
+ for (const key of ["last_run_at", "next_run_at", "created_at", "updated_at"]) {
2714
+ const timestamp = signalAwarenessText(monitor[key], 64);
2715
+ if (timestamp && Number.isFinite(Date.parse(timestamp))) result[key] = timestamp;
2716
+ }
2717
+ return Object.keys(result).length > 0 ? result : void 0;
2718
+ }
2719
+ function normalizeSignalAwarenessRun(value) {
2720
+ const run = signalAwarenessRecord(value);
2721
+ const result = {};
2722
+ const id = signalAwarenessText(run.id, 200);
2723
+ const monitorId = signalAwarenessText(run.monitor_id, 200);
2724
+ const status = signalAwarenessText(run.status, 80);
2725
+ const signalsFound = signalAwarenessCount(run.signals_found);
2726
+ if (id) result.id = id;
2727
+ if (monitorId) result.monitor_id = monitorId;
2728
+ if (status) result.status = status;
2729
+ if (signalsFound !== void 0) result.signals_found = signalsFound;
2730
+ for (const key of ["started_at", "completed_at", "created_at"]) {
2731
+ const timestamp = signalAwarenessText(run[key], 64);
2732
+ if (timestamp && Number.isFinite(Date.parse(timestamp))) result[key] = timestamp;
2733
+ }
2734
+ return Object.keys(result).length > 0 ? result : void 0;
2735
+ }
2736
+ function normalizeSignalAwarenessSignal(value) {
2737
+ const signal = value && typeof value === "object" && !Array.isArray(value) ? value : {};
2738
+ const rawData = signal.raw_data && typeof signal.raw_data === "object" && !Array.isArray(signal.raw_data) ? signal.raw_data : {};
2739
+ const row = publicSignalRow({
2740
+ ...rawData,
2741
+ ...signal,
2742
+ signal_type: signal.signal_type ?? rawData.signal_type,
2743
+ source_url: signal.canonical_source_url ?? rawData.canonical_source_url ?? signal.source_url ?? rawData.source_url ?? rawData.url,
2744
+ date: signal.date ?? signal.event_date ?? signal.detected_at ?? rawData.date ?? rawData.event_date ?? rawData.detected_at ?? rawData.observed_at,
2745
+ company_name: signal.company_name ?? rawData.company_name,
2746
+ company_domain: signal.domain ?? signal.company_domain ?? rawData.company_domain ?? rawData.domain
2747
+ });
2748
+ return row ? [row] : [];
2749
+ }
2364
2750
  function isPendingSignalResponse(data) {
2365
2751
  if (coreProductResponseFailed(data)) return false;
2366
2752
  return ["triggered", "queued", "processing", "pending", "pending_version", "waiting_for_deploy"].includes(String(data.status || "").toLowerCase());