@rudra-js/core 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +58 -42
  2. package/dist/claim-screening.d.ts.map +1 -1
  3. package/dist/claim-screening.js +3 -9
  4. package/dist/claim-screening.js.map +1 -1
  5. package/dist/component-generator.d.ts +1 -1
  6. package/dist/component-generator.d.ts.map +1 -1
  7. package/dist/component-generator.js +28 -61
  8. package/dist/component-generator.js.map +1 -1
  9. package/dist/component-spec.d.ts +100 -11
  10. package/dist/component-spec.d.ts.map +1 -1
  11. package/dist/component-spec.js +3 -6
  12. package/dist/component-spec.js.map +1 -1
  13. package/dist/fallback-component.d.ts.map +1 -1
  14. package/dist/fallback-component.js +3 -3
  15. package/dist/fallback-component.js.map +1 -1
  16. package/dist/fit-to-shopper.d.ts +4 -1
  17. package/dist/fit-to-shopper.d.ts.map +1 -1
  18. package/dist/fit-to-shopper.js +8 -0
  19. package/dist/fit-to-shopper.js.map +1 -1
  20. package/dist/index.d.ts +2 -2
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/model-prompt.d.ts.map +1 -1
  25. package/dist/model-prompt.js +16 -3
  26. package/dist/model-prompt.js.map +1 -1
  27. package/dist/product-display.d.ts +6 -0
  28. package/dist/product-display.d.ts.map +1 -0
  29. package/dist/product-display.js +32 -0
  30. package/dist/product-display.js.map +1 -0
  31. package/dist/reconciliation.d.ts +2 -4
  32. package/dist/reconciliation.d.ts.map +1 -1
  33. package/dist/reconciliation.js +15 -21
  34. package/dist/reconciliation.js.map +1 -1
  35. package/dist/schemas.d.ts +1 -0
  36. package/dist/schemas.d.ts.map +1 -1
  37. package/dist/schemas.js +1 -0
  38. package/dist/schemas.js.map +1 -1
  39. package/dist/signal-digest.d.ts.map +1 -1
  40. package/dist/signal-digest.js +2 -10
  41. package/dist/signal-digest.js.map +1 -1
  42. package/dist/spec-cache.d.ts +86 -7
  43. package/dist/spec-cache.d.ts.map +1 -1
  44. package/dist/spec-cache.js +14 -32
  45. package/dist/spec-cache.js.map +1 -1
  46. package/dist/tracking-input.d.ts.map +1 -1
  47. package/dist/tracking-input.js +8 -2
  48. package/dist/tracking-input.js.map +1 -1
  49. package/package.json +5 -4
  50. package/schemas/package.json +4 -0
  51. package/src/claim-screening.ts +3 -9
  52. package/src/component-generator.ts +33 -82
  53. package/src/component-spec.ts +5 -18
  54. package/src/fallback-component.ts +4 -3
  55. package/src/fit-to-shopper.ts +16 -1
  56. package/src/index.ts +1 -2
  57. package/src/model-prompt.ts +24 -3
  58. package/src/product-display.ts +43 -0
  59. package/src/reconciliation.ts +16 -23
  60. package/src/schemas.ts +6 -0
  61. package/src/signal-digest.ts +2 -8
  62. package/src/spec-cache.ts +17 -41
  63. package/src/tracking-input.ts +11 -2
