@sonordev/contracts 2.25.0 → 2.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.26.0
4
+
5
+ - Add positioning previews for exact Meta, Google Search and Broadcast draft targets. Current source witnesses and an independent consistency assessment support the owner's application checks.
6
+ - Add the property-interest entry with closed event and site report contracts. Exposure-normalized action rates, missing-session events and accepted tour inquiry evidence retain separate fields. The request matcher checks the exact site, window and explicit listing set.
7
+
3
8
  ## 2.25.0
4
9
 
5
10
  - Add guided Meta dataset selection and setup contracts, including exact verified dataset readback and a shared dataset name validator.
package/README.md CHANGED
@@ -1774,6 +1774,22 @@ Use `@sonordev/contracts/resonance` to review audience setup for a saved draft b
1774
1774
  Only eligible visits from the active grant window can be considered for delivery. The native owner checks approval, current scope and consent before dispatch. The parsers validate wire shape and consistency. Campaign launch and spend require their own authorization.
1775
1775
 
1776
1776
 
1777
+ ### Positioning preview
1778
+
1779
+ Use `parseResonancePositioningPreviewRequest` to select a saved draft revision, site and exact Meta, Google Search or Broadcast target. A destination or offer can be absent while you're exploring. Applying a ready suggestion requires a current verified destination and any selected offer.
1780
+
1781
+ `parseResonancePositioningPreview` separates the buyer rationale, source references and suggested copy. A fictional bike shop might use a verified booking page to support a draft about choosing a drop-off location, while keeping its guess about walk-in demand labeled as a hypothesis. Provisional and no-fit results carry reasons and no application token.
1782
+
1783
+ `parseResonancePositioningApplyRequest` accepts the owner's application token. The owner rechecks the original scope and current evidence before updating a draft or passing the selected text to native Broadcast preparation. Publication and campaign launch follow their existing approval paths.
1784
+
1785
+ ### Property interest analytics
1786
+
1787
+ Use `@sonordev/contracts/property-interest` for property exposure and deliberate-action events. `parsePropertyInterestEvent` accepts the reserved category `real_estate_interest` and a native listing UUID, surface, and optional display ordinal. The API resolves the listing against the site's scope before admitting the event.
1788
+
1789
+ `parsePropertyInterestReportForRequest(response, request)` checks the site, time window and exact selected listing set. A broad report uses UUID pagination with at most 50 properties per page. Each property's collection and detail cohorts keep exposure sessions, eligible action sessions, unmatched action sessions and events without a session distinct. `propertyInterestRateBps` returns a rounded basis-point rate or `null` when there are no exposure sessions.
1790
+
1791
+ Accepted tour inquiries have explicit source availability. A verified zero remains different from unavailable evidence. These reports describe site activity. They establish no advertising audience, booking, qualified buyer or causal result.
1792
+
1777
1793
  ## Sales call preparation
1778
1794
 
1779
1795
  Added in 2.24.0, `@sonordev/contracts/sales-call-prep` provides pure request,
