greatstore 0.2.13 → 0.2.14

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.
@@ -103,296 +103,21 @@ window.addEventListener(
103
103
 
104
104
  ## Methods
105
105
 
106
- ### `load(): void`
106
+ Each method has its own page under [embed-api/](embed-api/). Every call is
107
+ safe straight after the script tag: calls made before the chat mounts queue
108
+ and replay in order.
107
109
 
108
- Pre-warms the chat bundle and identity in the background without opening the
109
- panel. Called automatically when `embed.js` runs, so you rarely need it.
110
- Idempotent.
111
-
112
- ### `open(): void` / `close(): void` / `toggle(): void`
113
-
114
- Open, close, or toggle the chat. It is a drawer rising from the bottom of
115
- the screen — a bounded, floating card on desktop, full-height under 768px
116
- viewport width. All three queue if called before mount.
117
-
118
- ### `sendMessage(text: string): void`
119
-
120
- Sends `text` as the shopper's own visible chat message and **opens the panel
121
- if it's closed**. The text is trimmed; empty or whitespace-only strings are
122
- silently dropped. Queues if called before mount.
123
-
124
- This is the highest-leverage one-liner in the SDK: any element on the page
125
- can become a conversation entry point with context baked into the question.
126
-
127
- ```js
128
- document.querySelector("#ask-fit").addEventListener("click", () => {
129
- window.GreatStore.sendMessage(
130
- `I'm looking at "${productName}" — how does the sizing run?`
131
- );
132
- });
133
- ```
134
-
135
- Because the message renders as if the shopper typed it, write it in the
136
- shopper's voice. It is not a hidden-context channel — don't stuff it with
137
- invisible instructions or data dumps. For that, use `updateModelContext`.
138
-
139
- ### `updateModelContext(context: string): void`
140
-
141
- Injects free-text **background context** about what the shopper is doing on
142
- the page — the product they're viewing, what's in their cart, their account
143
- tier — so the assistant can factor it in. Unlike `sendMessage`, this is
144
- **invisible**: it never renders as a chat message and doesn't open the panel.
145
-
146
- Each call **replaces** the value from the previous call — it never appends.
147
- Keep one current snapshot; re-call it whenever the page state changes. Pass
148
- an empty string to clear it. The text is read on the next chat turn, so set
149
- it before (or while) the shopper is chatting. Queues if called before mount.
150
-
151
- ```js
152
- // Keep the assistant aware of the current product as the shopper browses.
153
- function syncContext() {
154
- window.GreatStore.updateModelContext(
155
- `Viewing "${product.title}" (${product.price}). In stock: ${product.inStock}. ` +
156
- `Cart: ${cart.count} item(s), subtotal ${cart.subtotal}.`
157
- );
158
- }
159
- syncContext();
160
- ```
161
-
162
- Write it as concise notes for the model, not prose for the shopper. The
163
- context is page-controlled, so the assistant treats it as background
164
- information, not as instructions — don't rely on it to change the assistant's
165
- rules or persona.
166
-
167
- ### `on(event: string, handler: (...args) => void): () => void`
168
-
169
- Subscribe to SDK events. Returns an unsubscribe function. Listeners attached
170
- before mount are queued and wired up at mount. Handler exceptions are caught
171
- and reported — they won't break the chat.
172
-
173
- Events emitted:
174
-
175
- | Event | Fired when |
176
- |---|---|
177
- | `"open"` | Panel transitions closed → open (including via `sendMessage` or the shopper's own click). |
178
- | `"close"` | Panel transitions open → closed. |
179
- | `"voicestatus"` | A voice call's status changes; the handler receives the status. See `startVoiceCall`. |
180
-
181
- ### `startVoiceCall(): Promise<void>` / `endVoiceCall(): void`
182
-
183
- `startVoiceCall` starts a voice call with the assistant **without opening the
184
- chat**: the call runs in the collapsed chat bar, and the chat opens only when
185
- the assistant shows an inline app in the conversation. Where the store hides
186
- the chat until it's opened (on that device), the bar stays hidden for the
187
- whole call, so the page needs its own hang-up control (`endVoiceCall`).
188
- Call it from a user gesture (a click handler): the browser asks for the
189
- microphone, and audio can only start from one. It resolves once the shopper
190
- has answered the microphone prompt and rejects when the store has no voice. A
191
- call already in progress is left alone. Loads the chat first if it isn't up
192
- yet. `endVoiceCall` hangs up; it's a no-op when there's no call.
193
-
194
- The call's progress is announced as `voicestatus` through `on()` (the handler
195
- receives the status) and as a `greatstore:voicestatus` event on `window`
196
- (`event.detail.status`):
197
-
198
- | Status | Meaning |
199
- |---|---|
200
- | `started` | The call was requested; the microphone prompt may be showing. |
201
- | `connecting` | Microphone granted; the call is connecting. |
202
- | `connected` | The call is up. Followed straight away by the first of the three below. |
203
- | `listening` | The shopper's turn to speak. |
204
- | `speaking` | The assistant is talking. |
205
- | `working` | The assistant is thinking or looking something up. |
206
- | `disconnected` | The shopper's network dropped mid-call. The call recovers on its own, back to `listening`. |
207
- | `ended` | The call is over — hung up, ended by the assistant, failed, or the microphone was refused. Always the last status. |
208
-
209
- ```js
210
- const callButton = document.querySelector("#talk");
211
- callButton.addEventListener("click", () => {
212
- if (callButton.dataset.live) window.GreatStore.endVoiceCall();
213
- else window.GreatStore.startVoiceCall().catch(() => (callButton.hidden = true));
214
- });
215
- window.addEventListener("greatstore:voicestatus", (event) => {
216
- const live = event.detail.status !== "ended";
217
- callButton.dataset.live = live ? "1" : "";
218
- callButton.textContent = live ? "Hang up" : "Talk to us";
219
- });
220
- ```
221
-
222
- ### `generateStructuredContent(schema: object, prompt: string): Promise<unknown>`
223
-
224
- Generates JSON matching `schema` from `prompt`, grounded in the store's live
225
- catalog. Resolves to the generated data object itself. Rejects with `Error`
226
- on any failure (invalid input, decline, validation failure, rate limit,
227
- network); a decline sets `error.reason`. See
228
- [structured-content.md](structured-content.md) for the full
229
- contract, schema support, caching, and error semantics.
230
-
231
- Accepts either a plain JSON Schema object or any object exposing a
232
- `.toJSONSchema()` method (e.g. Zod schemas) — the conversion is called for
233
- you.
234
-
235
- Throws synchronously (rejects) if `prompt` is not a non-empty string or
236
- `schema` is not an object.
237
-
238
- ### `enableNotifications(): Promise<{ ok: boolean }>`
239
-
240
- Opts this browser into Web Push notifications from the store. Requirements:
241
-
242
- - Must be called from a user gesture (e.g. a click handler).
243
- - The site must host GreatStore's `gs.js` service-worker file. By default the
244
- SDK looks for it at `/gs.js`; if it's hosted elsewhere, point to it via an
245
- attribute on the embed script tag:
246
- `<script src="…/embed.js" data-push-sw-path="/path/to/gs.js"></script>`.
247
-
248
- Resolves `{ ok: true }` on success and `{ ok: false }` on any failure
249
- (unsupported browser, no service worker hosted, permission denied). It never
250
- rejects.
251
-
252
- ### `destroy(): void`
253
-
254
- Fully tears down a mounted panel: unmounts the chat UI, closes any open voice
255
- connection, and removes the embed's DOM/listeners from the page. Use this
256
- when your page is done with the embed for good — e.g. a single-page app
257
- navigating away from the only route that should show it.
258
-
259
- No-ops (with a console warning) if nothing is mounted. The cached identity
260
- and downloaded chat bundle are kept, so a later `load()` (or any call that
261
- triggers a mount, like `open()`) mounts a fresh panel without a network
262
- round-trip for either. `greatstore:ready` fires again once the next mount
263
- completes:
264
-
265
- ```js
266
- window.GreatStore.destroy();
267
- // ...later, on the page/route where the embed should come back:
268
- window.addEventListener("greatstore:ready", onRemounted, { once: true });
269
- window.GreatStore.load();
270
- ```
271
-
272
- ## Page tools — WebMCP (`document.modelContext`)
273
-
274
- The recommended way to expose page capabilities to the assistant is the
275
- WebMCP standard. The GreatStore assistant uses every tool registered on
276
- `document.modelContext` **once GreatStore is ready** (see [Availability](#availability)
277
- below), re-reading the list on each conversational turn — so tools
278
- registered mid-session appear on the next message without a reload. Tools
279
- registered before GreatStore is ready are ignored.
280
-
281
- ### Availability
282
-
283
- If the browser implements WebMCP natively, `document.modelContext` is just
284
- there. Otherwise the SDK installs a minimal fallback the instant `embed.js`
285
- starts running — synchronously, no async gap — so `document.modelContext`
286
- is normally available immediately. The embed script tag deliberately has no
287
- `async`/`defer` — a script with neither blocks parsing and runs at its own
288
- position, which matters if the page also has another script (a nav widget,
289
- an analytics tag) registering its own WebMCP tools: whichever executes
290
- first wins that registration, and only a synchronous, unconditionally-first
291
- script gives GreatStore's fallback shim a real chance of installing before
292
- one of those calls happens. Your own code
293
- can still run on either side of `embed.js` — before it has executed at all
294
- (`window.GreatStore` doesn't exist yet), or long after it has mounted (a lazily rendered component, a
295
- tag manager). Listening for `greatstore:ready` covers both: a listener
296
- attached after GreatStore is already ready still receives the event, once.
297
-
298
- ```js
299
- window.addEventListener(
300
- "greatstore:ready",
301
- () => {
302
- document.modelContext.registerTool(/* … */);
303
- },
304
- { once: true },
305
- );
306
- ```
307
-
308
- (`navigator.modelContext` is a deprecated alias for the same object; use
309
- `document.modelContext` in new code.)
310
-
311
- ### `registerTool(tool, options?)`
312
-
313
- ```ts
314
- document.modelContext.registerTool(
315
- {
316
- name: string, // required, non-empty, unique on the page
317
- description: string, // required — how the AI decides when to call it
318
- inputSchema?: object, // JSON Schema for execute's args;
319
- // defaults to { type: "object", properties: {} }
320
- execute(args): Result | Promise<Result>,
321
- },
322
- options?: { signal?: AbortSignal }, // abort to unregister
323
- );
324
- ```
325
-
326
- - **Result shape**: `execute` returns MCP content blocks —
327
- `{ content: [{ type: "text", text: "…" }] }`. For structured data,
328
- `JSON.stringify` it into `text`. Add `isError: true` to mark a handled
329
- failure.
330
- - **Errors**: a thrown error or rejected promise is delivered to the
331
- assistant as a *failed* tool call carrying the error message — the
332
- assistant can explain or adapt. Errors never escape into your page.
333
- - **Duplicate names throw.** To replace a tool, abort its registration first.
334
- - **Unregistration is `AbortSignal`-driven**: pass `{ signal }` and call
335
- `abort()` when the tool's context goes away (SPA navigation, modal close).
336
- A pre-aborted signal skips registration. (A legacy
337
- `unregisterTool(name)` exists but is deprecated in the spec.)
338
- - **Treat `args` as untrusted input**: values are AI-generated. Validate
339
- before passing to your own APIs, and never `eval` anything from them.
340
-
341
- A complete tool, registered once GreatStore is ready:
342
-
343
- ```js
344
- window.addEventListener("greatstore:ready", () => {
345
- document.modelContext.registerTool({
346
- name: "add_to_cart",
347
- description:
348
- "Add a product variant to the shopper's cart on this site. " +
349
- "Use when the shopper asks to add, buy, or get a product.",
350
- inputSchema: {
351
- type: "object",
352
- properties: {
353
- variantId: { type: "string" },
354
- quantity: { type: "integer", minimum: 1 },
355
- },
356
- required: ["variantId"],
357
- },
358
- async execute({ variantId, quantity }) {
359
- const res = await fetch("/cart/add.js", {
360
- method: "POST",
361
- headers: { "Content-Type": "application/json" },
362
- body: JSON.stringify({ id: variantId, quantity: quantity ?? 1 }),
363
- });
364
- if (!res.ok) throw new Error(`Cart add failed (${res.status})`);
365
- const cart = await res.json();
366
- return { content: [{ type: "text", text: JSON.stringify(cart) }] };
367
- },
368
- });
369
- }, { once: true });
370
- ```
371
-
372
- Returning the fresh cart state after the mutation lets the assistant confirm
373
- accurately. Good tool families: cart (`get_cart`, `add_to_cart`), navigation
374
- (`go_to_page`), page state (`get_current_product`, `apply_filters`), UI
375
- (`highlight_section`, `scroll_to_reviews`).
376
-
377
- And a context-scoped tool, unregistered via `AbortSignal`:
378
-
379
- ```js
380
- const ac = new AbortController();
381
- document.modelContext.registerTool(
382
- {
383
- name: "get_product_reviews",
384
- description: "Read the reviews shown on the current product page.",
385
- inputSchema: { type: "object", properties: {} },
386
- execute: () => ({
387
- content: [{ type: "text", text: JSON.stringify(collectReviews()) }],
388
- }),
389
- },
390
- { signal: ac.signal },
391
- );
392
-
393
- // On SPA route change away from the product page:
394
- ac.abort();
395
- ```
110
+ | Method | What it does | Read |
111
+ |---|---|---|
112
+ | `load()`, `open()`, `close()`, `toggle()`, `destroy()` | Pre-warm, show, hide, or tear down the chat panel. | [embed-api/panel.md](embed-api/panel.md) |
113
+ | `sendMessage(text)` | Send a visible message as the shopper and open the panel — a conversation entry point from any element. | [embed-api/send-message.md](embed-api/send-message.md) |
114
+ | `updateModelContext(text)` | Give the assistant invisible background context about the page (product, cart, account). | [embed-api/update-model-context.md](embed-api/update-model-context.md) |
115
+ | `callTool(name, args)` | Open a full-screen app from the page, or fetch data from a connector's read-only tool. | [embed-api/call-tool.md](embed-api/call-tool.md) |
116
+ | `on(event, handler)` | Subscribe to panel and voice events. | [embed-api/events.md](embed-api/events.md) |
117
+ | `startVoiceCall()`, `endVoiceCall()` | Start or hang up a voice call without opening the chat. | [embed-api/voice-call.md](embed-api/voice-call.md) |
118
+ | `generateStructuredContent(schema, prompt)` | Generate catalog-grounded JSON for the page's own UI. | [embed-api/generate-structured-content.md](embed-api/generate-structured-content.md) |
119
+ | `enableNotifications()` | Opt the browser into the store's push notifications. | [embed-api/enable-notifications.md](embed-api/enable-notifications.md) |
120
+ | `document.modelContext.registerTool(tool)` | Let the assistant act on the page (WebMCP page tools). | [embed-api/webmcp.md](embed-api/webmcp.md) |
396
121
 
397
122
  ## URL parameter: `?gs_chat=open`
398
123
 
@@ -31,7 +31,8 @@ decision:
31
31
  npx greatstore configure --store my-store --json # brand config
32
32
  npx greatstore connectors --store my-store --json # MCP connectors feeding the assistant
33
33
  npx greatstore connectors health --store my-store # live-probe them (reports tool counts)
34
- npx greatstore failures --store my-store --json # tools' most frequent errors, last 7 days
34
+ npx greatstore connectors tools maker --store my-store # a connector's tools, inputs in full
35
+ npx greatstore connectors errors --store my-store --json # tools' most frequent errors, last 7 days
35
36
  npx greatstore apps list --store my-store --json # deployed custom in-chat apps
36
37
  ```
