@requiply/nuxt 0.0.0-stage → 0.1.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 (49) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +644 -2
  4. package/dist/module.d.mts +16 -0
  5. package/dist/module.json +12 -0
  6. package/dist/module.mjs +83 -0
  7. package/dist/runtime/app/components/RequiplyAccountLinks.d.ts +53 -0
  8. package/dist/runtime/app/components/RequiplyAccountLinks.js +13 -0
  9. package/dist/runtime/app/components/RequiplyBookButton.d.ts +37 -0
  10. package/dist/runtime/app/components/RequiplyBookButton.js +6 -0
  11. package/dist/runtime/app/components/RequiplyBundle.d.ts +21 -0
  12. package/dist/runtime/app/components/RequiplyBundle.js +4 -0
  13. package/dist/runtime/app/components/RequiplyCallButton.d.ts +35 -0
  14. package/dist/runtime/app/components/RequiplyCallButton.js +6 -0
  15. package/dist/runtime/app/components/RequiplyCartButton.d.ts +24 -0
  16. package/dist/runtime/app/components/RequiplyCartButton.js +4 -0
  17. package/dist/runtime/app/components/RequiplyDatePicker.d.ts +12 -0
  18. package/dist/runtime/app/components/RequiplyDatePicker.js +2 -0
  19. package/dist/runtime/app/components/RequiplyPortalButton.d.ts +34 -0
  20. package/dist/runtime/app/components/RequiplyPortalButton.js +6 -0
  21. package/dist/runtime/app/components/RequiplyPriceTiers.d.ts +21 -0
  22. package/dist/runtime/app/components/RequiplyPriceTiers.js +4 -0
  23. package/dist/runtime/app/components/RequiplyProduct.d.ts +37 -0
  24. package/dist/runtime/app/components/RequiplyProduct.js +26 -0
  25. package/dist/runtime/app/components/RequiplyProductCard.d.ts +21 -0
  26. package/dist/runtime/app/components/RequiplyProductCard.js +4 -0
  27. package/dist/runtime/app/components/RequiplyProductList.d.ts +70 -0
  28. package/dist/runtime/app/components/RequiplyProductList.js +19 -0
  29. package/dist/runtime/app/composables/useRequiply.d.ts +12 -0
  30. package/dist/runtime/app/composables/useRequiply.js +12 -0
  31. package/dist/runtime/app/composables/useRequiplyEmbed.d.ts +43 -0
  32. package/dist/runtime/app/composables/useRequiplyEmbed.js +54 -0
  33. package/dist/runtime/app/composables/useRequiplyProduct.d.ts +40 -0
  34. package/dist/runtime/app/composables/useRequiplyProduct.js +92 -0
  35. package/dist/runtime/app/embed.d.ts +79 -0
  36. package/dist/runtime/app/embed.js +75 -0
  37. package/dist/runtime/app/placeholder.d.ts +26 -0
  38. package/dist/runtime/app/placeholder.js +29 -0
  39. package/dist/runtime/app/plugins/requiply.d.ts +2 -0
  40. package/dist/runtime/app/plugins/requiply.js +46 -0
  41. package/dist/runtime/requiply.d.ts +2 -0
  42. package/dist/runtime/requiply.js +1 -0
  43. package/dist/runtime/server/tsconfig.json +3 -0
  44. package/dist/runtime/server/utils/requiply.d.ts +16 -0
  45. package/dist/runtime/server/utils/requiply.js +22 -0
  46. package/dist/runtime/types.d.ts +221 -0
  47. package/dist/runtime/types.js +0 -0
  48. package/dist/types.d.mts +9 -0
  49. package/package.json +78 -4
