@fayz-ai/sdk 0.8.3 → 0.8.5

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 (64) hide show
  1. package/dist/agent.d.ts +57 -0
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +1 -1
  4. package/dist/{chunk-SKARZBEH.js → chunk-F6PAMHPI.js} +59 -59
  5. package/dist/{chunk-SKARZBEH.js.map → chunk-F6PAMHPI.js.map} +1 -1
  6. package/dist/chunk-LSBVNW75.js +139 -0
  7. package/dist/chunk-LSBVNW75.js.map +1 -0
  8. package/dist/{chunk-7ZHG7XTA.js → chunk-V4GWI7WH.js} +12 -13
  9. package/dist/chunk-V4GWI7WH.js.map +1 -0
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3 -3
  13. package/dist/release-channels.js +1 -1
  14. package/dist/shop.d.ts.map +1 -1
  15. package/dist/shop.js +1 -1
  16. package/dist/vite.js +1 -1
  17. package/dist/vite.js.map +1 -1
  18. package/package.json +15 -24
  19. package/src/agent.ts +152 -5
  20. package/src/index.ts +3 -0
  21. package/src/release-channels.json +57 -57
  22. package/src/shop.ts +22 -20
  23. package/src/vite.ts +1 -1
  24. package/dist/agent.cjs +0 -16
  25. package/dist/agent.cjs.map +0 -1
  26. package/dist/ai-builder.cjs +0 -20
  27. package/dist/ai-builder.cjs.map +0 -1
  28. package/dist/app-params.cjs +0 -16
  29. package/dist/app-params.cjs.map +0 -1
  30. package/dist/chunk-746EA3BV.cjs +0 -774
  31. package/dist/chunk-746EA3BV.cjs.map +0 -1
  32. package/dist/chunk-7UZH4XEV.cjs +0 -66
  33. package/dist/chunk-7UZH4XEV.cjs.map +0 -1
  34. package/dist/chunk-7ZHG7XTA.js.map +0 -1
  35. package/dist/chunk-B6FHOO34.cjs +0 -63
  36. package/dist/chunk-B6FHOO34.cjs.map +0 -1
  37. package/dist/chunk-DAUDGR5N.cjs +0 -88
  38. package/dist/chunk-DAUDGR5N.cjs.map +0 -1
  39. package/dist/chunk-DK3ZA6NA.cjs +0 -139
  40. package/dist/chunk-DK3ZA6NA.cjs.map +0 -1
  41. package/dist/chunk-ENWSXKQE.cjs +0 -125
  42. package/dist/chunk-ENWSXKQE.cjs.map +0 -1
  43. package/dist/chunk-VPMRURSI.js +0 -63
  44. package/dist/chunk-VPMRURSI.js.map +0 -1
  45. package/dist/chunk-WMH7SIER.cjs +0 -140
  46. package/dist/chunk-WMH7SIER.cjs.map +0 -1
  47. package/dist/chunk-ZMHI2XGY.cjs +0 -68
  48. package/dist/chunk-ZMHI2XGY.cjs.map +0 -1
  49. package/dist/client.cjs +0 -22
  50. package/dist/client.cjs.map +0 -1
  51. package/dist/index.cjs +0 -103
  52. package/dist/index.cjs.map +0 -1
  53. package/dist/release-channels.cjs +0 -24
  54. package/dist/release-channels.cjs.map +0 -1
  55. package/dist/runtime.cjs +0 -16
  56. package/dist/runtime.cjs.map +0 -1
  57. package/dist/shop.cjs +0 -20
  58. package/dist/shop.cjs.map +0 -1
  59. package/dist/supported-surface.cjs +0 -24
  60. package/dist/supported-surface.cjs.map +0 -1
  61. package/dist/types.cjs +0 -4
  62. package/dist/types.cjs.map +0 -1
  63. package/dist/vite.cjs +0 -101
  64. package/dist/vite.cjs.map +0 -1