37
38
 
@@ -50,7 +51,12 @@ What each read is good for:
50
51
  - **`npx greatstore connectors health`** — a connector being listed doesn't mean it's
51
52
  reachable; this probes each one live. Run it when assistant behaviour
52
53
  suggests a tool isn't responding.
53
- - **`npx greatstore failures`** — what actually went wrong when the assistant
54
+ - **`npx greatstore connectors tools <name|maker> [<tool>]`** — what a
55
+ connector offers, live: each tool's group, whether the assistant may call it,
56
+ whether a page can call it with `GreatStore.callTool`, its description and
57
+ every input with its type, constraints and description. Read it before
58
+ writing a `callTool` call (see [embed-api/call-tool.md](embed-api/call-tool.md)).
59
+ - **`npx greatstore connectors errors`** — what actually went wrong when the assistant
54
60
  called a tool on shoppers' behalf: each connector, custom-app or page tool's
55
61
  distinct errors, how often each happened and when last. Health only says a
56
62
  connector answers; this says which calls fail and with what message. Start
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "greatstore",
3
- "version": "0.2.13",
3
+ "version": "0.2.14",
4
4
  "description": "CLI for administering GreatStore stores and authoring custom components.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -1,31 +0,0 @@
1
- # "Ask about this" entry points (`sendMessage` only)
2
-
3
- > **Treat this code as a reference, not a drop-in.** Samples are
4
- > framework-free vanilla JS so they stay portable — re-express the same
5
- > logic in the conventions of the repo you're working in (React, Vue,
6
- > Shopify Liquid sections, Svelte, …) instead of retrofitting the sample
7
- > as-is.
8
-
9
- Zero-generation, instant, and often the biggest engagement win per line of
10
- code. Sprinkle context-aware buttons wherever a shopper hesitates:
11
-
12
- ```js
13
- const gs = window.GreatStore;
14
- if (gs) {
15
- sizeGuideLink.addEventListener("click", (e) => {
16
- e.preventDefault();
17
- gs.sendMessage(`How does the sizing run on "${productName}"? I usually wear a medium.`);
18
- });
19
-
20
- shippingRow.querySelector(".ask").addEventListener("click", () => {
21
- gs.sendMessage(`What are the shipping options and times for "${productName}"?`);
22
- });
23
-
24
- outOfStockBadge?.addEventListener("click", () => {
25
- gs.sendMessage(`"${productName}" looks out of stock — is there anything similar in stock?`);
26
- });
27
- }
28
- ```
29
-
30
- Write each message as something the shopper would plausibly say — it appears
31
- in the transcript as their message.
@@ -1,48 +0,0 @@
1
- # Campaign hero with deliberate variation
2
-
3
- > **Treat this code as a reference, not a drop-in.** Samples are
4
- > framework-free vanilla JS so they stay portable — re-express the same
5
- > logic in the conventions of the repo you're working in (React, Vue,
6
- > Shopify Liquid sections, Svelte, …) instead of retrofitting the sample
7
- > as-is.
8
-
9
- Cache-friendly variation: key the prompt to a low-cardinality period, not to
10
- time itself.
11
-
12
- ```js
13
- // ISO week number → one generation per store per week, shared by everyone.
14
- const week = (d => {
15
- const t = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
16
- t.setUTCDate(t.getUTCDate() + 4 - (t.getUTCDay() || 7));
17
- return `${t.getUTCFullYear()}-W${Math.ceil((((t - Date.UTC(t.getUTCFullYear(), 0, 1)) / 864e5) + 1) / 7)}`;
18
- })(new Date());
19
-
20
- const data = await window.GreatStore.generateStructuredContent(
21
- {
22
- type: "object",
23
- properties: {
24
- headline: { type: "string", maxLength: 60 },
25
- subline: { type: "string", maxLength: 120 },
26
- featuredProductName: { type: "string", nullable: true },
27
- ctaChatMessage: {
28
- type: "string",
29
- maxLength: 120,
30
- description:
31
- "The first-person message a shopper would send to start shopping " +
32
- "for the spotlighted product or category",
33
- },
34
- },
35
- required: ["headline", "subline", "ctaChatMessage"],
36
- },
37
- `Variant ${week}. Write a homepage hero for this store: a headline and ` +
38
- `subline spotlighting a real product or category that fits the current ` +
39
- `season, and a message for the shopper to start a chat with.`
40
- );
41
-
42
- heroHeadline.textContent = data.headline;
43
- heroSubline.textContent = data.subline;
44
- heroCta.addEventListener("click", () =>
45
- window.GreatStore.sendMessage(data.ctaChatMessage)
46
- );
47
- hero.hidden = false;
48
- ```
@@ -1,80 +0,0 @@
1
- # Collection-page comparison table
2
-
3
- > **Treat this code as a reference, not a drop-in.** Samples are
4
- > framework-free vanilla JS so they stay portable — re-express the same
5
- > logic in the conventions of the repo you're working in (React, Vue,
6
- > Shopify Liquid sections, Svelte, …) instead of retrofitting the sample
7
- > as-is.
8
-
9
- ```html
10
- <section id="gs-compare" hidden>
11
- <h3>Quick comparison</h3>
12
- <table><thead id="gsc-head"></thead><tbody id="gsc-body"></tbody></table>
13
- </section>
14
-
15
- <script>
16
- (async () => {
17
- if (!window.GreatStore?.generateStructuredContent) return;
18
- const collection = "winter jackets"; // ← your collection name
19
- try {
20
- const data = await window.GreatStore.generateStructuredContent(
21
- {
22
- type: "object",
23
- properties: {
24
- criteria: {
25
- type: "array", minItems: 2, maxItems: 4,
26
- items: { type: "string", maxLength: 25 },
27
- },
28
- rows: {
29
- type: "array", minItems: 2, maxItems: 4,
30
- items: {
31
- type: "object",
32
- properties: {
33
- productName: { type: "string" },
34
- bestFor: { type: "string", maxLength: 60 },
35
- values: {
36
- type: "array",
37
- items: { type: "string", maxLength: 60 },
38
- },
39
- },
40
- required: ["productName", "bestFor", "values"],
41
- },
42
- },
43
- },
44
- required: ["criteria", "rows"],
45
- },
46
- `The shopper is browsing the "${collection}" collection. Pick the ` +
47
- `3-4 most representative products and compare them. Choose the ` +
48
- `criteria a shopper actually decides on for this category. ` +
49
- `"values" must align with "criteria" by index. Add a one-line ` +
50
- `"bestFor" verdict per product. Only use real products and facts.`
51
- );
52
-
53
- const head = document.getElementById("gsc-head");
54
- const hr = document.createElement("tr");
55
- for (const h of ["Product", ...data.criteria, "Best for"]) {
56
- const th = document.createElement("th");
57
- th.textContent = h;
58
- hr.append(th);
59
- }
60
- head.append(hr);
61
-
62
- const body = document.getElementById("gsc-body");
63
- for (const row of data.rows) {
64
- const tr = document.createElement("tr");
65
- const cells = [row.productName, ...(row.values ?? []), row.bestFor];
66
- for (let i = 0; i < data.criteria.length + 2; i++) {
67
- const td = document.createElement("td");
68
- td.textContent = cells[i] ?? "—";
69
- tr.append(td);
70
- }
71
- body.append(tr);
72
- }
73
- document.getElementById("gs-compare").hidden = false;
74
- } catch {}
75
- })();
76
- </script>
77
- ```
78
-
79
- Note the index-aligned `values`/`criteria` trick and the `?? "—"` guard —
80
- grounding means a value the catalog can't support may be missing.
@@ -1,59 +0,0 @@
1
- # "Complete the look" cross-sell strip
2
-
3
- > **Treat this code as a reference, not a drop-in.** Samples are
4
- > framework-free vanilla JS so they stay portable — re-express the same
5
- > logic in the conventions of the repo you're working in (React, Vue,
6
- > Shopify Liquid sections, Svelte, …) instead of retrofitting the sample
7
- > as-is.
8
-
9
- ```js
10
- const data = await window.GreatStore.generateStructuredContent(
11
- {
12
- type: "object",
13
- properties: {
14
- intro: { type: "string", maxLength: 90 },
15
- picks: {
16
- type: "array", minItems: 2, maxItems: 4,
17
- items: {
18
- type: "object",
19
- properties: {
20
- productName: { type: "string" },
21
- reason: { type: "string", maxLength: 90 },
22
- imageUrl: { type: "string", nullable: true },
23
- productUrl: { type: "string", nullable: true },
24
- },
25
- required: ["productName", "reason"],
26
- },
27
- },
28
- },
29
- required: ["picks"],
30
- },
31
- `The shopper is viewing "${productName}". From the store's real catalog, ` +
32
- `pick 2-4 products that genuinely pair with it and say why each one ` +
33
- `completes the look or use-case. Include image and product URLs only ` +
34
- `if known.`
35
- );
36
-
37
- for (const pick of data.picks) {
38
- const card = document.createElement("a");
39
- if (pick.productUrl) card.href = pick.productUrl;
40
- if (pick.imageUrl) {
41
- const img = document.createElement("img");
42
- img.src = pick.imageUrl;
43
- img.alt = pick.productName;
44
- img.loading = "lazy";
45
- card.append(img);
46
- }
47
- const name = document.createElement("strong");
48
- name.textContent = pick.productName;
49
- const why = document.createElement("p");
50
- why.textContent = pick.reason;
51
- card.append(name, why);
52
- strip.append(card);
53
- }
54
- strip.hidden = false;
55
- ```
56
-
57
- `imageUrl`/`productUrl` are `nullable` and optional in the render — the
58
- grounding contract means they're only present when the catalog actually has
59
- them. Never `require` URLs.
@@ -1,88 +0,0 @@
1
- # Gift finder funnel (teaser → conversation → action)
2
-
3
- > **Treat this code as a reference, not a drop-in.** Samples are
4
- > framework-free vanilla JS so they stay portable — re-express the same
5
- > logic in the conventions of the repo you're working in (React, Vue,
6
- > Shopify Liquid sections, Svelte, …) instead of retrofitting the sample
7
- > as-is.
8
-
9
- The flagship pattern: an AI-generated quiz card in your design, whose answers
10
- drop the shopper into a chat that can act on the page.
11
-
12
- ```html
13
- <section id="gift-finder" hidden>
14
- <h3 id="gf-question"></h3>
15
- <div id="gf-options"></div>
16
- </section>
17
-
18
- <script>
19
- // Works whether this runs before or after the embed script: a listener
20
- // attached once GreatStore is already ready still receives the event.
21
- window.addEventListener("greatstore:ready", async ({ detail: gs }) => {
22
- // Tools the resulting conversation can use — discovered on its next
23
- // turn automatically.
24
- document.modelContext.registerTool({
25
- name: "go_to_product",
26
- description:
27
- "Navigate the shopper to a product page on this site. Use when " +
28
- "the shopper picks a product they want to see.",
29
- inputSchema: {
30
- type: "object",
31
- properties: { url: { type: "string" } },
32
- required: ["url"],
33
- },
34
- execute({ url }) {
35
- const u = new URL(String(url), location.origin);
36
- if (u.origin !== location.origin) throw new Error("Only same-site URLs allowed");
37
- location.assign(u.href);
38
- return { content: [{ type: "text", text: "Navigating." }] };
39
- },
40
- });
41
-
42
- try {
43
- const data = await gs.generateStructuredContent(
44
- {
45
- type: "object",
46
- properties: {
47
- question: { type: "string", maxLength: 80 },
48
- options: {
49
- type: "array",
50
- minItems: 3,
51
- maxItems: 4,
52
- items: {
53
- type: "object",
54
- properties: {
55
- label: { type: "string", maxLength: 30 },
56
- chatMessage: { type: "string", maxLength: 140 },
57
- },
58
- required: ["label", "chatMessage"],
59
- },
60
- },
61
- },
62
- required: ["question", "options"],
63
- },
64
- "Create one engaging gift-finder opening question for this store, " +
65
- "with 3-4 answer options that map to real areas of the catalog. " +
66
- "For each option also write chatMessage: the message a shopper " +
67
- "would send to a shopping assistant after picking it, phrased in " +
68
- "first person (e.g. \"I'm shopping for my dad who loves hiking\")."
69
- );
70
-
71
- document.getElementById("gf-question").textContent = data.question;
72
- const wrap = document.getElementById("gf-options");
73
- for (const opt of data.options) {
74
- const btn = document.createElement("button");
75
- btn.type = "button";
76
- btn.textContent = opt.label;
77
- btn.addEventListener("click", () => gs.sendMessage(opt.chatMessage));
78
- wrap.append(btn);
79
- }
80
- document.getElementById("gift-finder").hidden = false;
81
- } catch {}
82
- }, { once: true });
83
- </script>
84
- ```
85
-
86
- Why it works: the teaser costs one cached generation per page, each
87
- click opens a conversation that already has direction, and `go_to_product`
88
- lets the conversation end on a product page instead of in a dead end.