@@ -0,0 +1,100 @@
1
+ import { type Value } from './wire-schema';
2
+ export declare const PROPERTY_INTEREST_CATEGORY: 'real_estate_interest';
3
+ export declare const PROPERTY_INTEREST_EVENT_NAMES: readonly ['property_exposed', 'gallery_open', 'detail_open', 'property_selected'];
4
+ export declare const PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS = 28;
5
+ export declare const PROPERTY_INTEREST_MAX_WINDOW_DAYS = 90;
6
+ export declare const PROPERTY_INTEREST_MAX_LISTINGS = 50;
7
+ export declare class PropertyInterestValidationError extends Error {
8
+ readonly path: string;
9
+ constructor(path: string, reason: string);
10
+ }
11
+ declare const eventProperties: import("./wire-schema").Field<{
12
+ schema_version: 1;
13
+ listing_id: string;
14
+ surface: "collection" | "detail";
15
+ } & {
16
+ ordinal?: number | undefined;
17
+ }>;
18
+ declare const event: import("./wire-schema").Field<{
19
+ category: "real_estate_interest";
20
+ name: "detail_open" | "gallery_open" | "property_exposed" | "property_selected";
21
+ properties: {
22
+ schema_version: 1;
23
+ listing_id: string;
24
+ surface: "collection" | "detail";
25
+ } & {
26
+ ordinal?: number | undefined;
27
+ };
28
+ } & {}>;
29
+ export type PropertyInterestEventProperties = Value<typeof eventProperties>;
30
+ export type PropertyInterestEvent = Value<typeof event>;
31
+ export declare const parsePropertyInterestEventProperties: (value: unknown) => PropertyInterestEventProperties;
32
+ export declare const parsePropertyInterestEvent: (value: unknown) => PropertyInterestEvent;
33
+ export declare const PROPERTY_INTEREST_EVENT_PROPERTIES_JSON_SCHEMA: import("./wire-schema").JsonSchema;
34
+ export declare const PROPERTY_INTEREST_EVENT_JSON_SCHEMA: import("./wire-schema").JsonSchema;
35
+ declare const reportRequest: import("./wire-schema").Field<{
36
+ site: string;
37
+ } & {
38
+ from?: string | undefined;
39
+ to?: string | undefined;
40
+ listingIds?: string[] | undefined;
41
+ cursor?: string | undefined;
42
+ }>;
43
+ export type PropertyInterestReportRequest = Value<typeof reportRequest>;
44
+ export declare const parsePropertyInterestReportRequest: (value: unknown) => PropertyInterestReportRequest;
45
+ export declare const PROPERTY_INTEREST_REPORT_REQUEST_JSON_SCHEMA: import("./wire-schema").JsonSchema;
46
+ /** Basis points rounded to nearest, with halves rounded up. A missing denominator stays null. */
47
+ export declare function propertyInterestRateBps(eligibleSessions: number, exposureSessions: number): number | null;
48
+ declare const report: import("./wire-schema").Field<{
49
+ schemaVersion: 1;
50
+ scope: "site";
51
+ site: string;
52
+ from: string;
53
+ to: string;
54
+ observedAt: string;
55
+ properties: ({
56
+ listingId: string;
57
+ displayAddress: string | null;
58
+ slug: string | null;
59
+ status: "active" | "expired" | "pending" | "sold" | "withdrawn" | null;
60
+ surfaces: ({
61
+ surface: "collection" | "detail";
62
+ exposureSessions: number;
63
+ missingSessionEvents: number;
64
+ actions: {
65
+ gallery_open: {
66
+ eligibleSessions: number;
67
+ unmatchedSessions: number;
68
+ rateBps: number | null;
69
+ } & {};
70
+ detail_open: {
71
+ eligibleSessions: number;
72
+ unmatchedSessions: number;
73
+ rateBps: number | null;
74
+ } & {};
75
+ property_selected: {
76
+ eligibleSessions: number;
77
+ unmatchedSessions: number;
78
+ rateBps: number | null;
79
+ } & {};
80
+ } & {};
81
+ } & {})[];
82
+ acceptedTourInquiries: ({
83
+ state: "available";
84
+ count: number;
85
+ source: "native_listing_accepted_tour_form";
86
+ } & {}) | ({
87
+ state: "unavailable";
88
+ count: null;
89
+ source: null;
90
+ } & {});
91
+ } & {})[];
92
+ hasMore: boolean;
93
+ nextCursor: string | null;
94
+ } & {}>;
95
+ export type PropertyInterestReport = Value<typeof report>;
96
+ export declare const parsePropertyInterestReport: (value: unknown) => PropertyInterestReport;
97
+ export declare const PROPERTY_INTEREST_REPORT_JSON_SCHEMA: import("./wire-schema").JsonSchema;
98
+ /** Binds a closed response to its query. The native owner still authenticates site and listing scope. */
99
+ export declare function parsePropertyInterestReportForRequest(value: unknown, request: unknown): PropertyInterestReport;
100
+ export {};
@@ -0,0 +1,261 @@
1
+ 'use strict';
2
+
3
+ // src/contracts/public-url-host.ts
4
+ function isPrivateIpv4(a, b) {
5
+ return a === 127 || a === 10 || a === 0 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127 || a >= 224;
6
+ }
7
+ function ipv6Words(host) {
8
+ if (!host.includes(":") || !/^[a-f\d:.]+$/.test(host)) return null;
9
+ let canonical;
10
+ try {
11
+ canonical = new URL(`http://[${host}]/`).hostname.slice(1, -1);
12
+ } catch {
13
+ return null;
14
+ }
15
+ const sides = canonical.split("::");
16
+ const left = sides[0] ? sides[0].split(":") : [];
17
+ const right = sides.length > 1 && sides[1] ? sides[1].split(":") : [];
18
+ return [...left, ...Array(sides.length > 1 ? 8 - left.length - right.length : 0).fill("0"), ...right].map((word) => parseInt(word, 16));
19
+ }
20
+ function isBlockedPublicUrlHost(rawHost) {
21
+ const host = rawHost.toLowerCase().replace(/^\[|\]$/g, "");
22
+ const blockedName = host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
23
+ if (host.includes(":") && host.includes("%")) return true;
24
+ const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
25
+ const blockedIp = !!ipv4 && isPrivateIpv4(Number(ipv4[1]), Number(ipv4[2]));
26
+ const words = ipv6Words(host);
27
+ const blockedIpv6 = !!words && // Unspecified/loopback, unique-local, link-local, deprecated site-local
28
+ // and multicast destinations aren't public logo/webhook endpoints.
29
+ (words.every((word) => word === 0) || words.slice(0, 7).every((word) => word === 0) && words[7] === 1 || (words[0] & 65024) === 64512 || (words[0] & 65472) === 65152 || (words[0] & 65472) === 65216 || (words[0] & 65280) === 65280 || // IPv4-mapped and older IPv4-compatible forms carry an IPv4 destination.
30
+ words.slice(0, 5).every((word) => word === 0) && [0, 65535].includes(words[5]) && isPrivateIpv4(words[6] >> 8, words[6] & 255));
31
+ return blockedName || blockedIp || blockedIpv6;
32
+ }
33
+
34
+ // src/contracts/sites-normalize.ts
35
+ function normalizeSiteHost(site2) {
36
+ if (!site2 || typeof site2 !== "string") return null;
37
+ let s = site2.trim().toLowerCase();
38
+ if (!s) return null;
39
+ s = s.replace(/^https?:\/\//, "");
40
+ const slash = s.indexOf("/");
41
+ if (slash >= 0) s = s.slice(0, slash);
42
+ const colon = s.indexOf(":");
43
+ if (colon >= 0) s = s.slice(0, colon);
44
+ s = s.replace(/\.+$/, "");
45
+ return s || null;
46
+ }
47
+
48
+ // src/contracts/sites.ts
49
+ function isNormalizedSiteHost(value) {
50
+ return typeof value === "string" && value.length > 0 && normalizeSiteHost(value) === value;
51
+ }
52
+
53
+ // src/contracts/wire-schema.ts
54
+ function createWireSchema(fail2, isValidationError) {
55
+ const own = (v, k) => Object.prototype.hasOwnProperty.call(v, k);
56
+ const field = (schema, read) => ({ schema, read });
57
+ const text2 = (max = 200, pattern, min = 1) => field({ type: "string", minLength: min, maxLength: max, ...pattern ? { pattern: pattern.source } : {} }, (v, p) => typeof v === "string" && v.length >= min && v.length <= max && (!pattern || pattern.test(v)) ? v : fail2(p, "invalid string"));
58
+ const choice2 = (...values) => field({ type: "string", enum: values }, (v, p) => typeof v === "string" && values.includes(v) ? v : fail2(p, "unsupported value"));
59
+ const literal2 = (value) => field({ const: value }, (v, p) => v === value ? value : fail2(p, "unexpected value"));
60
+ const integer2 = (min = 0, max = Number.MAX_SAFE_INTEGER) => field({ type: "integer", minimum: min, maximum: max }, (v, p) => typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max ? v : fail2(p, "invalid integer"));
61
+ const bool2 = field({ type: "boolean" }, (v, p) => typeof v === "boolean" ? v : fail2(p, "must be boolean"));
62
+ const optional2 = (f) => ({ ...f, optional: true });
63
+ const nullable2 = (f) => field({ anyOf: [f.schema, { type: "null" }] }, (v, p) => v === null ? null : f.read(v, p));
64
+ const list2 = (f, max = 100, min = 0) => field({ type: "array", items: f.schema, minItems: min, maxItems: max }, (v, p) => {
65
+ if (!Array.isArray(v) || v.length < min || v.length > max) fail2(p, "invalid array");
66
+ return v.map((x, i) => f.read(x, `${p}[${i}]`));
67
+ });
68
+ const object2 = (fields) => field({ type: "object", additionalProperties: false, properties: Object.fromEntries(Object.entries(fields).map(([k, f]) => [k, f.schema])), required: Object.keys(fields).filter((k) => !("optional" in fields[k])) }, (v, p) => {
69
+ if (!v || typeof v !== "object" || Array.isArray(v) || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) fail2(p, "must be a plain object");
70
+ const source = v, result = {};
71
+ for (const key of Reflect.ownKeys(source)) if (typeof key !== "string" || !own(fields, key)) fail2(p, "unknown field");
72
+ for (const [key, f] of Object.entries(fields)) {
73
+ if (!own(source, key)) {
74
+ if ("optional" in f) continue;
75
+ fail2(`${p}.${key}`, "required");
76
+ }
77
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
78
+ if (!own(descriptor, "value")) fail2(`${p}.${key}`, "accessors are not wire data");
79
+ result[key] = f.read(descriptor.value, `${p}.${key}`);
80
+ }
81
+ return result;
82
+ });
83
+ const union2 = (...fields) => field({ oneOf: fields.map((f) => f.schema) }, (v, p) => {
84
+ const found = [];
85
+ for (const f of fields) {
86
+ try {
87
+ found.push(f.read(v, p));
88
+ } catch (e) {
89
+ if (!isValidationError(e)) throw e;
90
+ }
91
+ }
92
+ return found.length === 1 ? found[0] : fail2(p, "must match exactly one supported shape");
93
+ });
94
+ const refine2 = (f, check) => field(f.schema, (v, p) => {
95
+ const result = f.read(v, p);
96
+ check(result, p);
97
+ return result;
98
+ });
99
+ return { field, text: text2, choice: choice2, literal: literal2, integer: integer2, bool: bool2, optional: optional2, nullable: nullable2, list: list2, object: object2, union: union2, refine: refine2 };
100
+ }
101
+
102
+ // src/contracts/wire-uuid.ts
103
+ var UUID_V1_TO_V8_PATTERN = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
104
+
105
+ // src/contracts/property-interest.ts
106
+ var PROPERTY_INTEREST_CATEGORY = "real_estate_interest";
107
+ var PROPERTY_INTEREST_EVENT_NAMES = ["property_exposed", "gallery_open", "detail_open", "property_selected"];
108
+ var PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS = 28;
109
+ var PROPERTY_INTEREST_MAX_WINDOW_DAYS = 90;
110
+ var PROPERTY_INTEREST_MAX_LISTINGS = 50;
111
+ var PropertyInterestValidationError = class extends Error {
112
+ constructor(path, reason) {
113
+ super(`${path}: ${reason}`);
114
+ this.path = path;
115
+ this.name = "PropertyInterestValidationError";
116
+ }
117
+ };
118
+ var fail = (path, reason) => {
119
+ throw new PropertyInterestValidationError(path, reason);
120
+ };
121
+ var { bool, choice, integer, list, literal, nullable, object, optional, refine, text, union } = createWireSchema(fail, (error) => error instanceof PropertyInterestValidationError);
122
+ var listingId = text(36, UUID_V1_TO_V8_PATTERN);
123
+ var surface = choice("collection", "detail");
124
+ var site = refine(text(253), (value, at) => {
125
+ if (!isNormalizedSiteHost(value) || isBlockedPublicUrlHost(value)) fail(at, "requires a normalized public site host");
126
+ });
127
+ var instant = refine(text(24, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/), (value, at) => {
128
+ const epoch = Date.parse(value);
129
+ if (!Number.isFinite(epoch) || new Date(epoch).toISOString().replace(".000Z", "Z") !== value.replace(".000Z", "Z")) {
130
+ fail(at, "requires a valid UTC instant");
131
+ }
132
+ });
133
+ var dayMs = 864e5;
134
+ var eventProperties = object({
135
+ schema_version: literal(1),
136
+ listing_id: listingId,
137
+ surface,
138
+ ordinal: optional(integer(1, 1e3))
139
+ });
140
+ var event = object({ category: literal(PROPERTY_INTEREST_CATEGORY), name: choice(...PROPERTY_INTEREST_EVENT_NAMES), properties: eventProperties });
141
+ var parsePropertyInterestEventProperties = (value) => eventProperties.read(value, "propertyInterestEventProperties");
142
+ var parsePropertyInterestEvent = (value) => event.read(value, "propertyInterestEvent");
143
+ var PROPERTY_INTEREST_EVENT_PROPERTIES_JSON_SCHEMA = eventProperties.schema;
144
+ var PROPERTY_INTEREST_EVENT_JSON_SCHEMA = event.schema;
145
+ function checkWindow(from, to, at) {
146
+ const duration = Date.parse(to) - Date.parse(from);
147
+ if (duration <= 0 || duration > PROPERTY_INTEREST_MAX_WINDOW_DAYS * dayMs) fail(at, "requires a positive window of at most 90 days");
148
+ }
149
+ function unique(values, at) {
150
+ if (new Set(values).size !== values.length) fail(at, "duplicate identity");
151
+ }
152
+ var reportRequest = refine(object({
153
+ site,
154
+ from: optional(instant),
155
+ to: optional(instant),
156
+ listingIds: optional(list(listingId, PROPERTY_INTEREST_MAX_LISTINGS, 1)),
157
+ cursor: optional(listingId)
158
+ }), (value, at) => {
159
+ if (value.from && value.to) checkWindow(value.from, value.to, at);
160
+ else if (value.from || value.to) fail(at, "requires both window endpoints or neither");
161
+ if (value.listingIds) unique(value.listingIds.map((id) => id.toLowerCase()), at + ".listingIds");
162
+ if (value.cursor && (!value.from || !value.to || value.listingIds)) {
163
+ fail(at + ".cursor", "requires the original broad report window");
164
+ }
165
+ });
166
+ var parsePropertyInterestReportRequest = (value) => reportRequest.read(value, "propertyInterestReportRequest");
167
+ var PROPERTY_INTEREST_REPORT_REQUEST_JSON_SCHEMA = reportRequest.schema;
168
+ function propertyInterestRateBps(eligibleSessions, exposureSessions) {
169
+ const eligible = integer().read(eligibleSessions, "propertyInterestRate.eligibleSessions");
170
+ const exposure = integer().read(exposureSessions, "propertyInterestRate.exposureSessions");
171
+ if (eligible > exposure) fail("propertyInterestRate", "eligible sessions exceed the exposure cohort");
172
+ if (exposure === 0) return null;
173
+ const denominator = BigInt(exposure);
174
+ return Number((BigInt(eligible) * 10000n + denominator / 2n) / denominator);
175
+ }
176
+ var action = object({ eligibleSessions: integer(), unmatchedSessions: integer(), rateBps: nullable(integer(0, 1e4)) });
177
+ var surfaceReport = refine(object({
178
+ surface,
179
+ exposureSessions: integer(),
180
+ missingSessionEvents: integer(),
181
+ actions: object({ gallery_open: action, detail_open: action, property_selected: action })
182
+ }), (value, at) => {
183
+ for (const [name, counts] of Object.entries(value.actions)) {
184
+ if (counts.eligibleSessions > value.exposureSessions || counts.rateBps !== propertyInterestRateBps(counts.eligibleSessions, value.exposureSessions)) {
185
+ fail(at + ".actions." + name, "requires the exact exposure-normalized rate");
186
+ }
187
+ }
188
+ });
189
+ var tourInquiries = union(
190
+ object({ state: literal("available"), count: integer(), source: literal("native_listing_accepted_tour_form") }),
191
+ object({ state: literal("unavailable"), count: literal(null), source: literal(null) })
192
+ );
193
+ var propertyReport = refine(object({
194
+ listingId,
195
+ displayAddress: nullable(text(240, /^[^\x00-\x1f\x7f]+$/)),
196
+ slug: nullable(text(200, /^[a-z0-9]+(?:-[a-z0-9]+)*$/)),
197
+ status: nullable(choice("active", "pending", "sold", "expired", "withdrawn")),
198
+ surfaces: list(surfaceReport, 2, 2),
199
+ acceptedTourInquiries: tourInquiries
200
+ }), (value, at) => {
201
+ unique(value.surfaces.map((row) => row.surface), at + ".surfaces");
202
+ });
203
+ var report = refine(object({
204
+ schemaVersion: literal(1),
205
+ scope: literal("site"),
206
+ site,
207
+ from: instant,
208
+ to: instant,
209
+ observedAt: instant,
210
+ properties: list(propertyReport, PROPERTY_INTEREST_MAX_LISTINGS),
211
+ hasMore: bool,
212
+ nextCursor: nullable(listingId)
213
+ }), (value, at) => {
214
+ checkWindow(value.from, value.to, at);
215
+ if (Date.parse(value.to) > Date.parse(value.observedAt)) fail(at + ".to", "window extends past the observation");
216
+ unique(value.properties.map((row) => row.listingId.toLowerCase()), at + ".properties");
217
+ if (value.hasMore !== (value.nextCursor !== null)) fail(at + ".hasMore", "must agree with the next cursor");
218
+ if (value.nextCursor && (value.properties.length !== PROPERTY_INTEREST_MAX_LISTINGS || value.properties[value.properties.length - 1]?.listingId.toLowerCase() !== value.nextCursor.toLowerCase())) {
219
+ fail(at + ".nextCursor", "requires the final listing of a full bounded result");
220
+ }
221
+ });
222
+ var parsePropertyInterestReport = (value) => report.read(value, "propertyInterestReport");
223
+ var PROPERTY_INTEREST_REPORT_JSON_SCHEMA = report.schema;
224
+ function parsePropertyInterestReportForRequest(value, request) {
225
+ const result = parsePropertyInterestReport(value);
226
+ const expected = parsePropertyInterestReportRequest(request);
227
+ const at = "propertyInterestReport";
228
+ if (result.site !== expected.site) fail(at + ".site", "does not match the requested site");
229
+ const from = Date.parse(result.from), to = Date.parse(result.to);
230
+ if (expected.from && expected.to) {
231
+ if (from !== Date.parse(expected.from) || to !== Date.parse(expected.to)) {
232
+ fail(at + ".from", "does not match the requested window");
233
+ }
234
+ } else if (to - from !== PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS * dayMs) {
235
+ fail(at + ".from", "does not match the default window duration");
236
+ }
237
+ if (expected.listingIds) {
238
+ const requestedIds = new Set(expected.listingIds.map((id) => id.toLowerCase()));
239
+ if (result.hasMore || result.properties.length !== requestedIds.size || result.properties.some((row) => !requestedIds.has(row.listingId.toLowerCase()))) {
240
+ fail(at + ".properties", "requires exactly the requested listings without pagination");
241
+ }
242
+ }
243
+ return result;
244
+ }
245
+
246
+ exports.PROPERTY_INTEREST_CATEGORY = PROPERTY_INTEREST_CATEGORY;
247
+ exports.PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS = PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS;
248
+ exports.PROPERTY_INTEREST_EVENT_JSON_SCHEMA = PROPERTY_INTEREST_EVENT_JSON_SCHEMA;
249
+ exports.PROPERTY_INTEREST_EVENT_NAMES = PROPERTY_INTEREST_EVENT_NAMES;
250
+ exports.PROPERTY_INTEREST_EVENT_PROPERTIES_JSON_SCHEMA = PROPERTY_INTEREST_EVENT_PROPERTIES_JSON_SCHEMA;
251
+ exports.PROPERTY_INTEREST_MAX_LISTINGS = PROPERTY_INTEREST_MAX_LISTINGS;
252
+ exports.PROPERTY_INTEREST_MAX_WINDOW_DAYS = PROPERTY_INTEREST_MAX_WINDOW_DAYS;
253
+ exports.PROPERTY_INTEREST_REPORT_JSON_SCHEMA = PROPERTY_INTEREST_REPORT_JSON_SCHEMA;
254
+ exports.PROPERTY_INTEREST_REPORT_REQUEST_JSON_SCHEMA = PROPERTY_INTEREST_REPORT_REQUEST_JSON_SCHEMA;
255
+ exports.PropertyInterestValidationError = PropertyInterestValidationError;
256
+ exports.parsePropertyInterestEvent = parsePropertyInterestEvent;
257
+ exports.parsePropertyInterestEventProperties = parsePropertyInterestEventProperties;
258
+ exports.parsePropertyInterestReport = parsePropertyInterestReport;
259
+ exports.parsePropertyInterestReportForRequest = parsePropertyInterestReportForRequest;
260
+ exports.parsePropertyInterestReportRequest = parsePropertyInterestReportRequest;
261
+ exports.propertyInterestRateBps = propertyInterestRateBps;
@@ -0,0 +1,244 @@
1
+ // src/contracts/public-url-host.ts
2
+ function isPrivateIpv4(a, b) {
3
+ return a === 127 || a === 10 || a === 0 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127 || a >= 224;
4
+ }
5
+ function ipv6Words(host) {
6
+ if (!host.includes(":") || !/^[a-f\d:.]+$/.test(host)) return null;
7
+ let canonical;
8
+ try {
9
+ canonical = new URL(`http://[${host}]/`).hostname.slice(1, -1);
10
+ } catch {
11
+ return null;
12
+ }
13
+ const sides = canonical.split("::");
14
+ const left = sides[0] ? sides[0].split(":") : [];
15
+ const right = sides.length > 1 && sides[1] ? sides[1].split(":") : [];
16
+ return [...left, ...Array(sides.length > 1 ? 8 - left.length - right.length : 0).fill("0"), ...right].map((word) => parseInt(word, 16));
17
+ }
18
+ function isBlockedPublicUrlHost(rawHost) {
19
+ const host = rawHost.toLowerCase().replace(/^\[|\]$/g, "");
20
+ const blockedName = host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
21
+ if (host.includes(":") && host.includes("%")) return true;
22
+ const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
23
+ const blockedIp = !!ipv4 && isPrivateIpv4(Number(ipv4[1]), Number(ipv4[2]));
24
+ const words = ipv6Words(host);
25
+ const blockedIpv6 = !!words && // Unspecified/loopback, unique-local, link-local, deprecated site-local
26
+ // and multicast destinations aren't public logo/webhook endpoints.
27
+ (words.every((word) => word === 0) || words.slice(0, 7).every((word) => word === 0) && words[7] === 1 || (words[0] & 65024) === 64512 || (words[0] & 65472) === 65152 || (words[0] & 65472) === 65216 || (words[0] & 65280) === 65280 || // IPv4-mapped and older IPv4-compatible forms carry an IPv4 destination.
28
+ words.slice(0, 5).every((word) => word === 0) && [0, 65535].includes(words[5]) && isPrivateIpv4(words[6] >> 8, words[6] & 255));
29
+ return blockedName || blockedIp || blockedIpv6;
30
+ }
31
+
32
+ // src/contracts/sites-normalize.ts
33
+ function normalizeSiteHost(site2) {
34
+ if (!site2 || typeof site2 !== "string") return null;
35
+ let s = site2.trim().toLowerCase();
36
+ if (!s) return null;
37
+ s = s.replace(/^https?:\/\//, "");
38
+ const slash = s.indexOf("/");
39
+ if (slash >= 0) s = s.slice(0, slash);
40
+ const colon = s.indexOf(":");
41
+ if (colon >= 0) s = s.slice(0, colon);
42
+ s = s.replace(/\.+$/, "");
43
+ return s || null;
44
+ }
45
+
46
+ // src/contracts/sites.ts
47
+ function isNormalizedSiteHost(value) {
48
+ return typeof value === "string" && value.length > 0 && normalizeSiteHost(value) === value;
49
+ }
50
+
51
+ // src/contracts/wire-schema.ts
52
+ function createWireSchema(fail2, isValidationError) {
53
+ const own = (v, k) => Object.prototype.hasOwnProperty.call(v, k);
54
+ const field = (schema, read) => ({ schema, read });
55
+ const text2 = (max = 200, pattern, min = 1) => field({ type: "string", minLength: min, maxLength: max, ...pattern ? { pattern: pattern.source } : {} }, (v, p) => typeof v === "string" && v.length >= min && v.length <= max && (!pattern || pattern.test(v)) ? v : fail2(p, "invalid string"));
56
+ const choice2 = (...values) => field({ type: "string", enum: values }, (v, p) => typeof v === "string" && values.includes(v) ? v : fail2(p, "unsupported value"));
57
+ const literal2 = (value) => field({ const: value }, (v, p) => v === value ? value : fail2(p, "unexpected value"));
58
+ const integer2 = (min = 0, max = Number.MAX_SAFE_INTEGER) => field({ type: "integer", minimum: min, maximum: max }, (v, p) => typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max ? v : fail2(p, "invalid integer"));
59
+ const bool2 = field({ type: "boolean" }, (v, p) => typeof v === "boolean" ? v : fail2(p, "must be boolean"));
60
+ const optional2 = (f) => ({ ...f, optional: true });
61
+ const nullable2 = (f) => field({ anyOf: [f.schema, { type: "null" }] }, (v, p) => v === null ? null : f.read(v, p));
62
+ const list2 = (f, max = 100, min = 0) => field({ type: "array", items: f.schema, minItems: min, maxItems: max }, (v, p) => {
63
+ if (!Array.isArray(v) || v.length < min || v.length > max) fail2(p, "invalid array");
64
+ return v.map((x, i) => f.read(x, `${p}[${i}]`));
65
+ });
66
+ const object2 = (fields) => field({ type: "object", additionalProperties: false, properties: Object.fromEntries(Object.entries(fields).map(([k, f]) => [k, f.schema])), required: Object.keys(fields).filter((k) => !("optional" in fields[k])) }, (v, p) => {
67
+ if (!v || typeof v !== "object" || Array.isArray(v) || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) fail2(p, "must be a plain object");
68
+ const source = v, result = {};
69
+ for (const key of Reflect.ownKeys(source)) if (typeof key !== "string" || !own(fields, key)) fail2(p, "unknown field");
70
+ for (const [key, f] of Object.entries(fields)) {
71
+ if (!own(source, key)) {
72
+ if ("optional" in f) continue;
73
+ fail2(`${p}.${key}`, "required");
74
+ }
75
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
76
+ if (!own(descriptor, "value")) fail2(`${p}.${key}`, "accessors are not wire data");
77
+ result[key] = f.read(descriptor.value, `${p}.${key}`);
78
+ }
79
+ return result;
80
+ });
81
+ const union2 = (...fields) => field({ oneOf: fields.map((f) => f.schema) }, (v, p) => {
82
+ const found = [];
83
+ for (const f of fields) {
84
+ try {
85
+ found.push(f.read(v, p));
86
+ } catch (e) {
87
+ if (!isValidationError(e)) throw e;
88
+ }
89
+ }
90
+ return found.length === 1 ? found[0] : fail2(p, "must match exactly one supported shape");
91
+ });
92
+ const refine2 = (f, check) => field(f.schema, (v, p) => {
93
+ const result = f.read(v, p);
94
+ check(result, p);
95
+ return result;
96
+ });
97
+ return { field, text: text2, choice: choice2, literal: literal2, integer: integer2, bool: bool2, optional: optional2, nullable: nullable2, list: list2, object: object2, union: union2, refine: refine2 };
98
+ }
99
+
100
+ // src/contracts/wire-uuid.ts
101
+ var UUID_V1_TO_V8_PATTERN = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
102
+
103
+ // src/contracts/property-interest.ts
104
+ var PROPERTY_INTEREST_CATEGORY = "real_estate_interest";
105
+ var PROPERTY_INTEREST_EVENT_NAMES = ["property_exposed", "gallery_open", "detail_open", "property_selected"];
106
+ var PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS = 28;
107
+ var PROPERTY_INTEREST_MAX_WINDOW_DAYS = 90;
108
+ var PROPERTY_INTEREST_MAX_LISTINGS = 50;
109
+ var PropertyInterestValidationError = class extends Error {
110
+ constructor(path, reason) {
111
+ super(`${path}: ${reason}`);
112
+ this.path = path;
113
+ this.name = "PropertyInterestValidationError";
114
+ }
115
+ };
116
+ var fail = (path, reason) => {
117
+ throw new PropertyInterestValidationError(path, reason);
118
+ };
119
+ var { bool, choice, integer, list, literal, nullable, object, optional, refine, text, union } = createWireSchema(fail, (error) => error instanceof PropertyInterestValidationError);
120
+ var listingId = text(36, UUID_V1_TO_V8_PATTERN);
121
+ var surface = choice("collection", "detail");
122
+ var site = refine(text(253), (value, at) => {
123
+ if (!isNormalizedSiteHost(value) || isBlockedPublicUrlHost(value)) fail(at, "requires a normalized public site host");
124
+ });
125
+ var instant = refine(text(24, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/), (value, at) => {
126
+ const epoch = Date.parse(value);
127
+ if (!Number.isFinite(epoch) || new Date(epoch).toISOString().replace(".000Z", "Z") !== value.replace(".000Z", "Z")) {
128
+ fail(at, "requires a valid UTC instant");
129
+ }
130
+ });
131
+ var dayMs = 864e5;
132
+ var eventProperties = object({
133
+ schema_version: literal(1),
134
+ listing_id: listingId,
135
+ surface,
136
+ ordinal: optional(integer(1, 1e3))
137
+ });
138
+ var event = object({ category: literal(PROPERTY_INTEREST_CATEGORY), name: choice(...PROPERTY_INTEREST_EVENT_NAMES), properties: eventProperties });
139
+ var parsePropertyInterestEventProperties = (value) => eventProperties.read(value, "propertyInterestEventProperties");
140
+ var parsePropertyInterestEvent = (value) => event.read(value, "propertyInterestEvent");
141
+ var PROPERTY_INTEREST_EVENT_PROPERTIES_JSON_SCHEMA = eventProperties.schema;
142
+ var PROPERTY_INTEREST_EVENT_JSON_SCHEMA = event.schema;
143
+ function checkWindow(from, to, at) {
144
+ const duration = Date.parse(to) - Date.parse(from);
145
+ if (duration <= 0 || duration > PROPERTY_INTEREST_MAX_WINDOW_DAYS * dayMs) fail(at, "requires a positive window of at most 90 days");
146
+ }
147
+ function unique(values, at) {
148
+ if (new Set(values).size !== values.length) fail(at, "duplicate identity");
149
+ }
150
+ var reportRequest = refine(object({
151
+ site,
152
+ from: optional(instant),
153
+ to: optional(instant),
154
+ listingIds: optional(list(listingId, PROPERTY_INTEREST_MAX_LISTINGS, 1)),
155
+ cursor: optional(listingId)
156
+ }), (value, at) => {
157
+ if (value.from && value.to) checkWindow(value.from, value.to, at);
158
+ else if (value.from || value.to) fail(at, "requires both window endpoints or neither");
159
+ if (value.listingIds) unique(value.listingIds.map((id) => id.toLowerCase()), at + ".listingIds");
160
+ if (value.cursor && (!value.from || !value.to || value.listingIds)) {
161
+ fail(at + ".cursor", "requires the original broad report window");
162
+ }
163
+ });
164
+ var parsePropertyInterestReportRequest = (value) => reportRequest.read(value, "propertyInterestReportRequest");
165
+ var PROPERTY_INTEREST_REPORT_REQUEST_JSON_SCHEMA = reportRequest.schema;
166
+ function propertyInterestRateBps(eligibleSessions, exposureSessions) {
167
+ const eligible = integer().read(eligibleSessions, "propertyInterestRate.eligibleSessions");
168
+ const exposure = integer().read(exposureSessions, "propertyInterestRate.exposureSessions");
169
+ if (eligible > exposure) fail("propertyInterestRate", "eligible sessions exceed the exposure cohort");
170
+ if (exposure === 0) return null;
171
+ const denominator = BigInt(exposure);
172
+ return Number((BigInt(eligible) * 10000n + denominator / 2n) / denominator);
173
+ }
174
+ var action = object({ eligibleSessions: integer(), unmatchedSessions: integer(), rateBps: nullable(integer(0, 1e4)) });
175
+ var surfaceReport = refine(object({
176
+ surface,
177
+ exposureSessions: integer(),
178
+ missingSessionEvents: integer(),
179
+ actions: object({ gallery_open: action, detail_open: action, property_selected: action })
180
+ }), (value, at) => {
181
+ for (const [name, counts] of Object.entries(value.actions)) {
182
+ if (counts.eligibleSessions > value.exposureSessions || counts.rateBps !== propertyInterestRateBps(counts.eligibleSessions, value.exposureSessions)) {
183
+ fail(at + ".actions." + name, "requires the exact exposure-normalized rate");
184
+ }
185
+ }
186
+ });
187
+ var tourInquiries = union(
188
+ object({ state: literal("available"), count: integer(), source: literal("native_listing_accepted_tour_form") }),
189
+ object({ state: literal("unavailable"), count: literal(null), source: literal(null) })
190
+ );
191
+ var propertyReport = refine(object({
192
+ listingId,
193
+ displayAddress: nullable(text(240, /^[^\x00-\x1f\x7f]+$/)),
194
+ slug: nullable(text(200, /^[a-z0-9]+(?:-[a-z0-9]+)*$/)),
195
+ status: nullable(choice("active", "pending", "sold", "expired", "withdrawn")),
196
+ surfaces: list(surfaceReport, 2, 2),
197
+ acceptedTourInquiries: tourInquiries
198
+ }), (value, at) => {
199
+ unique(value.surfaces.map((row) => row.surface), at + ".surfaces");
200
+ });
201
+ var report = refine(object({
202
+ schemaVersion: literal(1),
203
+ scope: literal("site"),
204
+ site,
205
+ from: instant,
206
+ to: instant,
207
+ observedAt: instant,
208
+ properties: list(propertyReport, PROPERTY_INTEREST_MAX_LISTINGS),
209
+ hasMore: bool,
210
+ nextCursor: nullable(listingId)
211
+ }), (value, at) => {
212
+ checkWindow(value.from, value.to, at);
213
+ if (Date.parse(value.to) > Date.parse(value.observedAt)) fail(at + ".to", "window extends past the observation");
214
+ unique(value.properties.map((row) => row.listingId.toLowerCase()), at + ".properties");
215
+ if (value.hasMore !== (value.nextCursor !== null)) fail(at + ".hasMore", "must agree with the next cursor");
216
+ if (value.nextCursor && (value.properties.length !== PROPERTY_INTEREST_MAX_LISTINGS || value.properties[value.properties.length - 1]?.listingId.toLowerCase() !== value.nextCursor.toLowerCase())) {
217
+ fail(at + ".nextCursor", "requires the final listing of a full bounded result");
218
+ }
219
+ });
220
+ var parsePropertyInterestReport = (value) => report.read(value, "propertyInterestReport");
221
+ var PROPERTY_INTEREST_REPORT_JSON_SCHEMA = report.schema;
222
+ function parsePropertyInterestReportForRequest(value, request) {
223
+ const result = parsePropertyInterestReport(value);
224
+ const expected = parsePropertyInterestReportRequest(request);
225
+ const at = "propertyInterestReport";
226
+ if (result.site !== expected.site) fail(at + ".site", "does not match the requested site");
227
+ const from = Date.parse(result.from), to = Date.parse(result.to);
228
+ if (expected.from && expected.to) {
229
+ if (from !== Date.parse(expected.from) || to !== Date.parse(expected.to)) {
230
+ fail(at + ".from", "does not match the requested window");
231
+ }
232
+ } else if (to - from !== PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS * dayMs) {
233
+ fail(at + ".from", "does not match the default window duration");
234
+ }
235
+ if (expected.listingIds) {
236
+ const requestedIds = new Set(expected.listingIds.map((id) => id.toLowerCase()));
237
+ if (result.hasMore || result.properties.length !== requestedIds.size || result.properties.some((row) => !requestedIds.has(row.listingId.toLowerCase()))) {
238
+ fail(at + ".properties", "requires exactly the requested listings without pagination");
239
+ }
240
+ }
241
+ return result;
242
+ }
243
+
244
+ export { PROPERTY_INTEREST_CATEGORY, PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS, PROPERTY_INTEREST_EVENT_JSON_SCHEMA, PROPERTY_INTEREST_EVENT_NAMES, PROPERTY_INTEREST_EVENT_PROPERTIES_JSON_SCHEMA, PROPERTY_INTEREST_MAX_LISTINGS, PROPERTY_INTEREST_MAX_WINDOW_DAYS, PROPERTY_INTEREST_REPORT_JSON_SCHEMA, PROPERTY_INTEREST_REPORT_REQUEST_JSON_SCHEMA, PropertyInterestValidationError, parsePropertyInterestEvent, parsePropertyInterestEventProperties, parsePropertyInterestReport, parsePropertyInterestReportForRequest, parsePropertyInterestReportRequest, propertyInterestRateBps };