@@ -0,0 +1,54 @@
1
+ import { computed, readonly } from "vue";
2
+ import { useState } from "#app";
3
+ import { embedRuntime, emptyCart, rescanEmbed } from "../embed.js";
4
+ export function useRequiplyEmbed() {
5
+ const ready = useState("requiply:embed-ready", () => false);
6
+ const cart = useState("requiply:embed-cart", emptyCart);
7
+ const whenReady = () => new Promise((resolve) => {
8
+ const runtime = embedRuntime();
9
+ if (runtime) return resolve(runtime);
10
+ if (typeof document === "undefined") return;
11
+ document.addEventListener("requiply:ready", () => {
12
+ const booted = embedRuntime();
13
+ if (booted) resolve(booted);
14
+ }, { once: true });
15
+ });
16
+ const withRuntime = (action) => {
17
+ const runtime = embedRuntime();
18
+ if (runtime) action(runtime);
19
+ };
20
+ return {
21
+ ready: readonly(ready),
22
+ cart: readonly(cart),
23
+ count: computed(() => cart.value.count),
24
+ async addToCart(item, quantity = 1) {
25
+ const runtime = embedRuntime();
26
+ if (!runtime || !item) return false;
27
+ let product = runtime.itemById(item) ?? runtime.item(item);
28
+ if (!product) {
29
+ await runtime.loadBySlugs([item]);
30
+ product = runtime.item(item);
31
+ }
32
+ if (!product && /^[0-9a-f-]{36}$/i.test(item)) {
33
+ await runtime.readCatalog({ ids: [item], includeSale: true });
34
+ product = runtime.itemById(item);
35
+ }
36
+ if (!product) return false;
37
+ runtime.requestAdd(product.id, quantity);
38
+ return true;
39
+ },
40
+ setQuantity: (groupId, quantity) => withRuntime((runtime) => runtime.setQuantity(groupId, quantity)),
41
+ remove: (groupId) => withRuntime((runtime) => runtime.remove(groupId)),
42
+ clear: () => withRuntime((runtime) => runtime.clear()),
43
+ setDates: (startDate, endDate) => withRuntime((runtime) => runtime.setDates(startDate, endDate)),
44
+ openCart: () => withRuntime((runtime) => runtime.ui.openCart?.()),
45
+ openDatePicker: () => withRuntime((runtime) => runtime.ui.openDatePicker?.()),
46
+ openCall: () => withRuntime((runtime) => runtime.ui.openCall?.()),
47
+ async checkout() {
48
+ const runtime = embedRuntime();
49
+ if (runtime) await runtime.openPortal();
50
+ },
51
+ whenReady,
52
+ rescan: rescanEmbed
53
+ };
54
+ }
@@ -0,0 +1,40 @@
1
+ import { type ComputedRef, type MaybeRefOrGetter, type Ref } from 'vue';
2
+ import type { RequiplyProduct } from '../../types.js';
3
+ export interface UseRequiplyProduct {
4
+ /**
5
+ * The product: server-rendered from the booking portal's public catalog, then the widgets'
6
+ * live copy once they load, with availability for the chosen dates. Null when unknown or
7
+ * hidden from clients.
8
+ */
9
+ product: ComputedRef<RequiplyProduct | null>;
10
+ /** True while the server-side read is running. */
11
+ pending: Ref<boolean>;
12
+ /** True once the widgets have loaded; the values below are only live from then on. */
13
+ ready: Readonly<Ref<boolean>>;
14
+ /** The base price formatted in the organization's currency and the visitor's language; null before `ready`. */
15
+ price: ComputedRef<string | null>;
16
+ /** Whether the visitor has chosen rental dates. */
17
+ hasDates: ComputedRef<boolean>;
18
+ /**
19
+ * Units that can still be booked: free units for the chosen dates (stock for products for
20
+ * sale, all units before dates are chosen). Null when unknown or unlimited.
21
+ */
22
+ available: ComputedRef<number | null>;
23
+ /** True when the dates are chosen and none is free. */
24
+ soldOut: ComputedRef<boolean>;
25
+ /** Units of this product in the cart. */
26
+ inCart: ComputedRef<number>;
27
+ /** Adds like "Add to booking": asks for dates first when bookings start from dates, then opens the cart. */
28
+ add(quantity?: number): Promise<boolean>;
29
+ /** Sets the quantity in the cart; 0 removes it. */
30
+ setQuantity(quantity: number): void;
31
+ remove(): void;
32
+ }
33
+ /**
34
+ * Everything to build your own product card or page in Vue while the widgets keep handling
35
+ * dates, the cart and checkout. `item` is the product slug or id.
36
+ *
37
+ * @example
38
+ * const { product, price, available, inCart, add } = useRequiplyProduct(() => route.params.slug as string)
39
+ */
40
+ export declare function useRequiplyProduct(item: MaybeRefOrGetter<string>): UseRequiplyProduct;
@@ -0,0 +1,92 @@
1
+ import { computed, toValue, watch } from "vue";
2
+ import { useAsyncData, useNuxtApp, useRuntimeConfig, useState } from "#app";
3
+ import { embedRuntime, loadSlugs } from "../embed.js";
4
+ import { useRequiplyEmbed } from "./useRequiplyEmbed.js";
5
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6
+ const CHUNK = 100;
7
+ function fetchCatalogProduct(app, config, key) {
8
+ let batch = app._requiplyCatalogBatch;
9
+ if (!batch) {
10
+ const created = { slugs: /* @__PURE__ */ new Set(), ids: /* @__PURE__ */ new Set(), result: Promise.resolve([]) };
11
+ created.result = Promise.resolve().then(async () => {
12
+ app._requiplyCatalogBatch = void 0;
13
+ const wanted = [...[...created.slugs].map((value) => ["slugs", value]), ...[...created.ids].map((value) => ["ids", value])];
14
+ const url = `${config.apiUrl.replace(/\/+$/, "")}/api/portal/v1/orgs/${encodeURIComponent(config.org)}/catalog`;
15
+ const pages = await Promise.all(Array.from({ length: Math.ceil(wanted.length / CHUNK) }, (_, index) => {
16
+ const chunk = wanted.slice(index * CHUNK, (index + 1) * CHUNK);
17
+ const slugs = chunk.filter(([kind]) => kind === "slugs").map(([, value]) => value);
18
+ const ids = chunk.filter(([kind]) => kind === "ids").map(([, value]) => value);
19
+ return $fetch(url, {
20
+ query: { ...slugs.length ? { slugs: slugs.join(",") } : {}, ...ids.length ? { ids: ids.join(",") } : {}, includeSale: "1" }
21
+ });
22
+ }));
23
+ return pages.flatMap((page) => page.items);
24
+ });
25
+ app._requiplyCatalogBatch = created;
26
+ batch = created;
27
+ }
28
+ const byId = UUID.test(key);
29
+ (byId ? batch.ids : batch.slugs).add(key);
30
+ return batch.result.then((items) => items.find((product) => (byId ? product.id : product.slug) === key) ?? null);
31
+ }
32
+ export function useRequiplyProduct(item) {
33
+ const config = useRuntimeConfig().public.requiply;
34
+ const app = useNuxtApp();
35
+ const embed = useRequiplyEmbed();
36
+ const version = useState("requiply:embed-version", () => 0);
37
+ const key = computed(() => toValue(item) ?? "");
38
+ const { data, pending } = useAsyncData(
39
+ () => `requiply-product:${key.value}`,
40
+ () => key.value && config.org ? fetchCatalogProduct(app, config, key.value) : Promise.resolve(null),
41
+ { default: () => null }
42
+ );
43
+ const live = computed(() => {
44
+ void version.value;
45
+ const runtime2 = embed.ready.value ? embedRuntime() : null;
46
+ if (!runtime2 || !key.value) return null;
47
+ return UUID.test(key.value) ? runtime2.itemById(key.value) : runtime2.item(key.value);
48
+ });
49
+ if (import.meta.client) {
50
+ watch([embed.ready, key], async ([ready, current]) => {
51
+ const runtime2 = ready ? embedRuntime() : null;
52
+ if (!runtime2 || !current || UUID.test(current) || runtime2.item(current)) return;
53
+ await loadSlugs(runtime2, [current]);
54
+ }, { immediate: true });
55
+ }
56
+ const product = computed(() => live.value ?? data.value);
57
+ const runtime = () => embed.ready.value ? embedRuntime() : null;
58
+ const available = computed(() => {
59
+ void version.value;
60
+ const current = live.value;
61
+ const rt = runtime();
62
+ return current && rt ? rt.maxQuantity(current.id) : null;
63
+ });
64
+ const hasDates = computed(() => Boolean(embed.cart.value.startDate && embed.cart.value.endDate));
65
+ const inCart = computed(() => {
66
+ const id = product.value?.id;
67
+ if (!id) return 0;
68
+ const cart = embed.cart.value;
69
+ return cart.items.find((line) => line.groupId === id)?.quantity ?? cart.saleLines.find((line) => line.saleItemId === id)?.quantity ?? 0;
70
+ });
71
+ return {
72
+ product,
73
+ pending,
74
+ ready: embed.ready,
75
+ price: computed(() => {
76
+ void version.value;
77
+ const rt = runtime();
78
+ return rt && product.value ? rt.price(product.value.price) : null;
79
+ }),
80
+ hasDates,
81
+ available,
82
+ soldOut: computed(() => (product.value?.kind === "sale" || hasDates.value) && available.value === 0),
83
+ inCart,
84
+ add: (quantity = 1) => product.value ? embed.addToCart(product.value.id, quantity) : Promise.resolve(false),
85
+ setQuantity: (quantity) => {
86
+ if (product.value) embed.setQuantity(product.value.id, quantity);
87
+ },
88
+ remove: () => {
89
+ if (product.value) embed.remove(product.value.id);
90
+ }
91
+ };
92
+ }
@@ -0,0 +1,79 @@
1
+ import type { RequiplyCart, RequiplyEmbedOptions, RequiplyProduct, RequiplyPublicRuntimeConfig, RequiplyTheme } from '../types.js';
2
+ /**
3
+ * The parts of the widget runtime (`window.RequiplyEmbed.runtime`, served by the booking
4
+ * portal) the module relies on. Kept narrow and checked before use, since the runtime is
5
+ * loaded from the portal and may be newer than this module.
6
+ */
7
+ export interface EmbedRuntime {
8
+ cart: {
9
+ items: Array<{
10
+ groupId: string;
11
+ quantity: number;
12
+ }>;
13
+ bundles: Array<{
14
+ bundleId: string;
15
+ quantity: number;
16
+ choices?: string[];
17
+ }>;
18
+ saleLines: Array<{
19
+ groupId: string;
20
+ quantity: number;
21
+ }>;
22
+ startDate: string | null;
23
+ endDate: string | null;
24
+ };
25
+ readonly count: number;
26
+ readonly selectedServiceIds: string[];
27
+ readonly hasDates: boolean;
28
+ readonly ui: {
29
+ openCart: (() => void) | null;
30
+ openDatePicker: (() => void) | null;
31
+ openCall: (() => void) | null;
32
+ };
33
+ subscribe(listener: () => void): () => void;
34
+ item(slug: string): RequiplyProduct | null;
35
+ itemById(id: string): RequiplyProduct | null;
36
+ line(groupId: string): {
37
+ groupId: string;
38
+ quantity: number;
39
+ } | null;
40
+ maxQuantity(groupId: string): number | null;
41
+ availabilityKnown(item: RequiplyProduct): boolean;
42
+ price(amount: number): string;
43
+ loadBySlugs(slugs: string[]): Promise<void>;
44
+ readCatalog(params: {
45
+ ids?: string[];
46
+ includeSale?: boolean;
47
+ }): Promise<unknown[]>;
48
+ requestAdd(groupId: string, quantity?: number): void;
49
+ setQuantity(groupId: string, quantity: number): void;
50
+ remove(groupId: string): void;
51
+ clear(): void;
52
+ setDates(startDate: string | null, endDate: string | null): void;
53
+ openPortal(): Promise<void>;
54
+ }
55
+ /** The widget runtime once it has booted, else null. */
56
+ export declare function embedRuntime(): EmbedRuntime | null;
57
+ /**
58
+ * Loads products into the runtime by slug, batching every call made in the same tick into
59
+ * one catalog request, as the runtime does for the placeholders of a page.
60
+ */
61
+ export declare function loadSlugs(runtime: EmbedRuntime, slugs: string[]): Promise<void>;
62
+ /** Asks the widget runtime to mount placeholders added since its last look. */
63
+ export declare function rescanEmbed(): void;
64
+ /** An empty cart, the state before the widgets boot and on the server. */
65
+ export declare function emptyCart(): RequiplyCart;
66
+ /** A plain copy of the runtime's cart, safe to keep in Vue state. */
67
+ export declare function cartSnapshot(runtime: EmbedRuntime): RequiplyCart;
68
+ /**
69
+ * The theme as a `:root` rule of `--rq-*` variables, or null without tokens. Values are
70
+ * written as given; characters that could end the rule are dropped.
71
+ */
72
+ export declare function themeCss(theme: RequiplyTheme | undefined): string | null;
73
+ /** The script URL of the widget runtime. */
74
+ export declare function embedScriptUrl(config: Pick<RequiplyPublicRuntimeConfig, 'portalUrl'>, embed: RequiplyEmbedOptions): string;
75
+ /**
76
+ * The `data-*` attributes the widget runtime reads from its script tag. Only options that
77
+ * were set are written, so the organization's own settings apply to the rest.
78
+ */
79
+ export declare function embedScriptAttributes(config: RequiplyPublicRuntimeConfig, embed: RequiplyEmbedOptions): Record<string, string>;
@@ -0,0 +1,75 @@
1
+ export function embedRuntime() {
2
+ if (typeof window === "undefined") return null;
3
+ return window.RequiplyEmbed?.runtime ?? null;
4
+ }
5
+ const pendingSlugs = /* @__PURE__ */ new Set();
6
+ let flushing = null;
7
+ export function loadSlugs(runtime, slugs) {
8
+ for (const slug of slugs) if (slug) pendingSlugs.add(slug);
9
+ flushing ??= Promise.resolve().then(async () => {
10
+ const batch = [...pendingSlugs];
11
+ pendingSlugs.clear();
12
+ flushing = null;
13
+ if (batch.length) await runtime.loadBySlugs(batch);
14
+ });
15
+ return flushing;
16
+ }
17
+ export function rescanEmbed() {
18
+ if (typeof window === "undefined") return;
19
+ window.RequiplyEmbed?.scan?.();
20
+ }
21
+ export function emptyCart() {
22
+ return { items: [], bundles: [], saleLines: [], serviceIds: [], startDate: null, endDate: null, count: 0 };
23
+ }
24
+ export function cartSnapshot(runtime) {
25
+ const { cart } = runtime;
26
+ return {
27
+ items: cart.items.map((line) => ({ groupId: line.groupId, quantity: line.quantity })),
28
+ bundles: cart.bundles.map((line) => ({
29
+ bundleId: line.bundleId,
30
+ quantity: line.quantity,
31
+ ...line.choices ? { choices: [...line.choices] } : {}
32
+ })),
33
+ saleLines: cart.saleLines.map((line) => ({ saleItemId: line.groupId, quantity: line.quantity })),
34
+ serviceIds: [...runtime.selectedServiceIds ?? []],
35
+ startDate: cart.startDate,
36
+ endDate: cart.endDate,
37
+ count: runtime.count
38
+ };
39
+ }
40
+ export function themeCss(theme) {
41
+ const declarations = Object.entries(theme ?? {}).filter((entry) => typeof entry[1] === "string" && entry[1].trim() !== "").map(([token, value]) => `--rq-${token.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`).replace(/[^a-z0-9-]/g, "")}: ${value.replace(/[;{}<>]/g, "").trim()};`);
42
+ return declarations.length ? `:root { ${declarations.join(" ")} }` : null;
43
+ }
44
+ export function embedScriptUrl(config, embed) {
45
+ return embed.scriptUrl || `${config.portalUrl.replace(/\/+$/, "")}/embed/v1/requiply-embed.js`;
46
+ }
47
+ export function embedScriptAttributes(config, embed) {
48
+ const attrs = {
49
+ "data-org": config.org,
50
+ "data-portal": config.portalUrl.replace(/\/+$/, ""),
51
+ "data-api": config.apiUrl.replace(/\/+$/, ""),
52
+ "data-locale": embed.locale,
53
+ "data-color": embed.color,
54
+ "data-corners": embed.corners,
55
+ "data-return-url": embed.returnUrl,
56
+ "data-site-url": embed.siteUrl,
57
+ "data-cart": embed.floatingCart === void 0 ? void 0 : String(embed.floatingCart),
58
+ "data-cart-position": embed.cartPosition,
59
+ "data-currency-display": embed.currencyDisplay,
60
+ "data-start-from": embed.startFrom,
61
+ "data-phones": embed.phones?.length ? JSON.stringify(embed.phones) : void 0,
62
+ "data-call": embed.callButton,
63
+ "data-call-float": embed.callFloating,
64
+ "data-call-note": embed.callNote,
65
+ "data-call-hours": embed.callHours === void 0 ? void 0 : String(embed.callHours),
66
+ // Nuxt sites get a calendar on the cart ("your booking" is a period) and a plus on
67
+ // "Add to booking"; the widget runtime's own default is a cart on both.
68
+ "data-cart-icon": embed.cartIcon ?? "calendar",
69
+ "data-button-icon": embed.buttonIcon ?? "plus",
70
+ "data-icon-style": embed.iconStyle,
71
+ "data-messages": embed.messages && Object.keys(embed.messages).length ? JSON.stringify(embed.messages) : void 0,
72
+ "data-css": embed.css?.trim() || void 0
73
+ };
74
+ return Object.fromEntries(Object.entries(attrs).filter((entry) => typeof entry[1] === "string" && entry[1] !== ""));
75
+ }
@@ -0,0 +1,26 @@
1
+ import { type ComponentObjectPropsOptions, type ExtractPropTypes, type SlotsType, type VNode } from 'vue';
2
+ type Attrs = Record<string, string | number | boolean | null | undefined>;
3
+ /**
4
+ * Defines a component that renders one booking widget placeholder, an element with the
5
+ * widget's class and `data-*` options that the widget runtime fills in (inside a shadow
6
+ * root, so site styles do not leak in). The default slot renders inside the placeholder as
7
+ * server-side fallback, e.g. a price or a link to the booking page for crawlers and
8
+ * visitors without JavaScript; the widget covers it once mounted.
9
+ *
10
+ * The element is keyed by its attributes, so changing a prop (another product on the same
11
+ * page component) replaces it and the runtime mounts the new one.
12
+ */
13
+ export declare function definePlaceholder<P extends ComponentObjectPropsOptions>(name: string, className: string, props: P, attrs: (props: ExtractPropTypes<P>) => Attrs, tag?: 'div' | 'span'): import("vue").DefineComponent<ComponentObjectPropsOptions<{
14
+ [x: string]: unknown;
15
+ }> extends P ? {} : ExtractPropTypes<P>, () => VNode<import("vue").RendererNode, import("vue").RendererElement, {
16
+ [key: string]: any;
17
+ }>, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<ComponentObjectPropsOptions<{
18
+ [x: string]: unknown;
19
+ }> extends P ? {} : ExtractPropTypes<P>> & Readonly<{}>, import("vue").ExtractDefaultPropTypes<P>, SlotsType<{
20
+ default?: () => VNode[];
21
+ }>, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
22
+ /** `{ item: 'tent' }` → `{ 'data-item': 'tent' }`, leaving out empty values. */
23
+ export declare function dataAttributes(attrs: Attrs): Record<string, string>;
24
+ /** Boolean-ish call option → the placeholder's `data-call` value. */
25
+ export declare function callAttr(call: boolean | 'off' | 'icon' | 'label' | undefined): string | undefined;
26
+ export {};
@@ -0,0 +1,29 @@
1
+ import { defineComponent, h } from "vue";
2
+ export function definePlaceholder(name, className, props, attrs, tag = "div") {
3
+ return defineComponent({
4
+ name,
5
+ inheritAttrs: true,
6
+ props,
7
+ slots: Object,
8
+ setup(componentProps, { slots }) {
9
+ return () => {
10
+ const data = dataAttributes(attrs(componentProps));
11
+ return h(tag, { key: JSON.stringify(data), class: className, ...data }, slots.default?.());
12
+ };
13
+ }
14
+ });
15
+ }
16
+ export function dataAttributes(attrs) {
17
+ const out = {};
18
+ for (const [key, value] of Object.entries(attrs)) {
19
+ if (value === void 0 || value === null || value === "") continue;
20
+ out[`data-${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`] = String(value);
21
+ }
22
+ return out;
23
+ }
24
+ export function callAttr(call) {
25
+ if (call === void 0) return void 0;
26
+ if (call === false) return "off";
27
+ if (call === true) return "icon";
28
+ return call;
29
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
2
+ export default _default;
@@ -0,0 +1,46 @@
1
+ import { defineNuxtPlugin, useHead, useRuntimeConfig, useState } from "#app";
2
+ import { cartSnapshot, embedRuntime, embedScriptAttributes, embedScriptUrl, emptyCart, themeCss } from "../embed.js";
3
+ export default defineNuxtPlugin({
4
+ name: "requiply",
5
+ setup(nuxtApp) {
6
+ const config = useRuntimeConfig().public.requiply;
7
+ if (config.publishableKey?.startsWith("rq_sk_")) {
8
+ throw new Error("[requiply] NUXT_PUBLIC_REQUIPLY_PUBLISHABLE_KEY holds a secret key (rq_sk_...). Use a publishable key (rq_pk_...) and keep the secret one in NUXT_REQUIPLY_SECRET_KEY.");
9
+ }
10
+ const ready = useState("requiply:embed-ready", () => false);
11
+ const cart = useState("requiply:embed-cart", emptyCart);
12
+ const version = useState("requiply:embed-version", () => 0);
13
+ if (!config.embed || !config.org) return;
14
+ const theme = themeCss(config.embed.theme);
15
+ useHead({
16
+ style: theme ? [{ key: "requiply-theme", textContent: theme }] : [],
17
+ script: [{
18
+ key: "requiply-embed",
19
+ src: embedScriptUrl(config, config.embed),
20
+ defer: true,
21
+ ...embedScriptAttributes(config, config.embed)
22
+ }]
23
+ });
24
+ if (import.meta.server) return;
25
+ const attach = (runtime) => {
26
+ if (ready.value) return;
27
+ const sync = () => {
28
+ cart.value = cartSnapshot(runtime);
29
+ version.value++;
30
+ };
31
+ sync();
32
+ runtime.subscribe(sync);
33
+ ready.value = true;
34
+ };
35
+ const onReady = () => {
36
+ const runtime = embedRuntime();
37
+ if (runtime) attach(runtime);
38
+ };
39
+ const afterHydration = () => {
40
+ if (nuxtApp.isHydrating) nuxtApp.hooks.hookOnce("app:suspense:resolve", onReady);
41
+ else onReady();
42
+ };
43
+ document.addEventListener("requiply:ready", afterHydration, { once: true });
44
+ afterHydration();
45
+ }
46
+ });
@@ -0,0 +1,2 @@
1
+ export * from '@requiply/api-sdk';
2
+ export type * from './types';
@@ -0,0 +1 @@
1
+ export * from "@requiply/api-sdk";
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": "../../../.nuxt/tsconfig.server.json",
3
+ }
@@ -0,0 +1,16 @@
1
+ import { RequiplyClient } from '@requiply/api-sdk';
2
+ import type { H3Event } from 'h3';
3
+ /**
4
+ * The Requiply API client with the secret key, for server routes, server middleware and
5
+ * Nitro tasks. A secret key reaches everything the organization's API allows: bookings,
6
+ * clients, sales, reports and inventory edits. Never return its raw results to the browser
7
+ * without picking the fields the page needs.
8
+ *
9
+ * @param event The request, so runtime config overrides per environment apply. Optional in tasks.
10
+ * @example
11
+ * export default defineEventHandler(async (event) => {
12
+ * const requiply = useRequiplyServer(event)
13
+ * return requiply.reports.revenue({ groupBy: 'month' })
14
+ * })
15
+ */
16
+ export declare function useRequiplyServer(event?: H3Event): RequiplyClient;
@@ -0,0 +1,22 @@
1
+ import { RequiplyClient } from "@requiply/api-sdk";
2
+ import { useRuntimeConfig } from "nitropack/runtime";
3
+ const clients = /* @__PURE__ */ new Map();
4
+ export function useRequiplyServer(event) {
5
+ const { requiply: privateConfig, public: { requiply: publicConfig } } = useRuntimeConfig(event);
6
+ const secretKey = privateConfig?.secretKey;
7
+ if (!secretKey) {
8
+ throw new Error("[requiply] useRequiplyServer() needs a secret key: set NUXT_REQUIPLY_SECRET_KEY (or `requiply.secretKey` in nuxt.config). Create one in Requiply under Settings > API keys.");
9
+ }
10
+ if (!secretKey.startsWith("rq_sk_")) {
11
+ throw new Error("[requiply] NUXT_REQUIPLY_SECRET_KEY does not hold a secret key (rq_sk_...).");
12
+ }
13
+ const baseUrl = publicConfig?.apiUrl;
14
+ const cacheKey = `${baseUrl}
15
+ ${secretKey}`;
16
+ let client = clients.get(cacheKey);
17
+ if (!client) {
18
+ client = new RequiplyClient({ apiKey: secretKey, baseUrl });
19
+ clients.set(cacheKey, client);
20
+ }
21
+ return client;
22
+ }