@signaliz/sdk 1.0.66 → 1.0.68

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,20 +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,
1669
- historicalBillingMetadata: data.historical_billing_metadata,
1670
- resultReturnedFrom: data.result_returned_from ?? billingMetadata?.result_returned_from,
1671
- cacheHit: typeof data.cache_hit === "boolean" ? data.cache_hit : billingMetadata?.cache_hit,
1672
- negativeCacheHit: data.negative_cache_hit,
1673
- negativeCacheTtlSeconds: data.negative_cache_ttl_seconds,
1674
- cacheTier: data.cache_tier,
1675
- freshEnrichmentUsed: typeof data.fresh_enrichment_used === "boolean" ? data.fresh_enrichment_used : billingMetadata?.fresh_enrichment_used,
1676
- liveProviderCalled: typeof data.live_provider_called === "boolean" ? data.live_provider_called : billingMetadata?.live_provider_called,
1677
- openrouterCalled: typeof data.openrouter_called === "boolean" ? data.openrouter_called : billingMetadata?.openrouter_called,
1678
- byoOpenrouterUsed: typeof data.byo_openrouter_used === "boolean" ? data.byo_openrouter_used : billingMetadata?.byo_openrouter_used,
1933
+ creditsUsed: data.credits_used,
1934
+ creditsCharged: data.credits_charged,
1935
+ billingReplayed: data.billing_replayed,
1936
+ idempotencyReplayed: data.idempotency_replayed,
1679
1937
  error: processing || found ? void 0 : coreProductErrorMessage(data) ?? "No verified email found",
1680
1938
  errorCode: processing || found ? void 0 : coreProductErrorCode(data) ?? "EMAIL_NOT_FOUND",
1681
1939
  status: processing ? "processing" : "completed",
@@ -1687,18 +1945,17 @@ function normalizeFindEmailResult(data) {
1687
1945
  doNotAutoResubmit: data.do_not_auto_resubmit === true,
1688
1946
  recoveryMode: data.recovery_mode === "same_run" ? "same_run" : void 0,
1689
1947
  recoveryStatus: ["pending", "completed"].includes(String(data.recovery_status)) ? data.recovery_status : void 0,
1690
- cachePublicationStatus: data.cache_publication_status,
1691
- cachePublicationRetryEligible: data.cache_publication_retry_eligible,
1692
1948
  raw: data
1693
1949
  };
1694
1950
  }
1695
1951
  function normalizeVerifyEmailResult(email, data) {
1952
+ data = publicProductData(data, "verify_email");
1696
1953
  const failed = coreProductResponseFailed(data);
1697
1954
  const malformed = data.is_malformed === true || data.verification_verdict === "malformed" || data.verification_status === "malformed" || data.deliverability_status === "malformed";
1698
- const verificationStatus = String(
1955
+ const verificationStatus = normalizeVerifyEmailStatus(
1699
1956
  failed ? malformed ? "malformed" : "error" : data.verification_status ?? data.verification_verdict ?? data.deliverability_status ?? "unknown"
1700
- ).toLowerCase();
1701
- const deliverabilityStatus = String(data.deliverability_status ?? verificationStatus).toLowerCase();
1957
+ );
1958
+ const deliverabilityStatus = normalizeVerifyEmailStatus(data.deliverability_status ?? verificationStatus);
1702
1959
  const verified = !failed && (data.email_verified === true || ["valid", "deliverable"].includes(verificationStatus));
1703
1960
  const isCatchAll = data.email_is_catch_all ?? data.is_catch_all ?? data.catch_all ?? data.diagnostics?.is_catch_all ?? false;
1704
1961
  const verifiedForSending = !failed && data.verified_for_sending === true;
@@ -1719,10 +1976,12 @@ function normalizeVerifyEmailResult(email, data) {
1719
1976
  verifiedForSending,
1720
1977
  verificationStatus,
1721
1978
  deliverabilityStatus,
1722
- 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
+ ),
1723
1982
  isRoleAccount: data.is_role_account === true || data.email_is_role_account === true || data.role === true,
1724
1983
  quality: typeof data.quality === "string" ? data.quality : null,
1725
- 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),
1726
1985
  smtpStatus: data.smtp_status ?? (isCatchAll ? "accept_all" : verifiedForSending ? "accepted" : "not_checked"),
1727
1986
  providerStatus: data.provider_status ?? verificationStatus,