package/src/index.ts CHANGED
@@ -43,7 +43,6 @@ export {
43
43
  blockSchema,
44
44
  generatedSpecSchema,
45
45
  parseComponentSpec,
46
- parseGeneratedSpec,
47
46
  productReferenceSchema,
48
47
  safeParseGeneratedSpec,
49
48
  type BannerBlock,
@@ -64,7 +63,7 @@ export {
64
63
  } from './component-spec.js';
65
64
 
66
65
  export { reconcileSpec, type ReconcileResult } from './reconciliation.js';
67
- export { selectProducts, type ProductPick } from './product-selection.js';
66
+ export { selectProducts, type ProductPick, type RankOrder } from './product-selection.js';
68
67
 
69
68
  export {
70
69
  createFixedSpecProvider,
@@ -1,4 +1,10 @@
1
- import { BANNER_TONES, EMPHASIS, RECOMMENDATION_BASES, TONES } from './component-spec.js';
1
+ import {
2
+ BANNER_TONES,
3
+ EMPHASIS,
4
+ GRID_COLUMNS,
5
+ RECOMMENDATION_BASES,
6
+ TONES,
7
+ } from './component-spec.js';
2
8
  import type { SignalDigest } from './signal-digest.js';
3
9
  import { FIELD_LIMITS, type Product, type TrackingInput } from './tracking-input.js';
4
10
 
@@ -12,6 +18,21 @@ export interface PromptPair {
12
18
 
13
19
  const quotedList = (values: readonly string[]) => values.map((value) => `"${value}"`).join(', ');
14
20
 
21
+ const NUMBER_WORDS = [
22
+ 'zero',
23
+ 'one',
24
+ 'two',
25
+ 'three',
26
+ 'four',
27
+ 'five',
28
+ 'six',
29
+ 'seven',
30
+ 'eight',
31
+ 'nine',
32
+ ];
33
+
34
+ const inWords = (count: number) => NUMBER_WORDS[count] ?? String(count);
35
+
15
36
  export const SYSTEM_PROMPT = `You design one recommendation component for one shopper on an
16
37
  e-commerce page. You return JSON matching the schema you were given, and nothing else.
17
38
 
@@ -46,7 +67,7 @@ Blocks never nest.
46
67
 
47
68
  - "hero" — one large statement, optionally anchored to a single product. Use
48
69
  when one product clearly dominates what the shopper seems to want.
49
- - "grid" — a titled grid of 2, 3 or 4 columns. The general choice when several
70
+ - "grid" — a titled grid of ${GRID_COLUMNS.slice(0, -1).join(', ')} or ${GRID_COLUMNS.at(-1)} columns. The general choice when several
50
71
  products are comparably relevant.
51
72
  - "carousel" — a row read left to right. Use when the order means something.
52
73
  - "banner" — a single line of merchandising copy, with a tone of ${quotedList(BANNER_TONES)}.
@@ -59,7 +80,7 @@ Blocks never nest.
59
80
  products: you are never shown which set the shop will pick, so words about
60
81
  the things in it end up beside a different set. Never say a set saves money,
61
82
  and never say by how much — you are not told any of the prices. Every product
62
- in a set spends one of your product slots, and a set holds two to five of
83
+ in a set spends one of your product slots, and a set holds two to ${inWords(FIELD_LIMITS.productsPerBundle)} of
63
84
  them.
64
85
 
65
86
  Each product you place carries an "emphasis" of ${quotedList(EMPHASIS)}.
@@ -0,0 +1,43 @@
1
+ import type { Bundle, Product } from './tracking-input.js';
2
+
3
+ export function defaultHrefForSku(sku: string): string {
4
+ return `/product/${encodeURIComponent(sku)}`;
5
+ }
6
+
7
+ export function findSellableProduct(
8
+ products: ReadonlyMap<string, Product>,
9
+ sku: string,
10
+ ): Product | undefined {
11
+ const product = products.get(sku);
12
+ return product?.isInStock === false ? undefined : product;
13
+ }
14
+
15
+ function formatMoney(price: number, currency: string, locale?: string): string {
16
+ let formatter: Intl.NumberFormat;
17
+ try {
18
+ formatter = new Intl.NumberFormat(locale, { style: 'currency', currency });
19
+ } catch {
20
+ return `${currency} ${price}`;
21
+ }
22
+ return formatter.format(price);
23
+ }
24
+
25
+ export function defaultFormatPrice(product: Product, locale?: string): string {
26
+ if (!Number.isFinite(product.price)) {
27
+ throw new TypeError(
28
+ `price for SKU ${product.sku} is ${String(product.price)}, not a finite number. ` +
29
+ 'Catalog objects must satisfy productSchema from @rudra-js/core',
30
+ );
31
+ }
32
+ return formatMoney(product.price, product.currency, locale);
33
+ }
34
+
35
+ export function defaultFormatBundlePrice(bundle: Bundle, locale?: string): string {
36
+ if (!Number.isFinite(bundle.price)) {
37
+ throw new TypeError(
38
+ `price for bundle ${bundle.id} is ${String(bundle.price)}, not a finite number. ` +
39
+ 'Bundle objects must satisfy bundleSchema from @rudra-js/core',
40
+ );
41
+ }
42
+ return formatMoney(bundle.price, bundle.currency, locale);
43
+ }
@@ -24,10 +24,6 @@ const CLAMP = {
24
24
 
25
25
  export const MAX_BLOCKS = 4;
26
26
 
27
- export function capBlocks(blocks: Block[]): Block[] {
28
- return blocks.slice(0, MAX_BLOCKS);
29
- }
30
-
31
27
  export interface ReconcileResult {
32
28
  spec: GeneratedSpec;
33
29
  isUsable: boolean;
@@ -253,27 +249,24 @@ function chooseBundle(run: Run): Bundle | undefined {
253
249
  return best;
254
250
  }
255
251
 
256
- export function bundleForShopper(
252
+ export function heroAndSetSkus(
253
+ blocks: Block[],
257
254
  input: TrackingInput,
258
255
  digest: SignalDigest,
259
- spokenFor: readonly string[],
260
- ): Bundle | undefined {
261
- const run = startRun(input, digest, new Map());
262
- for (const sku of spokenFor) place(run, sku);
263
-
264
- return chooseBundle(run);
265
- }
266
-
267
- export function placeableHeroSkus(blocks: readonly Block[], input: TrackingInput): string[] {
268
- const allowed = inStockSkus(input);
269
- const blocked = blockedForPicks(input);
270
- const skus: string[] = [];
271
- for (const block of blocks) {
272
- if (block.kind !== 'hero' || block.sku === null) continue;
273
- if (!allowed.has(block.sku) || blocked.has(block.sku)) continue;
274
- if (!skus.includes(block.sku)) skus.push(block.sku);
256
+ ): ReadonlySet<string> {
257
+ const heroes = startRun(input, digest, new Map());
258
+ let setSkus: readonly string[] | undefined;
259
+ let listAbove = false;
260
+
261
+ for (const block of blocks.slice(0, MAX_BLOCKS)) {
262
+ if (block.kind === 'hero' && block.sku !== null) takeSlot(block.sku, heroes);
263
+ if (setSkus !== undefined) continue;
264
+ if (block.kind === 'bundle') setSkus = chooseBundle(heroes)?.skus ?? [];
265
+ if (block.kind === 'grid' || block.kind === 'carousel') listAbove ||= block.items.length > 0;
275
266
  }
276
- return skus;
267
+
268
+ const withSet = new Set([...heroes.placed, ...(setSkus ?? [])]);
269
+ return listAbove && withSet.size >= digest.maxItems ? heroes.placed : withSet;
277
270
  }
278
271
 
279
272
  function reconcileBlock(block: Block, run: Run): Block | null {
@@ -390,7 +383,7 @@ export function reconcileSpec(
390
383
  }
391
384
 
392
385
  const blocks: Block[] = [];
393
- for (const block of capBlocks(generated.blocks)) {
386
+ for (const block of generated.blocks.slice(0, MAX_BLOCKS)) {
394
387
  const reconciled = reconcileBlock(block, run);
395
388
  if (reconciled !== null) blocks.push(reconciled);
396
389
  }
package/src/schemas.ts CHANGED
@@ -5,3 +5,9 @@ export {
5
5
  renderContextSchema,
6
6
  } from './tracking-input.js';
7
7
  export { parseComponentSpec } from './component-spec.js';
8
+ export {
9
+ defaultFormatBundlePrice,
10
+ defaultFormatPrice,
11
+ defaultHrefForSku,
12
+ findSellableProduct,
13
+ } from './product-display.js';
@@ -150,14 +150,8 @@ function mergeViewsBySku(views: ViewSignal[]): MergedView[] {
150
150
  const totals = new Map<string, MergedView>();
151
151
 
152
152
  for (const view of views) {
153
- const total = totals.get(view.sku);
154
- if (!total) {
155
- const first: MergedView = { sku: view.sku, views: view.views, weight: weightOf(view) };
156
- if (view.dwellMs !== undefined) first.dwellMs = view.dwellMs;
157
- if (view.category !== undefined) first.category = view.category;
158
- totals.set(view.sku, first);
159
- continue;
160
- }
153
+ const total = totals.get(view.sku) ?? { sku: view.sku, views: 0, weight: -Infinity };
154
+ totals.set(view.sku, total);
161
155
 
162
156
  total.views += view.views;
163
157
  if (view.dwellMs !== undefined) total.dwellMs = (total.dwellMs ?? 0) + view.dwellMs;
package/src/spec-cache.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { SPEC_VERSION, type GeneratedSpec } from './component-spec.js';
3
- import { SYSTEM_PROMPT } from './model-prompt.js';
4
- import type { SignalDigest } from './signal-digest.js';
2
+ import { z } from 'zod';
3
+ import { SPEC_VERSION, generatedSpecSchema } from './component-spec.js';
4
+ import type { PromptPair } from './model-prompt.js';
5
5
 
6
- export interface CachedSpec {
7
- spec: GeneratedSpec;
8
- generatedAt: number;
9
- }
6
+ export const cachedSpecSchema = z.object({
7
+ spec: generatedSpecSchema,
8
+ generatedAt: z.number(),
9
+ });
10
+
11
+ export type CachedSpec = z.infer<typeof cachedSpecSchema>;
10
12
 
11
13
  export interface SpecCache {
12
14
  get(key: string): Promise<CachedSpec | undefined>;
@@ -79,43 +81,17 @@ export function createNullSpecCache(): SpecCache {
79
81
  return { get: async () => undefined, set: async () => {} };
80
82
  }
81
83
 
82
- function canonicalise(value: unknown): string {
83
- if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
84
- if (Array.isArray(value)) return `[${value.map(canonicalise).join(',')}]`;
85
-
86
- const sorted = Object.entries(value as Record<string, unknown>).toSorted(([left], [right]) =>
87
- left < right ? -1 : 1,
88
- );
89
- const fields: string[] = [];
90
- for (const [name, fieldValue] of sorted) {
91
- if (fieldValue === undefined) continue;
92
- fields.push(`${JSON.stringify(name)}:${canonicalise(fieldValue)}`);
93
- }
94
- return `{${fields.join(',')}}`;
95
- }
96
-
97
- const PROMPT_FINGERPRINT = createHash('sha256').update(SYSTEM_PROMPT).digest('hex').slice(0, 16);
98
-
99
- function withoutDwellAndScores(digest: SignalDigest) {
100
- return {
101
- ...digest,
102
- topViewed: digest.topViewed.map(({ dwellMs: _dwellMs, ...view }) => view),
103
- categoryAffinity: digest.categoryAffinity.map(({ score: _score, ...affinity }) => affinity),
104
- };
105
- }
106
-
107
84
  export function specCacheKey(
108
- digest: SignalDigest,
109
- candidateSkus: readonly string[],
85
+ prompt: PromptPair,
110
86
  provider: { name: string; model: string },
111
87
  ): string {
112
- const material = canonicalise({
113
- specVersion: SPEC_VERSION,
114
- prompt: PROMPT_FINGERPRINT,
115
- provider,
116
- digest: withoutDwellAndScores(digest),
117
- candidates: candidateSkus.toSorted(),
118
- });
88
+ const material = JSON.stringify([
89
+ SPEC_VERSION,
90
+ provider.name,
91
+ provider.model,
92
+ prompt.system,
93
+ prompt.user,
94
+ ]);
119
95
 
120
96
  return createHash('sha256').update(material).digest('hex').slice(0, 32);
121
97
  }
@@ -23,6 +23,15 @@ const MAX_EPOCH_MS = Date.UTC(2100, 0, 1);
23
23
  const identifier = () => z.string().min(1).max(FIELD_LIMITS.identifier);
24
24
  const optionalIdentifier = () => identifier().optional();
25
25
 
26
+ // In u mode a surrogate pair reads as one code point, so this matches only an unpaired half.
27
+ const hasLoneSurrogate = (value: string) => /\p{Surrogate}/u.test(value);
28
+
29
+ // Product links run the SKU through encodeURIComponent, which throws on a lone surrogate.
30
+ const skuIdentifier = () =>
31
+ identifier().refine((value) => !hasLoneSurrogate(value), {
32
+ message: 'expected well-formed Unicode, with no unpaired surrogate',
33
+ });
34
+
26
35
  const currencyCode = () =>
27
36
  z
28
37
  .string()
@@ -48,7 +57,7 @@ const imageReference = () =>
48
57
  );
49
58
 
50
59
  export const productSchema = z.strictObject({
51
- sku: identifier(),
60
+ sku: skuIdentifier(),
52
61
  title: z.string().min(1).max(FIELD_LIMITS.shortText),
53
62
  category: identifier(),
54
63
  price: z.number().nonnegative(),
@@ -143,7 +152,7 @@ export type TrackingSignals = z.infer<typeof trackingSignalsSchema>;
143
152
  export const bundleSchema = z.strictObject({
144
153
  id: identifier(),
145
154
  skus: z
146
- .array(identifier())
155
+ .array(skuIdentifier())
147
156
  .min(2)
148
157
  .max(FIELD_LIMITS.productsPerBundle)
149
158
  .refine(isUnique, { message: 'a bundle must not list the same product twice' }),