@@ -1,774 +0,0 @@
1
- 'use strict';
2
-
3
- // src/shop.ts
4
- var _accessTokenResolver = null;
5
- function setShopAccessTokenResolver(resolver) {
6
- _accessTokenResolver = resolver;
7
- }
8
- var FayzShopError = class extends Error {
9
- constructor(message, status, responseBody) {
10
- super(message);
11
- this.status = status;
12
- this.responseBody = responseBody;
13
- this.name = "FayzShopError";
14
- }
15
- };
16
- function normalizeBaseUrl(url) {
17
- return url.replace(/\/+$/, "");
18
- }
19
- function slugify(name) {
20
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
21
- }
22
- function nowIso() {
23
- return (/* @__PURE__ */ new Date()).toISOString();
24
- }
25
- function productMetadataKey(kind, value) {
26
- return `${kind}:${value.toLowerCase()}`;
27
- }
28
- function buildProductMetadataOverlay(overlays) {
29
- const map = /* @__PURE__ */ new Map();
30
- for (const overlay of overlays ?? []) {
31
- if (overlay.sku) map.set(productMetadataKey("sku", overlay.sku), overlay.metadata);
32
- if (overlay.slug) map.set(productMetadataKey("slug", overlay.slug), overlay.metadata);
33
- }
34
- return map;
35
- }
36
- function asUuid(value) {
37
- if (!value) return null;
38
- return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) ? value : null;
39
- }
40
- function rowToImage(row) {
41
- return {
42
- id: row.id,
43
- productId: row.product_id,
44
- url: row.url,
45
- altText: row.alt_text ?? null,
46
- sortOrder: row.sort_order ?? 0,
47
- isPrimary: row.is_primary ?? false,
48
- createdAt: row.created_at ?? nowIso()
49
- };
50
- }
51
- function getProductMetadata(row, overlay) {
52
- const metadata = row.metadata ?? {};
53
- const bySlug = overlay?.get(productMetadataKey("slug", row.slug ?? slugify(row.name)));
54
- const bySku = row.sku ? overlay?.get(productMetadataKey("sku", row.sku)) : void 0;
55
- return { ...bySlug ?? {}, ...bySku ?? {}, ...metadata };
56
- }
57
- function getStoreCategory(row, overlay) {
58
- const raw = getProductMetadata(row, overlay).fayzStoreCategory;
59
- return raw && typeof raw === "object" ? raw : null;
60
- }
61
- function rowToProduct(row, overlay) {
62
- const metadata = getProductMetadata(row, overlay);
63
- const storeCategory = getStoreCategory(row, overlay);
64
- return {
65
- id: row.id,
66
- tenantId: row.tenant_id,
67
- name: row.name,
68
- slug: row.slug ?? slugify(row.name),
69
- description: row.description ?? null,
70
- price: row.price ?? 0,
71
- compareAtPrice: row.compare_at_price ?? null,
72
- currency: row.currency ?? "BRL",
73
- status: row.status ?? "active",
74
- inventoryCount: row.inventory_count ?? 0,
75
- sku: row.sku ?? null,
76
- sortOrder: row.sort_order ?? 0,
77
- metadata,
78
- images: Array.isArray(row.images) ? row.images.map(rowToImage) : [],
79
- categoryId: storeCategory?.id ?? row.category_id ?? null,
80
- categoryName: storeCategory?.name ?? row.category?.name ?? null,
81
- isPhysical: row.is_physical ?? true,
82
- weight: row.weight ?? null,
83
- weightUnit: row.weight_unit ?? "kg",
84
- createdAt: row.created_at ?? nowIso(),
85
- updatedAt: row.updated_at ?? row.created_at ?? nowIso()
86
- };
87
- }
88
- function rowToCategory(row) {
89
- return {
90
- id: row.id,
91
- tenantId: row.tenant_id ?? "global",
92
- name: row.name,
93
- slug: row.slug ?? slugify(row.name),
94
- description: row.description ?? null,
95
- parentId: row.parent_id ?? null,
96
- sortOrder: row.sort_order ?? 0,
97
- imageUrl: row.image_url ?? null,
98
- createdAt: row.created_at ?? nowIso()
99
- };
100
- }
101
- function storeCategoryToCategory(category, tenantId) {
102
- const name = category.name ?? "Category";
103
- return {
104
- id: category.id ?? slugify(name),
105
- tenantId,
106
- name,
107
- slug: category.slug ?? slugify(name),
108
- description: category.description ?? null,
109
- parentId: null,
110
- sortOrder: category.sortOrder ?? 0,
111
- imageUrl: category.imageUrl ?? null,
112
- createdAt: nowIso()
113
- };
114
- }
115
- function deriveStoreCategories(products, tenantId) {
116
- const categories = /* @__PURE__ */ new Map();
117
- for (const product of products) {
118
- const category = getStoreCategory(product);
119
- if (!category?.name && !category?.id) continue;
120
- const mapped = storeCategoryToCategory(category, tenantId);
121
- categories.set(mapped.id, mapped);
122
- }
123
- return [...categories.values()].sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name));
124
- }
125
- function rowToOrder(row) {
126
- return {
127
- id: row.id,
128
- tenantId: row.tenant_id,
129
- orderNumber: row.order_number ?? 0,
130
- status: row.status ?? "open",
131
- financialStatus: row.financial_status ?? "pending",
132
- fulfillmentStatus: row.fulfillment_status ?? "unfulfilled",
133
- currency: row.currency ?? "BRL",
134
- subtotal: row.subtotal ?? 0,
135
- taxTotal: row.tax_total ?? 0,
136
- discountTotal: row.discount_total ?? 0,
137
- shippingTotal: row.shipping_total ?? 0,
138
- total: row.total ?? 0,
139
- customerId: row.customer_id ?? null,
140
- customerName: row.customer_name ?? null,
141
- customerEmail: row.customer_email ?? null,
142
- discountCode: row.discount_code ?? null,
143
- notes: row.notes ?? null,
144
- shippingAddress: row.shipping_address ?? null,
145
- paymentMethodKind: row.payment_method_kind ?? null,
146
- paidAt: row.paid_at ?? null,
147
- items: Array.isArray(row.items) ? row.items.map(rowToOrderItem) : [],
148
- createdAt: row.created_at ?? nowIso(),
149
- updatedAt: row.updated_at ?? row.created_at ?? nowIso()
150
- };
151
- }
152
- function rowToOrderItem(row) {
153
- return {
154
- id: row.id,
155
- orderId: row.order_id,
156
- productId: row.product_id ?? null,
157
- name: row.name,
158
- sku: row.sku ?? null,
159
- quantity: row.quantity ?? 0,
160
- unitPrice: row.unit_price ?? 0,
161
- total: row.total ?? 0,
162
- imageUrl: row.image_url ?? null
163
- };
164
- }
165
- function rowToCustomer(row) {
166
- return {
167
- id: row.id,
168
- tenantId: row.tenant_id,
169
- firstName: row.first_name,
170
- lastName: row.last_name ?? "",
171
- email: row.email ?? null,
172
- phone: row.phone ?? null,
173
- notes: row.notes ?? null,
174
- ordersCount: row.orders_count ?? 0,
175
- totalSpent: row.total_spent ?? 0,
176
- createdAt: row.created_at ?? nowIso(),
177
- updatedAt: row.updated_at ?? row.created_at ?? nowIso()
178
- };
179
- }
180
- function rowToDiscount(row) {
181
- return {
182
- id: row.id,
183
- tenantId: row.tenant_id,
184
- title: row.title,
185
- code: row.code ?? null,
186
- type: row.type,
187
- method: row.method ?? "code",
188
- value: row.value ?? 0,
189
- usageLimit: row.usage_limit ?? null,
190
- oncePerCustomer: row.once_per_customer ?? false,
191
- startsAt: row.starts_at ?? nowIso(),
192
- endsAt: row.ends_at ?? null,
193
- status: row.status ?? "active",
194
- timesUsed: row.times_used ?? 0,
195
- createdAt: row.created_at ?? nowIso(),
196
- updatedAt: row.updated_at ?? row.created_at ?? nowIso()
197
- };
198
- }
199
- function updateOrderPayload(input) {
200
- const updates = {};
201
- if (input.status !== void 0) updates.status = input.status;
202
- if (input.financialStatus !== void 0) updates.financial_status = input.financialStatus;
203
- if (input.fulfillmentStatus !== void 0) updates.fulfillment_status = input.fulfillmentStatus;
204
- if (input.notes !== void 0) updates.notes = input.notes;
205
- return updates;
206
- }
207
- function createFayzShopProvider(options) {
208
- if (options.mode === "broker" || options.apiBaseUrl || options.projectId) {
209
- return createBrokerShopProvider(options);
210
- }
211
- if (!options.supabaseUrl || !options.publishableKey || !options.storeId) {
212
- throw new FayzShopError("Fayz Shop provider requires either broker apiBaseUrl/projectId or legacy supabaseUrl/publishableKey/storeId.", 400);
213
- }
214
- const baseUrl = `${normalizeBaseUrl(options.supabaseUrl)}/rest/v1`;
215
- const fetcher = options.fetcher ?? fetch;
216
- const key = options.publishableKey;
217
- const storeId = options.storeId;
218
- const productMetadataOverlay = buildProductMetadataOverlay(options.productMetadata);
219
- async function request(table, init = {}) {
220
- const query = init.query?.toString();
221
- const response = await fetcher(`${baseUrl}/${table}${query ? `?${query}` : ""}`, {
222
- ...init,
223
- headers: {
224
- apikey: key,
225
- // Declares which store this read is for. Until 0020 tenant isolation was
226
- // a client-side convention (a tenant_id filter the caller could simply
227
- // omit, returning every merchant's catalogue); the RLS policy now reads
228
- // this header, so the scope is enforced server-side.
229
- "x-fayz-store": storeId,
230
- // The shopper's JWT when signed in, the publishable key otherwise. The
231
- // apikey header stays the publishable key either way — Supabase uses it
232
- // to route the project, not to authenticate.
233
- Authorization: `Bearer ${_accessTokenResolver?.() || key}`,
234
- ...init.body ? { "Content-Type": "application/json", Prefer: "return=representation" } : {},
235
- ...init.headers
236
- }
237
- });
238
- const text = await response.text();
239
- let body;
240
- try {
241
- body = text ? JSON.parse(text) : void 0;
242
- } catch {
243
- body = text;
244
- }
245
- if (!response.ok) {
246
- const message = typeof body === "object" && body ? String(body.message ?? body.error ?? `Fayz Shop request failed with status ${response.status}`) : `Fayz Shop request failed with status ${response.status}`;
247
- throw new FayzShopError(message, response.status, body);
248
- }
249
- return body;
250
- }
251
- const tenantQuery = () => {
252
- const query = new URLSearchParams();
253
- query.set("tenant_id", `eq.${storeId}`);
254
- return query;
255
- };
256
- const singleById = (id) => {
257
- const query = tenantQuery();
258
- query.set("id", `eq.${id}`);
259
- query.set("limit", "1");
260
- return query;
261
- };
262
- return {
263
- async listProducts(options2) {
264
- const query = tenantQuery();
265
- query.set("select", "*,images:plg_shop_product_images(*),category:plg_shop_categories(name)");
266
- if (options2?.status) query.set("status", `eq.${options2.status}`);
267
- if (options2?.slug) query.set("slug", `eq.${options2.slug}`);
268
- if (options2?.search) query.set("name", `ilike.*${options2.search}*`);
269
- query.set("order", `${options2?.orderBy ?? "sort_order"}.${options2?.order ?? "asc"}`);
270
- if (options2?.limit) query.set("limit", String(options2.limit));
271
- if (options2?.offset) query.set("offset", String(options2.offset));
272
- const products = (await request("plg_shop_products", { query })).map((row) => rowToProduct(row, productMetadataOverlay));
273
- return options2?.categoryId ? products.filter((product) => product.categoryId === options2.categoryId) : products;
274
- },
275
- async getProduct(id) {
276
- if (!asUuid(id)) return null;
277
- const query = singleById(id);
278
- query.set("select", "*,images:plg_shop_product_images(*),category:plg_shop_categories(name)");
279
- const rows = await request("plg_shop_products", { query });
280
- return rows[0] ? rowToProduct(rows[0], productMetadataOverlay) : null;
281
- },
282
- async createProduct() {
283
- throw new FayzShopError("Product writes require the Fayz admin/broker API.", 501);
284
- },
285
- async updateProduct() {
286
- throw new FayzShopError("Product writes require the Fayz admin/broker API.", 501);
287
- },
288
- async deleteProduct() {
289
- throw new FayzShopError("Product writes require the Fayz admin/broker API.", 501);
290
- },
291
- async uploadProductImage() {
292
- throw new FayzShopError("Product image uploads require the Fayz admin/broker API.", 501);
293
- },
294
- async deleteProductImage() {
295
- throw new FayzShopError("Product image deletes require the Fayz admin/broker API.", 501);
296
- },
297
- async listCategories() {
298
- const productQuery = tenantQuery();
299
- productQuery.set("select", "metadata");
300
- productQuery.set("order", "sort_order.asc");
301
- const products = await request("plg_shop_products", { query: productQuery });
302
- const storeCategories = deriveStoreCategories(products, storeId);
303
- if (storeCategories.length > 0) return storeCategories;
304
- const query = new URLSearchParams();
305
- query.set("select", "*");
306
- query.set("order", "sort_order.asc");
307
- return (await request("plg_shop_categories", { query })).map(rowToCategory);
308
- },
309
- async createCategory() {
310
- throw new FayzShopError("Category writes require the Fayz admin/broker API.", 501);
311
- },
312
- async updateCategory() {
313
- throw new FayzShopError("Category writes require the Fayz admin/broker API.", 501);
314
- },
315
- async deleteCategory() {
316
- throw new FayzShopError("Category deletes require the Fayz admin/broker API.", 501);
317
- },
318
- async listOrders(options2) {
319
- const query = tenantQuery();
320
- query.set("select", "*,items:plg_shop_order_items(*)");
321
- if (options2?.status) query.set("status", `eq.${options2.status}`);
322
- if (options2?.financialStatus) query.set("financial_status", `eq.${options2.financialStatus}`);
323
- if (options2?.fulfillmentStatus) query.set("fulfillment_status", `eq.${options2.fulfillmentStatus}`);
324
- if (options2?.customerId) query.set("customer_id", `eq.${options2.customerId}`);
325
- if (options2?.customerEmail) query.set("customer_email", `eq.${options2.customerEmail}`);
326
- if (options2?.search) query.set("or", `(customer_name.ilike.*${options2.search}*,customer_email.ilike.*${options2.search}*)`);
327
- query.set("order", "created_at.desc");
328
- if (options2?.limit) query.set("limit", String(options2.limit));
329
- if (options2?.offset) query.set("offset", String(options2.offset));
330
- try {
331
- return (await request("plg_shop_orders", { query })).map(rowToOrder);
332
- } catch (err) {
333
- if (!options2?.customerId) throw err;
334
- const rows = await request("rpc/shop_list_orders", {
335
- method: "POST",
336
- body: JSON.stringify({
337
- p_customer_id: options2.customerId,
338
- p_limit: options2.limit ?? 50
339
- })
340
- });
341
- return (rows ?? []).map(rowToOrder);
342
- }
343
- },
344
- async getOrder(id) {
345
- const query = singleById(id);
346
- query.set("select", "*,items:plg_shop_order_items(*)");
347
- let rows = [];
348
- try {
349
- rows = await request("plg_shop_orders", { query });
350
- } catch {
351
- }
352
- if (rows[0]) return rowToOrder(rows[0]);
353
- try {
354
- const row = await request("rpc/shop_get_order", {
355
- method: "POST",
356
- body: JSON.stringify({ p_order_id: id })
357
- });
358
- return row ? rowToOrder(row) : null;
359
- } catch {
360
- return null;
361
- }
362
- },
363
- async confirmPayment(id, reference) {
364
- const row = await request("rpc/shop_confirm_payment", {
365
- method: "POST",
366
- body: JSON.stringify({ p_order_id: id, p_reference: reference ?? null })
367
- });
368
- return row ? rowToOrder(row) : null;
369
- },
370
- async createOrder(input) {
371
- const subtotal = input.items.reduce((sum, item) => sum + item.quantity * item.unitPrice, 0);
372
- const discountTotal = input.discountTotal ?? 0;
373
- const shippingTotal = input.shippingTotal ?? 0;
374
- const total = Math.round((subtotal - discountTotal + shippingTotal) * 100) / 100;
375
- const [order] = await request("plg_shop_orders", {
376
- method: "POST",
377
- body: JSON.stringify({
378
- tenant_id: storeId,
379
- customer_id: input.customerId ?? null,
380
- customer_name: input.customerName ?? null,
381
- customer_email: input.customerEmail ?? null,
382
- currency: input.currency ?? "BRL",
383
- notes: input.notes ?? null,
384
- subtotal,
385
- discount_total: discountTotal,
386
- shipping_total: shippingTotal,
387
- discount_code: input.discountCode ?? null,
388
- total,
389
- status: "open",
390
- financial_status: "pending",
391
- fulfillment_status: "unfulfilled"
392
- })
393
- });
394
- if (!order) throw new FayzShopError("Order insert did not return a row.", 500);
395
- if (input.items.length) {
396
- await request("plg_shop_order_items", {
397
- method: "POST",
398
- body: JSON.stringify(input.items.map((item) => ({
399
- order_id: order.id,
400
- product_id: asUuid(item.productId),
401
- name: item.name,
402
- sku: item.sku ?? null,
403
- quantity: item.quantity,
404
- unit_price: item.unitPrice,
405
- total: item.quantity * item.unitPrice,
406
- image_url: item.imageUrl ?? null
407
- })))
408
- });
409
- }
410
- return this.getOrder(order.id);
411
- },
412
- async updateOrder(id, input) {
413
- await request("plg_shop_orders", {
414
- method: "PATCH",
415
- query: singleById(id),
416
- body: JSON.stringify(updateOrderPayload(input))
417
- });
418
- return this.getOrder(id);
419
- },
420
- async placeOrder(input) {
421
- const orderId = await request("rpc/shop_place_order", {
422
- method: "POST",
423
- body: JSON.stringify({
424
- p_tenant_id: input.tenantId ?? storeId,
425
- p_items: input.items.map((line) => ({
426
- product_id: line.productId,
427
- quantity: line.quantity,
428
- options_label: line.optionsLabel ?? null
429
- })),
430
- p_customer_id: asUuid(input.customerId ?? void 0),
431
- p_customer_name: input.customer?.name ?? null,
432
- p_customer_email: input.customer?.email ?? null,
433
- p_currency: input.currency ?? "BRL",
434
- p_discount_code: input.discountCode ?? null,
435
- p_shipping_total: input.shippingTotal ?? 0,
436
- // snake_case keys on purpose: the RPC freezes this jsonb onto the
437
- // order and public.addresses uses these exact column names.
438
- p_shipping_address: input.shippingAddress ? {
439
- postal_code: input.shippingAddress.postalCode,
440
- street: input.shippingAddress.street,
441
- number: input.shippingAddress.number ?? null,
442
- complement: input.shippingAddress.complement ?? null,
443
- district: input.shippingAddress.district ?? null,
444
- city: input.shippingAddress.city,
445
- state: input.shippingAddress.state,
446
- country: input.shippingAddress.country ?? "BR",
447
- recipient: input.shippingAddress.recipient ?? null,
448
- phone: input.shippingAddress.phone ?? null,
449
- label: input.shippingAddress.label ?? null
450
- } : null,
451
- p_payment_method: input.paymentMethod ?? null,
452
- p_notes: input.notes ?? null
453
- })
454
- });
455
- const order = await this.getOrder(orderId);
456
- if (!order) throw new FayzShopError("Order was placed but could not be read back.", 500);
457
- return order;
458
- },
459
- async listCustomers(options2) {
460
- const query = tenantQuery();
461
- query.set("select", "*");
462
- query.set("order", "first_name.asc");
463
- if (options2?.search) query.set("or", `(first_name.ilike.*${options2.search}*,last_name.ilike.*${options2.search}*,email.ilike.*${options2.search}*)`);
464
- if (options2?.limit) query.set("limit", String(options2.limit));
465
- if (options2?.offset) query.set("offset", String(options2.offset));
466
- return (await request("plg_shop_customers", { query })).map(rowToCustomer);
467
- },
468
- async getCustomer(id) {
469
- const rows = await request("plg_shop_customers", { query: singleById(id) });
470
- return rows[0] ? rowToCustomer(rows[0]) : null;
471
- },
472
- async resolveCustomer(input) {
473
- const row = await request("rpc/shop_resolve_customer", {
474
- method: "POST",
475
- body: JSON.stringify({
476
- p_tenant_id: storeId,
477
- p_email: input.email,
478
- p_name: input.name ?? null
479
- })
480
- });
481
- const customer = Array.isArray(row) ? row[0] : row;
482
- if (!customer) throw new FayzShopError("shop_resolve_customer returned no row.", 500);
483
- return rowToCustomer(customer);
484
- },
485
- async quoteShipping(postalCode, subtotal) {
486
- const digits = (postalCode || "").replace(/\D/g, "");
487
- if (digits.length !== 8) return [];
488
- const rows = await request("rpc/shop_quote_shipping", {
489
- method: "POST",
490
- body: JSON.stringify({
491
- p_tenant_id: storeId,
492
- p_postal_code: digits,
493
- p_subtotal: subtotal
494
- })
495
- });
496
- return (rows ?? []).map((row) => ({
497
- zoneId: row.zone_id,
498
- name: row.name,
499
- carrier: row.carrier ?? void 0,
500
- rate: Number(row.rate ?? 0),
501
- baseRate: Number(row.base_rate ?? row.rate ?? 0),
502
- freeAbove: row.free_above == null ? null : Number(row.free_above),
503
- etaMinDays: row.eta_min_days ?? void 0,
504
- etaMaxDays: row.eta_max_days ?? void 0,
505
- free: Boolean(row.free)
506
- }));
507
- },
508
- async listCustomerAddresses(customerId) {
509
- if (!asUuid(customerId)) return [];
510
- const query = new URLSearchParams();
511
- query.set("select", "id,label,recipient,phone,postal_code,street,number,complement,district,city,state,country,is_default");
512
- query.set("owner_type", "eq.shop_customer");
513
- query.set("owner_id", `eq.${customerId}`);
514
- query.set("order", "is_default.desc,created_at.desc");
515
- const rows = await request("addresses", { query }).catch(() => []);
516
- return rows.map((row) => ({
517
- id: row.id,
518
- label: row.label ?? void 0,
519
- recipient: row.recipient ?? void 0,
520
- phone: row.phone ?? void 0,
521
- postalCode: row.postal_code ?? "",
522
- street: row.street ?? "",
523
- number: row.number ?? void 0,
524
- complement: row.complement ?? void 0,
525
- district: row.district ?? void 0,
526
- city: row.city ?? "",
527
- state: row.state ?? "",
528
- country: row.country ?? void 0,
529
- isDefault: row.is_default ?? false
530
- }));
531
- },
532
- async createCustomer(input) {
533
- const [customer] = await request("plg_shop_customers", {
534
- method: "POST",
535
- body: JSON.stringify({
536
- tenant_id: storeId,
537
- first_name: input.firstName,
538
- last_name: input.lastName ?? "",
539
- email: input.email ?? null,
540
- phone: input.phone ?? null,
541
- notes: input.notes ?? null
542
- })
543
- });
544
- if (!customer) throw new FayzShopError("Customer insert did not return a row.", 500);
545
- return rowToCustomer(customer);
546
- },
547
- async updateCustomer(id, input) {
548
- const updates = {};
549
- if (input.firstName !== void 0) updates.first_name = input.firstName;
550
- if (input.lastName !== void 0) updates.last_name = input.lastName;
551
- if (input.email !== void 0) updates.email = input.email;
552
- if (input.phone !== void 0) updates.phone = input.phone;
553
- if (input.notes !== void 0) updates.notes = input.notes;
554
- const [customer] = await request("plg_shop_customers", {
555
- method: "PATCH",
556
- query: singleById(id),
557
- body: JSON.stringify(updates)
558
- });
559
- if (!customer) throw new FayzShopError("Customer update did not return a row.", 500);
560
- return rowToCustomer(customer);
561
- },
562
- async deleteCustomer(id) {
563
- await request("plg_shop_customers", { method: "DELETE", query: singleById(id) });
564
- },
565
- async listDiscounts(options2) {
566
- const query = tenantQuery();
567
- query.set("select", "*");
568
- query.set("order", "created_at.desc");
569
- if (options2?.status) query.set("status", `eq.${options2.status}`);
570
- if (options2?.type) query.set("type", `eq.${options2.type}`);
571
- if (options2?.search) query.set("title", `ilike.*${options2.search}*`);
572
- if (options2?.limit) query.set("limit", String(options2.limit));
573
- if (options2?.offset) query.set("offset", String(options2.offset));
574
- return (await request("plg_shop_discounts", { query })).map(rowToDiscount);
575
- },
576
- async getDiscount(id) {
577
- const rows = await request("plg_shop_discounts", { query: singleById(id) });
578
- return rows[0] ? rowToDiscount(rows[0]) : null;
579
- },
580
- async createDiscount() {
581
- throw new FayzShopError("Discount writes require the Fayz admin/broker API.", 501);
582
- },
583
- async updateDiscount() {
584
- throw new FayzShopError("Discount writes require the Fayz admin/broker API.", 501);
585
- },
586
- async deleteDiscount() {
587
- throw new FayzShopError("Discount deletes require the Fayz admin/broker API.", 501);
588
- }
589
- };
590
- }
591
- function appendQuery(url, values) {
592
- const query = new URLSearchParams();
593
- for (const [key, value] of Object.entries(values)) {
594
- if (value !== void 0) query.set(key, String(value));
595
- }
596
- const serialized = query.toString();
597
- return serialized ? `${url}?${serialized}` : url;
598
- }
599
- function normalizeBrokerProduct(product, overlay) {
600
- const category = product.category && typeof product.category === "object" ? product.category : null;
601
- const row = {
602
- id: product.id,
603
- tenant_id: product.tenantId,
604
- name: product.name,
605
- slug: product.slug,
606
- description: product.description,
607
- price: product.price,
608
- compare_at_price: product.compareAtPrice,
609
- currency: product.currency,
610
- status: product.status,
611
- inventory_count: product.inventoryCount,
612
- sku: product.sku,
613
- sort_order: product.sortOrder,
614
- metadata: product.metadata,
615
- images: Array.isArray(product.images) ? product.images.map((image) => {
616
- const row2 = image;
617
- return {
618
- id: String(row2.id ?? ""),
619
- product_id: String(row2.productId ?? product.id ?? ""),
620
- url: String(row2.url ?? ""),
621
- alt_text: row2.altText ?? null,
622
- sort_order: row2.sortOrder ?? 0,
623
- is_primary: row2.isPrimary ?? false,
624
- created_at: row2.createdAt ?? null
625
- };
626
- }) : [],
627
- category_id: product.categoryId ?? category?.id,
628
- category: category ? { name: category.name } : null,
629
- is_physical: product.isPhysical,
630
- weight: product.weight,
631
- weight_unit: product.weightUnit,
632
- created_at: product.createdAt,
633
- updated_at: product.updatedAt
634
- };
635
- return rowToProduct(row, overlay);
636
- }
637
- function normalizeBrokerCategory(category) {
638
- return {
639
- id: category.id,
640
- tenantId: category.tenantId ?? "global",
641
- name: category.name,
642
- slug: category.slug ?? slugify(category.name),
643
- description: category.description ?? null,
644
- parentId: category.parentId ?? null,
645
- sortOrder: category.sortOrder ?? 0,
646
- imageUrl: category.imageUrl ?? null,
647
- createdAt: category.createdAt ?? nowIso()
648
- };
649
- }
650
- function createBrokerShopProvider(options) {
651
- if (!options.apiBaseUrl || !options.projectId) {
652
- throw new FayzShopError("Fayz Shop broker mode requires apiBaseUrl and projectId.", 400);
653
- }
654
- const fetcher = options.fetcher ?? fetch;
655
- const apiBaseUrl = normalizeBaseUrl(options.apiBaseUrl);
656
- const projectId = encodeURIComponent(options.projectId);
657
- const productMetadataOverlay = buildProductMetadataOverlay(options.productMetadata);
658
- async function request(path, init = {}) {
659
- const response = await fetcher(`${apiBaseUrl}/public/projects/${projectId}/shop${path}`, init);
660
- const text = await response.text();
661
- let body;
662
- try {
663
- body = text ? JSON.parse(text) : void 0;
664
- } catch {
665
- body = text;
666
- }
667
- if (!response.ok) {
668
- const message = typeof body === "object" && body ? String(body.message ?? body.error ?? `Fayz Shop broker request failed with status ${response.status}`) : `Fayz Shop broker request failed with status ${response.status}`;
669
- throw new FayzShopError(message, response.status, body);
670
- }
671
- return body;
672
- }
673
- return {
674
- async listProducts(options2) {
675
- if (options2?.slug) {
676
- const product = await this.getProduct(options2.slug);
677
- return product ? [product] : [];
678
- }
679
- const response = await request(appendQuery("/products", {
680
- status: options2?.status,
681
- categoryId: options2?.categoryId,
682
- search: options2?.search,
683
- limit: options2?.limit,
684
- offset: options2?.offset,
685
- orderBy: options2?.orderBy,
686
- order: options2?.order
687
- }));
688
- return (response.products ?? []).map((product) => normalizeBrokerProduct(product, productMetadataOverlay));
689
- },
690
- async getProduct(id) {
691
- const response = await request(`/products/${encodeURIComponent(id)}`);
692
- return response.product ? normalizeBrokerProduct(response.product, productMetadataOverlay) : null;
693
- },
694
- async createProduct() {
695
- throw new FayzShopError("Product writes require the Fayz admin/broker API.", 501);
696
- },
697
- async updateProduct() {
698
- throw new FayzShopError("Product writes require the Fayz admin/broker API.", 501);
699
- },
700
- async deleteProduct() {
701
- throw new FayzShopError("Product writes require the Fayz admin/broker API.", 501);
702
- },
703
- async uploadProductImage() {
704
- throw new FayzShopError("Product image uploads require the Fayz admin/broker API.", 501);
705
- },
706
- async deleteProductImage() {
707
- throw new FayzShopError("Product image deletes require the Fayz admin/broker API.", 501);
708
- },
709
- async listCategories() {
710
- const response = await request("/categories");
711
- return (response.categories ?? []).map(normalizeBrokerCategory);
712
- },
713
- async createCategory() {
714
- throw new FayzShopError("Category writes require the Fayz admin/broker API.", 501);
715
- },
716
- async updateCategory() {
717
- throw new FayzShopError("Category writes require the Fayz admin/broker API.", 501);
718
- },
719
- async deleteCategory() {
720
- throw new FayzShopError("Category deletes require the Fayz admin/broker API.", 501);
721
- },
722
- async listOrders() {
723
- throw new FayzShopError("Order reads require the Fayz admin/broker API.", 501);
724
- },
725
- async getOrder() {
726
- throw new FayzShopError("Order reads require the Fayz admin/broker API.", 501);
727
- },
728
- async createOrder() {
729
- throw new FayzShopError("Order writes require the Fayz admin/broker API.", 501);
730
- },
731
- async updateOrder() {
732
- throw new FayzShopError("Order writes require the Fayz admin/broker API.", 501);
733
- },
734
- async placeOrder() {
735
- throw new FayzShopError("Order placement requires the Fayz admin/broker API.", 501);
736
- },
737
- async listCustomers() {
738
- throw new FayzShopError("Customer reads require the Fayz admin/broker API.", 501);
739
- },
740
- async getCustomer() {
741
- throw new FayzShopError("Customer reads require the Fayz admin/broker API.", 501);
742
- },
743
- async createCustomer() {
744
- throw new FayzShopError("Customer writes require the Fayz admin/broker API.", 501);
745
- },
746
- async updateCustomer() {
747
- throw new FayzShopError("Customer writes require the Fayz admin/broker API.", 501);
748
- },
749
- async deleteCustomer() {
750
- throw new FayzShopError("Customer writes require the Fayz admin/broker API.", 501);
751
- },
752
- async listDiscounts() {
753
- throw new FayzShopError("Discount reads require the Fayz admin/broker API.", 501);
754
- },
755
- async getDiscount() {
756
- throw new FayzShopError("Discount reads require the Fayz admin/broker API.", 501);
757
- },
758
- async createDiscount() {
759
- throw new FayzShopError("Discount writes require the Fayz admin/broker API.", 501);
760
- },
761
- async updateDiscount() {
762
- throw new FayzShopError("Discount writes require the Fayz admin/broker API.", 501);
763
- },
764
- async deleteDiscount() {
765
- throw new FayzShopError("Discount deletes require the Fayz admin/broker API.", 501);
766
- }
767
- };
768
- }
769
-
770
- exports.FayzShopError = FayzShopError;
771
- exports.createFayzShopProvider = createFayzShopProvider;
772
- exports.setShopAccessTokenResolver = setShopAccessTokenResolver;
773
- //# sourceMappingURL=chunk-746EA3BV.cjs.map
774
- //# sourceMappingURL=chunk-746EA3BV.cjs.map