1728
1987
  failureReason: data.failure_reason ?? (verifiedForSending ? "none" : isCatchAll ? "catch_all_domain_not_send_safe" : "verification_not_send_safe"),
@@ -1731,54 +1990,49 @@ function normalizeVerifyEmailResult(email, data) {
1731
1990
  verificationSource: data.verification_source,
1732
1991
  verificationObservedAt: typeof data.verification_observed_at === "string" ? data.verification_observed_at : void 0,
1733
1992
  billingReplayed: data.billing_replayed,
1993
+ idempotencyReplayed: data.idempotency_replayed,
1734
1994
  creditsUsed: data.credits_used,
1735
- billingMetadata: data.billing_metadata,
1736
- historicalBillingMetadata: data.historical_billing_metadata,
1737
- resultReturnedFrom: data.result_returned_from,
1738
- cacheHit: data.cache_hit,
1739
- negativeCacheHit: data.negative_cache_hit,
1740
- negativeCacheTtlSeconds: data.negative_cache_ttl_seconds,
1741
- cacheTier: data.cache_tier,
1742
- freshEnrichmentUsed: data.fresh_enrichment_used,
1743
- liveProviderCalled: data.live_provider_called,
1744
- openrouterCalled: data.openrouter_called,
1745
- byoOpenrouterUsed: data.byo_openrouter_used,
1746
- estimatedExternalCostUsd: data.estimated_external_cost_usd,
1747
1995
  runId: data.run_id ?? verificationRunId,
1748
- cachePublicationStatus: data.cache_publication_status,
1749
- cachePublicationRetryEligible: data.cache_publication_retry_eligible,
1750
1996
  suggestedAction: data.suggested_action,
1751
1997
  raw: data
1752
1998
  };
1753
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
+ }
1754
2025
  function companySignalRequestBody(params) {
1755
- const online = params.online ?? true;
1756
2026
  return compact({
1757
2027
  signal_run_id: params.signalRunId,
1758
- company_domain: params.companyDomain,
1759
- company_name: params.companyName,
1760
- research_prompt: params.researchPrompt,
1761
- signal_types: params.signalTypes,
1762
- target_signal_count: params.targetSignalCount,
1763
- lookback_days: params.lookbackDays,
1764
- online,
1765
- enable_deep_search: params.enableDeepSearch ?? online,
1766
- search_mode: params.searchMode ?? "balanced",
1767
- include_summary: params.includeSummary,
1768
- enable_outreach_intelligence: params.enableOutreachIntelligence,
1769
- enable_predictive_intelligence: params.enablePredictiveIntelligence,
1770
- skip_cache: params.skipCache,
1771
- include_candidate_evidence: params.includeCandidateEvidence,
1772
- wait_for_result: true,
1773
- max_wait_ms: params.maxWaitMs,
2028
+ domain: params.domain ?? params.companyDomain,
1774
2029
  dry_run: params.dryRun,
1775
2030
  idempotency_key: params.idempotencyKey
1776
2031
  });
1777
2032
  }
