@central-ticket/queue-sdk 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.mjs ADDED
@@ -0,0 +1,185 @@
1
+ import {
2
+ CentralQ
3
+ } from "./chunk-A4HITWM4.mjs";
4
+ import "./chunk-42RGFZKP.mjs";
5
+ import "./chunk-XRJFNASX.mjs";
6
+
7
+ // src/react.ts
8
+ import { useEffect, useRef, useState, useCallback } from "react";
9
+ function useCentralQ(options) {
10
+ const [token, setToken] = useState(null);
11
+ const [position, setPosition] = useState(null);
12
+ const [ahead, setAhead] = useState(null);
13
+ const [expired, setExpired] = useState(false);
14
+ const [error, setError] = useState(false);
15
+ const instanceRef = useRef(null);
16
+ const leave = useCallback(() => {
17
+ instanceRef.current?.leave();
18
+ setToken(null);
19
+ setPosition(null);
20
+ setAhead(null);
21
+ }, []);
22
+ useEffect(() => {
23
+ const queue = CentralQ.init(options);
24
+ queue.on("passed", (detail) => {
25
+ setToken(detail.token);
26
+ setPosition(null);
27
+ setAhead(null);
28
+ setExpired(false);
29
+ setError(false);
30
+ });
31
+ queue.on("position", (detail) => {
32
+ setPosition(detail.position);
33
+ setAhead(detail.ahead);
34
+ });
35
+ queue.on("expired", () => {
36
+ setToken(null);
37
+ setExpired(true);
38
+ });
39
+ queue.on("error", () => {
40
+ setError(true);
41
+ });
42
+ instanceRef.current = queue;
43
+ return () => {
44
+ queue.destroy();
45
+ instanceRef.current = null;
46
+ };
47
+ }, [options.apiUrl, options.apiKey, options.eventId]);
48
+ return {
49
+ token,
50
+ position,
51
+ ahead,
52
+ expired,
53
+ error,
54
+ leave,
55
+ instance: instanceRef.current
56
+ };
57
+ }
58
+ function useQueue(options) {
59
+ const [status, setStatus] = useState("idle");
60
+ const [data, setData] = useState({
61
+ token: null,
62
+ position: null,
63
+ ahead: null,
64
+ expiresAt: null
65
+ });
66
+ const [error, setError] = useState(null);
67
+ const instanceRef = useRef(null);
68
+ const reset = useCallback(() => {
69
+ setStatus("idle");
70
+ setError(null);
71
+ setData({ token: null, position: null, ahead: null, expiresAt: null });
72
+ }, []);
73
+ const leave = useCallback(() => {
74
+ instanceRef.current?.leave();
75
+ setData({ token: null, position: null, ahead: null, expiresAt: null });
76
+ setStatus("idle");
77
+ }, []);
78
+ useEffect(() => {
79
+ let queue = null;
80
+ let cancelled = false;
81
+ if (options.enabled === false) {
82
+ instanceRef.current?.destroy();
83
+ instanceRef.current = null;
84
+ reset();
85
+ return;
86
+ }
87
+ setStatus("joining");
88
+ setError(null);
89
+ const init = async () => {
90
+ try {
91
+ let userId = options.userId;
92
+ let queueInitToken = options.queueInitToken;
93
+ if (!userId || !queueInitToken) {
94
+ if (options.autoInitToken === false) {
95
+ throw new Error(
96
+ "Falta queueInitToken/userId y initEndpoint est\xE1 deshabilitado"
97
+ );
98
+ }
99
+ const init2 = await options.client.issueQueueInitToken(
100
+ options.eventId,
101
+ userId
102
+ );
103
+ userId = init2.userId;
104
+ queueInitToken = init2.queueInitToken;
105
+ }
106
+ if (cancelled) return;
107
+ queue = options.client.createQueue({
108
+ eventId: options.eventId,
109
+ userId,
110
+ queueInitToken,
111
+ pollInterval: options.pollInterval,
112
+ container: options.container
113
+ });
114
+ queue.on("passed", (detail) => {
115
+ setData({
116
+ token: detail.token,
117
+ position: null,
118
+ ahead: null,
119
+ expiresAt: detail.expiresAt
120
+ });
121
+ setStatus("passed");
122
+ setError(null);
123
+ });
124
+ queue.on("position", (detail) => {
125
+ setData((prev) => ({
126
+ ...prev,
127
+ token: null,
128
+ position: detail.position,
129
+ ahead: detail.ahead
130
+ }));
131
+ setStatus("waiting");
132
+ });
133
+ queue.on("expired", () => {
134
+ setData({
135
+ token: null,
136
+ position: null,
137
+ ahead: null,
138
+ expiresAt: null
139
+ });
140
+ setStatus("expired");
141
+ });
142
+ queue.on("error", () => {
143
+ setStatus("error");
144
+ setError(new Error("Queue connection error"));
145
+ });
146
+ instanceRef.current = queue;
147
+ } catch (err) {
148
+ if (cancelled) return;
149
+ setStatus("error");
150
+ setError(
151
+ err instanceof Error ? err : new Error("Queue connection error")
152
+ );
153
+ }
154
+ };
155
+ init();
156
+ return () => {
157
+ cancelled = true;
158
+ queue?.destroy();
159
+ instanceRef.current = null;
160
+ };
161
+ }, [
162
+ options.client,
163
+ options.enabled,
164
+ options.eventId,
165
+ options.userId,
166
+ options.queueInitToken,
167
+ options.autoInitToken,
168
+ options.pollInterval,
169
+ options.container,
170
+ reset
171
+ ]);
172
+ return {
173
+ status,
174
+ data,
175
+ isPending: status === "idle" || status === "joining",
176
+ error,
177
+ leave,
178
+ reset,
179
+ instance: instanceRef.current
180
+ };
181
+ }
182
+ export {
183
+ useCentralQ,
184
+ useQueue
185
+ };
@@ -0,0 +1,21 @@
1
+ interface ValidateQueueTokenServerOptions {
2
+ apiUrl?: string;
3
+ secretKey: string;
4
+ eventId: string;
5
+ token: string;
6
+ }
7
+ type QueueTokenValidationResult = {
8
+ valid: true;
9
+ userId: string;
10
+ eventId: string;
11
+ expiresAt: string;
12
+ } | {
13
+ valid: false;
14
+ reason: string;
15
+ };
16
+ declare function validateQueueTokenServer(options: ValidateQueueTokenServerOptions): Promise<{
17
+ status: number;
18
+ data: QueueTokenValidationResult;
19
+ }>;
20
+
21
+ export { type QueueTokenValidationResult, type ValidateQueueTokenServerOptions, validateQueueTokenServer };
@@ -0,0 +1,21 @@
1
+ interface ValidateQueueTokenServerOptions {
2
+ apiUrl?: string;
3
+ secretKey: string;
4
+ eventId: string;
5
+ token: string;
6
+ }
7
+ type QueueTokenValidationResult = {
8
+ valid: true;
9
+ userId: string;
10
+ eventId: string;
11
+ expiresAt: string;
12
+ } | {
13
+ valid: false;
14
+ reason: string;
15
+ };
16
+ declare function validateQueueTokenServer(options: ValidateQueueTokenServerOptions): Promise<{
17
+ status: number;
18
+ data: QueueTokenValidationResult;
19
+ }>;
20
+
21
+ export { type QueueTokenValidationResult, type ValidateQueueTokenServerOptions, validateQueueTokenServer };
package/dist/server.js ADDED
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/server.ts
21
+ var server_exports = {};
22
+ __export(server_exports, {
23
+ validateQueueTokenServer: () => validateQueueTokenServer
24
+ });
25
+ module.exports = __toCommonJS(server_exports);
26
+
27
+ // src/queue-client.ts
28
+ var CENTRALQ_DEFAULT_API_URL = "http://localhost:3001";
29
+
30
+ // src/server.ts
31
+ function normalizeApiUrl(apiUrl) {
32
+ return apiUrl.replace(/\/+$/, "");
33
+ }
34
+ async function validateQueueTokenServer(options) {
35
+ const apiUrl = options.apiUrl ?? CENTRALQ_DEFAULT_API_URL;
36
+ const response = await fetch(
37
+ `${normalizeApiUrl(apiUrl)}/api/verify/${encodeURIComponent(options.eventId)}`,
38
+ {
39
+ method: "POST",
40
+ headers: {
41
+ "Content-Type": "application/json",
42
+ "x-api-key": options.secretKey
43
+ },
44
+ body: JSON.stringify({ token: options.token })
45
+ }
46
+ );
47
+ const data = await response.json().catch(() => ({
48
+ valid: false,
49
+ reason: "Respuesta inv\xE1lida"
50
+ }));
51
+ return { status: response.status, data };
52
+ }
53
+ // Annotate the CommonJS export names for ESM import in node:
54
+ 0 && (module.exports = {
55
+ validateQueueTokenServer
56
+ });
@@ -0,0 +1,8 @@
1
+ import {
2
+ validateQueueTokenServer
3
+ } from "./chunk-JR7BCYB5.mjs";
4
+ import "./chunk-42RGFZKP.mjs";
5
+ import "./chunk-XRJFNASX.mjs";
6
+ export {
7
+ validateQueueTokenServer
8
+ };
@@ -0,0 +1,79 @@
1
+ import { Readable } from 'svelte/store';
2
+ import { Q as QueueStatus, C as CentralQ, c as CentralQCreateOptions, a as CentralQClient, d as CentralQOptions } from './centralq-I9tdL_Xr.mjs';
3
+
4
+ interface CentralQStores {
5
+ /** Store con el token JWT si el usuario fue admitido */
6
+ token: Readable<string | null>;
7
+ /** Store con la posición en la cola (1-based) */
8
+ position: Readable<number | null>;
9
+ /** Store con las personas delante en la cola */
10
+ ahead: Readable<number | null>;
11
+ /** Store indicando si la sesión expiró */
12
+ expired: Readable<boolean>;
13
+ /** Store indicando si hay un error de conexión */
14
+ error: Readable<boolean>;
15
+ /** Libera el slot (llamar después de comprar) */
16
+ leave: () => void;
17
+ }
18
+ interface QueueData {
19
+ token: string | null;
20
+ position: number | null;
21
+ ahead: number | null;
22
+ expiresAt: number | null;
23
+ }
24
+ interface UseQueueOptions extends Omit<CentralQCreateOptions, "apiUrl" | "apiKey"> {
25
+ /** Cliente global creado con createCentralQClient */
26
+ client: CentralQClient;
27
+ /** Habilita o pausa la suscripción de la cola */
28
+ enabled?: boolean;
29
+ /** Deshabilita bootstrap automático de init token */
30
+ autoInitToken?: boolean;
31
+ }
32
+ type UseQueueOptionsInput = UseQueueOptions | (() => UseQueueOptions);
33
+ interface QueueStores {
34
+ status: Readable<QueueStatus>;
35
+ token: Readable<string | null>;
36
+ position: Readable<number | null>;
37
+ ahead: Readable<number | null>;
38
+ expiresAt: Readable<number | null>;
39
+ data: Readable<QueueData>;
40
+ isPending: Readable<boolean>;
41
+ error: Readable<Error | null>;
42
+ leave: () => void;
43
+ reset: () => void;
44
+ instance: Readable<CentralQ | null>;
45
+ }
46
+ /**
47
+ * Svelte adapter que encapsula toda la lógica de CentralQ
48
+ * usando Svelte stores.
49
+ *
50
+ * **Debe llamarse en el top-level del `<script>` del componente**
51
+ * (igual que onMount — internamente usa onMount para diferir
52
+ * la inicialización al browser y evitar problemas de SSR).
53
+ *
54
+ * ```svelte
55
+ * <script lang="ts">
56
+ * import { createCentralQ } from '@central-ticket/queue-sdk/svelte';
57
+ *
58
+ * const { token, position, expired, leave } = createCentralQ({
59
+ * apiUrl: 'http://localhost:3001',
60
+ * apiKey: 'ctq_pub_xxx',
61
+ * eventId: 'coldplay-2026',
62
+ * });
63
+ * </script>
64
+ *
65
+ * {#if $token}
66
+ * <button onclick={() => { buy(); leave(); }}>Comprar</button>
67
+ * {:else if $expired}
68
+ * <p>Sesión expirada</p>
69
+ * {:else if $position}
70
+ * <p>Posición #{$position}</p>
71
+ * {:else}
72
+ * <p>Conectando...</p>
73
+ * {/if}
74
+ * ```
75
+ */
76
+ declare function createCentralQ(options: CentralQOptions): CentralQStores;
77
+ declare function useQueue(optionsInput: UseQueueOptionsInput): QueueStores;
78
+
79
+ export { type CentralQStores, type QueueData, type QueueStores, type UseQueueOptions, type UseQueueOptionsInput, createCentralQ, useQueue };
@@ -0,0 +1,79 @@
1
+ import { Readable } from 'svelte/store';
2
+ import { Q as QueueStatus, C as CentralQ, c as CentralQCreateOptions, a as CentralQClient, d as CentralQOptions } from './centralq-I9tdL_Xr.js';
3
+
4
+ interface CentralQStores {
5
+ /** Store con el token JWT si el usuario fue admitido */
6
+ token: Readable<string | null>;
7
+ /** Store con la posición en la cola (1-based) */
8
+ position: Readable<number | null>;
9
+ /** Store con las personas delante en la cola */
10
+ ahead: Readable<number | null>;
11
+ /** Store indicando si la sesión expiró */
12
+ expired: Readable<boolean>;
13
+ /** Store indicando si hay un error de conexión */
14
+ error: Readable<boolean>;
15
+ /** Libera el slot (llamar después de comprar) */
16
+ leave: () => void;
17
+ }
18
+ interface QueueData {
19
+ token: string | null;
20
+ position: number | null;
21
+ ahead: number | null;
22
+ expiresAt: number | null;
23
+ }
24
+ interface UseQueueOptions extends Omit<CentralQCreateOptions, "apiUrl" | "apiKey"> {
25
+ /** Cliente global creado con createCentralQClient */
26
+ client: CentralQClient;
27
+ /** Habilita o pausa la suscripción de la cola */
28
+ enabled?: boolean;
29
+ /** Deshabilita bootstrap automático de init token */
30
+ autoInitToken?: boolean;
31
+ }
32
+ type UseQueueOptionsInput = UseQueueOptions | (() => UseQueueOptions);
33
+ interface QueueStores {
34
+ status: Readable<QueueStatus>;
35
+ token: Readable<string | null>;
36
+ position: Readable<number | null>;
37
+ ahead: Readable<number | null>;
38
+ expiresAt: Readable<number | null>;
39
+ data: Readable<QueueData>;
40
+ isPending: Readable<boolean>;
41
+ error: Readable<Error | null>;
42
+ leave: () => void;
43
+ reset: () => void;
44
+ instance: Readable<CentralQ | null>;
45
+ }
46
+ /**
47
+ * Svelte adapter que encapsula toda la lógica de CentralQ
48
+ * usando Svelte stores.
49
+ *
50
+ * **Debe llamarse en el top-level del `<script>` del componente**
51
+ * (igual que onMount — internamente usa onMount para diferir
52
+ * la inicialización al browser y evitar problemas de SSR).
53
+ *
54
+ * ```svelte
55
+ * <script lang="ts">
56
+ * import { createCentralQ } from '@central-ticket/queue-sdk/svelte';
57
+ *
58
+ * const { token, position, expired, leave } = createCentralQ({
59
+ * apiUrl: 'http://localhost:3001',
60
+ * apiKey: 'ctq_pub_xxx',
61
+ * eventId: 'coldplay-2026',
62
+ * });
63
+ * </script>
64
+ *
65
+ * {#if $token}
66
+ * <button onclick={() => { buy(); leave(); }}>Comprar</button>
67
+ * {:else if $expired}
68
+ * <p>Sesión expirada</p>
69
+ * {:else if $position}
70
+ * <p>Posición #{$position}</p>
71
+ * {:else}
72
+ * <p>Conectando...</p>
73
+ * {/if}
74
+ * ```
75
+ */
76
+ declare function createCentralQ(options: CentralQOptions): CentralQStores;
77
+ declare function useQueue(optionsInput: UseQueueOptionsInput): QueueStores;
78
+
79
+ export { type CentralQStores, type QueueData, type QueueStores, type UseQueueOptions, type UseQueueOptionsInput, createCentralQ, useQueue };