1778
2033
  function validateCompanySignalParams(params) {
1779
- validateCoreProductMaxWaitMs(params.maxWaitMs);
1780
- if (params.targetSignalCount !== void 0 && (!Number.isInteger(params.targetSignalCount) || params.targetSignalCount < 1 || params.targetSignalCount > 15)) {
1781
- 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");
1782
2036
  }
1783
2037
  if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
1784
2038
  throw new RangeError("lookbackDays must be an integer between 1 and 365");
@@ -1786,25 +2040,11 @@ function validateCompanySignalParams(params) {
1786
2040
  }
1787
2041
  function companySignalParamsFromRecoveredRow(row) {
1788
2042
  return {
1789
- companyDomain: row.company?.domain ?? row.company_domain,
1790
- companyName: row.company?.name ?? row.company_name,
2043
+ domain: row.company?.domain ?? row.company_domain,
1791
2044
  signalRunId: row.signal_run_id ?? row.run_id
1792
2045
  };
1793
2046
  }
1794
- var COMPANY_SIGNAL_LARGE_BATCH_CONTROL_FIELDS = [
1795
- "research_prompt",
1796
- "signal_types",
1797
- "target_signal_count",
1798
- "lookback_days",
1799
- "online",
1800
- "enable_deep_search",
1801
- "search_mode",
1802
- "include_summary",
1803
- "enable_outreach_intelligence",
1804
- "enable_predictive_intelligence",
1805
- "skip_cache",
1806
- "include_candidate_evidence"
1807
- ];
2047
+ var COMPANY_SIGNAL_LARGE_BATCH_CONTROL_FIELDS = [];
1808
2048
  function companySignalLargeBatchSubmission(requests) {
1809
2049
  if (requests.length <= 25) return null;
1810
2050
  if (requests.some(
@@ -1821,67 +2061,158 @@ function companySignalLargeBatchSubmission(requests) {
1821
2061
  COMPANY_SIGNAL_LARGE_BATCH_CONTROL_FIELDS.filter((field) => request[field] !== void 0).map((field) => [field, request[field]])
1822
2062
  );
1823
2063
  if (JSON.stringify(requestControls) !== controlKey) return null;
1824
- 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();
1825
2065
  if (!hasIdentity) return null;
1826
2066
  }
1827
2067
  return {
1828
- requests: requests.map((request) => compact({
1829
- company_domain: request.company_domain,
1830
- company_name: request.company_name
1831
- })),
2068
+ requests: requests.map((request) => compact({ domain: request.domain })),
1832
2069
  submissionFields
1833
2070
  };
1834
2071
  }
1835
2072
  function normalizeCompanySignalResult(params, data) {
2073
+ data = publicProductData(data, "company_signals");
1836
2074
  const failed = coreProductResponseFailed(data);
1837
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);
1838
2086
  return {
1839
2087
  success: !failed,
1840
2088
  error: failed ? coreProductErrorMessage(data) : void 0,
1841
2089
  errorCode: failed ? coreProductErrorCode(data) : void 0,
1842
2090
  status: data.status,
1843
2091
  signalRunId: data.signal_run_id ?? data.run_id ?? params.signalRunId,
1844
- company: {
1845
- name: data.company?.name ?? params.companyName ?? null,
1846
- domain: data.company?.domain ?? params.companyDomain ?? null
1847
- },
1848
- signals: rawSignals.map((signal) => {
1849
- return {
1850
- id: signal.id,
1851
- title: signal.title ?? "",
1852
- type: signal.type ?? signal.signal_type ?? "unknown",
1853
- content: signal.content ?? signal.description ?? "",
1854
- date: signal.date ?? null,
1855
- detectedAt: signal.detected_at ?? null,
1856
- datePrecision: signal.date_precision,
1857
- sourceUrl: signal.source_url ?? signal.url ?? null,
1858
- sourceType: signal.source_type,
1859
- confidence: signal.confidence ?? signal.confidence_score ?? null,
1860
- signalFamily: signal.signal_family,
1861
- eventType: signal.signal_event_type,
1862
- eventLabel: signal.signal_event_label,
1863
- classification: signal.signal_classification ?? null
1864
- };
1865
- }),
1866
- signalCount: failed ? 0 : data.signal_count ?? data.total_signals ?? rawSignals.length,
1867
- signalSummary: failed ? null : data.signal_summary ?? null,
1868
- intelligence: failed ? null : data.intelligence ?? null,
1869
- copyFuel: failed ? null : data.copy_fuel ?? null,
1870
- evidenceValidation: failed ? void 0 : data.evidence_validation,
1871
- evidenceSources: failed ? [] : data.metadata?.evidence_sources ?? data.evidence_sources,
1872
- evidenceCount: failed ? 0 : data.evidence_count,
1873
- evidenceCountTotal: failed ? 0 : data.evidence_count_total,
1874
- evidenceSourcesOmitted: failed ? 0 : data.evidence_sources_omitted,
1875
- evidenceScope: failed ? void 0 : data.evidence_scope,
1876
- billingMetadata: data.billing_metadata,
1877
- resultReturnedFrom: data.result_returned_from,
1878
- cacheHit: data.cache_hit,
1879
- freshEnrichmentUsed: data.fresh_enrichment_used,
1880
- creditsUsed: data.credits_used,
1881
- liveProviderCalled: data.live_provider_called,
1882
- aiProviderCalled: data.ai_provider_called,
1883
- byoAiUsed: data.byo_ai_used,
1884
- 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
1885
2216
  };
1886
2217
  }
1887
2218
  var SIGNAL_DISCOVERY_SOURCES = /* @__PURE__ */ new Set(["web", "news"]);
@@ -1914,10 +2245,32 @@ function validateSignalDiscoveryParams(params) {
1914
2245
  if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
1915
2246
  throw new RangeError("lookbackDays must be an integer between 1 and 365");
1916
2247
  }
2248
+ validateSignalDateWindow(params);
1917
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)))) {
1918
2250
  throw new TypeError("sources must contain only web or news");
1919
2251
  }
1920
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
+ }
1921
2274
  function signalDiscoveryRequestBody(params) {
1922
2275
  const runId = typeof params.signalSearchRunId === "string" ? params.signalSearchRunId.trim() : "";
1923
2276
  if (runId) {
@@ -1926,6 +2279,8 @@ function signalDiscoveryRequestBody(params) {
1926
2279
  // An explicit limit expands or narrows the retained qualified cohort;
1927
2280
  // omitting it preserves the original preview size.
1928
2281
  limit: params.limit,
2282
+ after_date: params.afterDate?.trim(),
2283
+ before_date: params.beforeDate?.trim(),
1929
2284
  dry_run: params.dryRun,
1930
2285
  idempotency_key: params.idempotencyKey
1931
2286
  });
@@ -1936,6 +2291,8 @@ function signalDiscoveryRequestBody(params) {
1936
2291
  limit: params.limit ?? 100,
1937
2292
  sources: params.sources,
1938
2293
  lookback_days: params.lookbackDays,
2294
+ after_date: params.afterDate?.trim(),
2295
+ before_date: params.beforeDate?.trim(),
1939
2296
  dry_run: params.dryRun,
1940
2297
  idempotency_key: params.idempotencyKey
1941
2298
  });
@@ -1944,106 +2301,25 @@ function normalizeSignalDiscoveryResult(params, data) {
1944
2301
  const rawSignals = Array.isArray(data.signals) ? data.signals : [];
1945
2302
  const rawStatus = String(data.status || "").toLowerCase();
1946
2303
  const status = SIGNAL_DISCOVERY_STATUSES.has(rawStatus) ? rawStatus : rawSignals.length > 0 ? "completed" : "failed";
1947
- 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
+ );
1948
2309
  return {
1949
2310
  success: data.success !== false,
1950
2311
  status,
1951
2312
  capability: "signals_everything",
1952
2313
  signalSearchRunId: String(data.signal_search_run_id ?? params.signalSearchRunId ?? ""),
1953
2314
  query: String(data.query ?? params.query ?? ""),
1954
- requestedCount: Number(data.requested_count ?? params.limit ?? 100),
2315
+ ...Number.isFinite(requestedCount) && requestedCount > 0 ? { requestedCount } : {},
1955
2316
  nextPollAfterSeconds: typeof data.next_poll_after_seconds === "number" ? data.next_poll_after_seconds : void 0,
1956
2317
  signals,
1957
2318
  signalCount: signals.length,
1958
- availableCompanySignalCount: Number.isFinite(Number(data.available_company_signal_count)) ? Number(data.available_company_signal_count) : void 0,
1959
- sourceLanes: Array.isArray(data.source_lanes) ? data.source_lanes.filter((lane) => typeof lane === "string") : void 0,
1960
- evidenceValidation: data.evidence_validation && typeof data.evidence_validation === "object" ? data.evidence_validation : void 0,
1961
- discoveryDiagnostics: data.discovery_diagnostics && typeof data.discovery_diagnostics === "object" ? data.discovery_diagnostics : void 0,
1962
- identityResolution: data.identity_resolution && typeof data.identity_resolution === "object" ? data.identity_resolution : void 0,
1963
- costGuardrail: normalizeSignalDiscoveryCostGuardrail(data.cost_guardrail),
1964
- warnings: Array.isArray(data.warnings) ? data.warnings.filter((warning) => typeof warning === "string") : void 0,
1965
- raw: data
1966
- };
1967
- }
1968
- function normalizeSignalDiscoveryCostGuardrail(value) {
1969
- if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
1970
- const guardrail = value;
1971
- const maxCost = Number(guardrail.max_cost_per_qualified_signal_usd);
1972
- const withinLimit = guardrail.within_limit === true;
1973
- if (!Number.isFinite(maxCost)) return void 0;
1974
- const numberOrNullable = (candidate) => {
1975
- if (candidate === null) return null;
1976
- const numeric = Number(candidate);
1977
- return Number.isFinite(numeric) ? numeric : void 0;
1978
- };
1979
- const numberOrUndefined = (candidate) => {
1980
- const numeric = Number(candidate);
1981
- return Number.isFinite(numeric) ? numeric : void 0;
1982
- };
1983
- return {
1984
- maxCostPerQualifiedSignalUsd: maxCost,
1985
- projectedSourceCostUsd: numberOrNullable(guardrail.projected_source_cost_usd),
1986
- maxSourceCostUsd: numberOrNullable(guardrail.max_source_cost_usd),
1987
- projectedCostPerRequestedCompanySignalUsd: numberOrNullable(
1988
- guardrail.projected_cost_per_requested_company_signal_usd
1989
- ),
1990
- sourceCostUsd: numberOrNullable(guardrail.source_cost_usd),
1991
- costSource: ["observed", "catalog_preflight", "catalog_bounded", "mixed", "unavailable"].includes(String(guardrail.cost_source)) ? String(guardrail.cost_source) : void 0,
1992
- identityResolutionCostUsd: numberOrNullable(guardrail.identity_resolution_cost_usd),
1993
- identityCostSource: [
1994
- "observed_zero_credit_receipts",
1995
- "contractual_zero_cost",
1996
- "not_used",
1997
- "unavailable"
1998
- ].includes(String(guardrail.identity_cost_source)) ? String(guardrail.identity_cost_source) : void 0,
1999
- identityProviderRequests: numberOrUndefined(guardrail.identity_provider_requests),
2000
- qualifiedCompanySignalCount: numberOrUndefined(guardrail.qualified_company_signal_count),
2001
- returnedCompanySignalCount: numberOrUndefined(guardrail.returned_company_signal_count),
2002
- availableCompanySignalCount: numberOrUndefined(guardrail.available_company_signal_count),
2003
- acquisitionCandidateLimit: numberOrUndefined(guardrail.acquisition_candidate_limit),
2004
- minimumQualifiedCompanySignals: numberOrUndefined(guardrail.minimum_qualified_company_signals),
2005
- costPerQualifiedSignalUsd: numberOrNullable(guardrail.cost_per_qualified_signal_usd),
2006
- withinLimit
2007
- };
2008
- }
2009
- function normalizeSignalDiscoverySignal(value) {
2010
- const signal = value && typeof value === "object" && !Array.isArray(value) ? value : {};
2011
- const company = signal.company && typeof signal.company === "object" && !Array.isArray(signal.company) ? signal.company : {};
2012
- const companyName = String(company.name ?? signal.company_name ?? "").trim();
2013
- const companyDomain = String(company.domain ?? signal.company_domain ?? "").trim();
2014
- if (!companyName || !companyDomain) {
2015
- throw new Error("Signals Everything response violated the company attribution contract.");
2016
- }
2017
- const eventDate = String(signal.event_date ?? signal.date ?? signal.signal_date ?? "").trim();
2018
- const sourceUrl = String(signal.source_url ?? signal.url ?? "").trim();
2019
- const evidence = Array.isArray(signal.evidence) ? signal.evidence.map((item) => ({
2020
- url: String(item?.url ?? "").trim(),
2021
- publishedAt: String(item?.published_at ?? item?.publishedAt ?? "").trim(),
2022
- source: String(item?.source ?? "").trim()
2023
- })).filter((item) => Boolean(item.url)) : [];
2024
- if (!eventDate || !sourceUrl || !evidence.some((item) => item.url === sourceUrl && item.publishedAt === eventDate)) {
2025
- throw new Error("Signals Everything response violated the dated-evidence and source-URL contract.");
2026
- }
2027
- return {
2028
- id: signal.id,
2029
- company: {
2030
- name: companyName,
2031
- domain: companyDomain,
2032
- linkedinUrl: company.linkedin_url ?? signal.company_linkedin_url ?? void 0
2033
- },
2034
- title: signal.title ?? "",
2035
- type: signal.type ?? signal.signal_type ?? "unknown",
2036
- summary: signal.summary ?? signal.content ?? signal.description ?? "",
2037
- eventDate,
2038
- evidence,
2039
- content: signal.summary ?? signal.content ?? signal.description ?? "",
2040
- date: signal.event_date ?? signal.date ?? signal.signal_date ?? null,
2041
- detectedAt: signal.event_date ?? signal.detected_at ?? null,
2042
- sourceUrl,
2043
- sourceType: signal.source_type ?? null,
2044
- confidence: signal.confidence ?? signal.confidence_score ?? null,
2045
- classification: signal.signal_classification ?? signal.classification ?? null,
2046
- 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
2047
2323
  };
2048
2324
  }
2049
2325
  function validateBatchSize(items) {
@@ -2097,9 +2373,6 @@ function normalizedBatchDomain(value) {
2097
2373
  function normalizedBatchLinkedIn(value) {
2098
2374
  return normalizedBatchText(value).replace(/\/+$/, "");
2099
2375
  }
2100
- function normalizedBatchList(value) {
2101
- return Array.isArray(value) ? value.map(normalizedBatchText).filter(Boolean).sort() : [];
2102
- }
2103
2376
  function normalizedFindEmailBatchName(request) {
2104
2377
  const fullName = normalizedBatchText(request.full_name);
2105
2378
  const componentName = [normalizedBatchText(request.first_name), normalizedBatchText(request.last_name)].filter(Boolean).join(" ");
@@ -2114,39 +2387,24 @@ function coreProductBatchRequestKey(path, request) {
2114
2387
  normalizedBatchDomain(request.company_domain),
2115
2388
  normalizedBatchLinkedIn(request.linkedin_url),
2116
2389
  normalizedBatchText(request.company_name),
2117
- request.skip_cache === true || request.bypass_cache === true,
2118
2390
  normalizedBatchIdempotencyKey(request.idempotency_key)
2119
2391
  ]);
2120
2392
  }
2121
2393
  if (path === "api/v1/verify-email") {
2122
2394
  return JSON.stringify([
2123
2395
  normalizedBatchText(request.email),
2124
- request.skip_cache === true || request.bypass_cache === true,
2125
2396
  request.skip_catch_all_verification === true,
2126
2397
  request.skip_esp_check === true,
2127
2398
  normalizedBatchIdempotencyKey(request.idempotency_key)
2128
2399
  ]);
2129
2400
  }
2130
2401
  if (path === "api/v1/company-signals") {
2131
- const online = request.online !== false;
2132
- const deepSearch = request.enable_deep_search === void 0 ? online : request.enable_deep_search !== false;
2133
2402
  return JSON.stringify([
2134
2403
  normalizedBatchText(request.signal_run_id),
2135
2404
  normalizedBatchDomain(request.company_domain || request.domain),
2136
2405
  normalizedBatchText(request.company_name),
2137
- normalizedBatchText(request.company_id),
2138
- normalizedBatchLinkedIn(request.linkedin_url),
2139
- normalizedBatchText(request.industry),
2140
2406
  typeof request.research_prompt === "string" ? request.research_prompt.trim() : "",
2141
- normalizedBatchList(request.signal_types),
2142
- Number(request.target_signal_count) || null,
2143
2407
  Number(request.lookback_days) || null,
2144
- online,
2145
- deepSearch,
2146
- normalizedBatchText(request.search_mode || "balanced"),
2147
- request.enable_outreach_intelligence === true,
2148
- request.enable_predictive_intelligence === true,
2149
- request.skip_cache === true || request.bypass_cache === true,
2150
2408
  normalizedBatchIdempotencyKey(request.idempotency_key)
2151
2409
  ]);
2152
2410
  }
@@ -2156,9 +2414,12 @@ function coreProductBatchRequestKey(path, request) {
2156
2414
  typeof request.title === "string" ? request.title.trim() : "",
2157
2415
  typeof request.campaign_offer === "string" ? request.campaign_offer.trim() : "",
2158
2416
  typeof request.research_prompt === "string" ? request.research_prompt.trim() : "",
2417
+ normalizedBatchText(request.copy_evidence_mode),
2159
2418
  Number(request.lookback_days) || null,
2160
2419
  typeof request.signal_run_id === "string" ? request.signal_run_id.trim() : "",
2161
- 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() : "",
2162
2423
  request.enable_deep_search === true,
2163
2424
  normalizedBatchIdempotencyKey(request.idempotency_key)
2164
2425
  ]);
@@ -2263,43 +2524,60 @@ function signalToCopyRequestBody(params) {
2263
2524
  person_name: params.personName,
2264
2525
  title: params.title,
2265
2526
  campaign_offer: params.campaignOffer,
2266
- research_prompt: params.researchPrompt,
2267
- lookback_days: params.lookbackDays,
2527
+ copy_evidence_mode: params.copyEvidenceMode,
2528
+ lookback_days: 365,
2268
2529
  signal_run_id: params.signalRunId,
2269
- skip_cache: params.skipCache,
2530
+ signal_search_run_id: params.signalSearchRunId,
2531
+ fact_id: params.factId,
2532
+ event_id: params.eventId,
2270
2533
  enable_deep_search: params.enableDeepSearch,
2271
2534
  max_wait_ms: params.maxWaitMs,
2272
2535
  dry_run: params.dryRun,
2273
2536
  idempotency_key: params.idempotencyKey
2274
2537
  });
2275
2538
  }
2276
- function validateLargeAvailableDataSignalCopyBatch(requests) {
2539
+ function validateLargeSignalCopyBatch(requests) {
2277
2540
  if (requests.length <= 25) return;
2278
2541
  const invalidIndex = requests.findIndex(
2279
- (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()
2280
2543
  );
2281
2544
  if (invalidIndex >= 0) {
2282
2545
  throw new RangeError(
2283
- `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.`
2284
2547
  );
2285
2548
  }
2286
2549
  }
2287
- function availableDataSignalCopyRequestBody(params) {
2550
+ function durableSignalCopyRequestBody(params) {
2288
2551
  return compact({
2289
2552
  company_domain: params.companyDomain,
2290
2553
  person_name: params.personName,
2291
2554
  title: params.title,
2292
2555
  campaign_offer: params.campaignOffer,
2293
- research_prompt: params.researchPrompt,
2294
- lookback_days: params.lookbackDays,
2295
- 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
2296
2563
  });
2297
2564
  }
2298
2565
  function validateSignalToCopyParams(params) {
2299
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
+ }
2300
2570
  if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
2301
2571
  throw new RangeError("lookbackDays must be an integer between 1 and 365");
2302
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
+ }
2303
2581
  if (typeof params.signalRunId === "string" && params.signalRunId.trim()) return;
2304
2582
  const missing = [
2305
2583
  ["companyDomain", params.companyDomain],
@@ -2318,6 +2596,7 @@ function validateCoreProductMaxWaitMs(value) {
2318
2596
  }
2319
2597
  }
2320
2598
  function normalizeSignalToCopyResult(data) {
2599
+ data = publicProductData(data, "signal_to_copy");
2321
2600
  const failed = coreProductResponseFailed(data);
2322
2601
  return {
2323
2602
  success: !failed,
@@ -2326,6 +2605,11 @@ function normalizeSignalToCopyResult(data) {
2326
2605
  status: data.status,
2327
2606
  runId: data.run_id ?? data.signal_run_id,
2328
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,
2329
2613
  resumeContextPersisted: data.resume_context_persisted,
2330
2614
  strongestSignal: failed ? "" : data.strongest_signal ?? "",
2331
2615
  whyNow: failed ? "" : data.why_now ?? "",
@@ -2334,17 +2618,11 @@ function normalizeSignalToCopyResult(data) {
2334
2618
  confidence: failed ? 0 : data.confidence ?? 0,
2335
2619
  evidenceUrl: failed ? "" : data.evidence_url ?? "",
2336
2620
  researchPrompt: data.research_prompt,
2621
+ copyEvidenceMode: data.copy_evidence_mode,
2337
2622
  empty: data.empty,
2338
2623
  emptyReason: data.empty_reason,
2339
2624
  researchMetadata: failed ? void 0 : data.research_metadata,
2340
- billingMetadata: data.billing_metadata,
2341
- resultReturnedFrom: data.result_returned_from,
2342
- cacheHit: data.cache_hit,
2343
- freshEnrichmentUsed: data.fresh_enrichment_used,
2344
2625
  creditsUsed: data.credits_used,
2345
- liveProviderCalled: data.live_provider_called,
2346
- aiProviderCalled: data.ai_provider_called,
2347
- byoAiUsed: data.byo_ai_used,
2348
2626
  unlimitedSignalToCopy: data.unlimited_signal_to_copy,
2349
2627
  signalToCopyEntitlement: data.signal_to_copy_entitlement,
2350
2628
  variations: (failed ? [] : data.variations ?? []).map((variation) => ({
@@ -2358,6 +2636,117 @@ function normalizeSignalToCopyResult(data) {
2358
2636
  raw: data
2359
2637
  };
2360
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
+ }
2361
2750
  function isPendingSignalResponse(data) {
2362
2751
  if (coreProductResponseFailed(data)) return false;
2363
2752
  return ["triggered", "queued", "processing", "pending", "pending_version", "waiting_for_deploy"].includes(String(data.status || "").toLowerCase());