etiquetas.js 1.0.0-alpha.15 → 1.0.0-alpha.16

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.
@@ -0,0 +1,40 @@
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
8
+ }
9
+ };
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
15
+ }
16
+ };
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
19
+ });
20
+ };
21
+ import { L as LabelsAPI } from "./index-CrFIiiLi.js";
22
+ function getTemplateById(templateId) {
23
+ return __async(this, null, function* () {
24
+ try {
25
+ const labelData = yield LabelsAPI.getLabel(templateId);
26
+ if (!labelData) {
27
+ throw new Error(`Template/etiqueta não encontrado com ID: ${templateId}`);
28
+ }
29
+ console.log("templateContent:", labelData);
30
+ return JSON.parse(labelData.label_content);
31
+ } catch (error) {
32
+ console.error(`Erro ao buscar template: ${error.message}`);
33
+ throw error;
34
+ }
35
+ });
36
+ }
37
+ export {
38
+ getTemplateById
39
+ };
40
+ //# sourceMappingURL=templates-DB-LZbhi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templates-DB-LZbhi.js","sources":["../src/templates.js"],"sourcesContent":["/**\r\n * 🏷️ TEMPLATES DO SISTEMA DE ETIQUETAS\r\n * \r\n * Configurações e definições de templates para cada tipo de etiqueta\r\n */\r\n\r\nimport { templateVariables } from './constants.js';\r\n\r\nimport { LabelsAPI } from '../api/api.js';\r\n\r\n// ============================================================================\r\n// TEMPLATES DE PEÇAS\r\n// ============================================================================\r\n\r\n\r\n/**\r\n * Obtém um template pelo seu ID a partir da API de etiquetas\r\n * @param {number|string} templateId - ID do template/etiqueta a buscar\r\n * @returns {Promise<Object>} Template com dados da API\r\n */\r\nexport async function getTemplateById(templateId) {\r\n try {\r\n // Converte para número se for string numérica\r\n\r\n \r\n \r\n // Busca na API pelo ID\r\n const labelData = await LabelsAPI.getLabel(templateId);\r\n \r\n if (!labelData) {\r\n throw new Error(`Template/etiqueta não encontrado com ID: ${templateId}`);\r\n }\r\n \r\n \r\n \r\n \r\n // Retorna em formato de array conforme esperado pela função loadLabelTemplate\r\n console.log('templateContent:', labelData);\r\n return JSON.parse(labelData.label_content);\r\n } catch (error) {\r\n console.error(`Erro ao buscar template: ${error.message}`);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Obtém templates por tipo\r\n * @param {string} type - Tipo de etiqueta (parts, woodwork, inputs, scraps, volumes)\r\n * @returns {Array} Lista de templates do tipo especificado\r\n */\r\nexport function getTemplatesByType(type) {\r\n return Object.values(allTemplates).filter(template => template.type === type);\r\n}\r\n\r\n/**\r\n * Lista todos os IDs de templates disponíveis\r\n * @returns {Array} Lista de IDs de templates\r\n */\r\nexport function getTemplateIds() {\r\n return Object.keys(allTemplates);\r\n}\r\n\r\n/**\r\n * Valida se um template possui estrutura válida\r\n * @param {Object} template - Template a ser validado\r\n * @returns {boolean} True se válido, false caso contrário\r\n */\r\nexport function validateTemplate(template) {\r\n if (!template || typeof template !== 'object') return false;\r\n \r\n const requiredFields = ['id', 'name', 'type', 'pageWidth', 'pageHeight', 'elements'];\r\n \r\n for (const field of requiredFields) {\r\n if (!(field in template)) return false;\r\n }\r\n \r\n if (!Array.isArray(template.elements)) return false;\r\n \r\n return true;\r\n}\r\n\r\n/**\r\n * Obtém variáveis utilizadas em um template\r\n * @param {Object} template - Template a ser analisado\r\n * @returns {Array} Lista de variáveis encontradas\r\n */\r\nexport function getTemplateVariables(template) {\r\n if (!validateTemplate(template)) return [];\r\n \r\n const variables = new Set();\r\n const variableRegex = /\\{\\{([^}]+)\\}\\}/g;\r\n \r\n template.elements.forEach(element => {\r\n if (element.content) {\r\n let match;\r\n while ((match = variableRegex.exec(element.content)) !== null) {\r\n variables.add(match[1]);\r\n }\r\n }\r\n });\r\n \r\n return Array.from(variables);\r\n}\r\n\r\n/**\r\n * Substitui variáveis em um template com dados fornecidos\r\n * @param {Object} template - Template base\r\n * @param {Object} data - Dados para substituição\r\n * @returns {Object} Template com variáveis substituídas\r\n */\r\nexport function replaceTemplateVariables(template, data) {\r\n if (!validateTemplate(template)) return template;\r\n \r\n const processedTemplate = JSON.parse(JSON.stringify(template));\r\n \r\n processedTemplate.elements = processedTemplate.elements.map(element => {\r\n if (element.content) {\r\n element.content = element.content.replace(/\\{\\{([^}]+)\\}\\}/g, (match, variable) => {\r\n return data[variable] || match;\r\n });\r\n }\r\n return element;\r\n });\r\n \r\n return processedTemplate;\r\n}\r\n\r\n// ============================================================================\r\n// EXPORTAÇÃO PADRÃO\r\n// ============================================================================\r\n\r\nexport default {\r\n\r\n getTemplateById,\r\n getTemplatesByType,\r\n getTemplateIds,\r\n validateTemplate,\r\n getTemplateVariables,\r\n replaceTemplateVariables\r\n};"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBO,SAAe,gBAAgB,YAAY;AAAA;AAChD,QAAI;AAMF,YAAM,YAAY,MAAM,UAAU,SAAS,UAAU;AAErD,UAAI,CAAC,WAAW;AACd,cAAM,IAAI,MAAM,4CAA4C,UAAU,EAAE;AAAA,MAC1E;AAMA,cAAQ,IAAI,oBAAoB,SAAS;AACzC,aAAO,KAAK,MAAM,UAAU,aAAa;AAAA,IAC3C,SAAS,OAAO;AACd,cAAQ,MAAM,4BAA4B,MAAM,OAAO,EAAE;AACzD,YAAM;AAAA,IACR;AAAA,EACF;AAAA;"}
@@ -0,0 +1,114 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ import { c as create } from "./index-CrFIiiLi.js";
18
+ const createPrinterSlice = (set, get) => ({
19
+ printerStatus: {
20
+ name: "Aguardando...",
21
+ connected: false,
22
+ status: "disconnected",
23
+ hasDefaultPrinter: false,
24
+ message: "Conectando ao servidor...",
25
+ printer: null
26
+ },
27
+ setPrinterStatus: (status) => set(() => ({ printerStatus: status })),
28
+ updatePrinterStatus: (updates) => set((state) => ({
29
+ printerStatus: __spreadValues(__spreadValues({}, state.printerStatus), updates)
30
+ }))
31
+ });
32
+ const createSSESlice = (set, get) => ({
33
+ sseConnected: false,
34
+ eventSource: null,
35
+ setSseConnected: (connected) => set(() => ({ sseConnected: connected })),
36
+ setEventSource: (eventSource) => set(() => ({ eventSource })),
37
+ connectToSSE: () => {
38
+ const { eventSource, setSseConnected, updatePrinterStatus, setEventSource } = get();
39
+ if (typeof EventSource === "undefined") {
40
+ console.log("EventSource não disponível em ambiente Node.js");
41
+ setSseConnected(false);
42
+ updatePrinterStatus({ connected: false, status: "disconnected" });
43
+ return;
44
+ }
45
+ if (eventSource) {
46
+ eventSource.close();
47
+ }
48
+ try {
49
+ const newEventSource = new EventSource("http://localhost:9999/printer/status/stream");
50
+ setEventSource(newEventSource);
51
+ newEventSource.onopen = () => {
52
+ console.log("Conexão SSE estabelecida com a impressora");
53
+ setSseConnected(true);
54
+ updatePrinterStatus({ status: "connecting" });
55
+ };
56
+ newEventSource.addEventListener("printer-status", (event) => {
57
+ var _a;
58
+ try {
59
+ const data = JSON.parse(event.data);
60
+ console.log("message =>>>>>>>>>", data);
61
+ let status = "disconnected";
62
+ let name = "Nenhuma impressora";
63
+ if (!data.hasDefaultPrinter) {
64
+ status = "no-printer";
65
+ name = "Sem impressora configurada";
66
+ } else if (data.isConnected && data.printer) {
67
+ status = "connected";
68
+ name = data.printer.name || "Impressora";
69
+ } else {
70
+ status = "disconnected";
71
+ name = ((_a = data.printer) == null ? void 0 : _a.name) || "Impressora";
72
+ }
73
+ updatePrinterStatus({
74
+ name,
75
+ connected: data.isConnected || false,
76
+ status,
77
+ hasDefaultPrinter: data.hasDefaultPrinter || false,
78
+ message: data.message || "",
79
+ printer: data.printer || null
80
+ });
81
+ } catch (error) {
82
+ console.warn("Erro ao processar dados da impressora:", error);
83
+ }
84
+ });
85
+ newEventSource.onerror = (error) => {
86
+ console.error("Erro na conexão SSE:", error);
87
+ setSseConnected(false);
88
+ updatePrinterStatus({ connected: false, status: "disconnected" });
89
+ newEventSource.close();
90
+ setEventSource(null);
91
+ setTimeout(() => {
92
+ get().connectToSSE();
93
+ }, 5e3);
94
+ };
95
+ } catch (error) {
96
+ console.error("Erro ao conectar SSE:", error);
97
+ setSseConnected(false);
98
+ updatePrinterStatus({ connected: false, status: "disconnected" });
99
+ }
100
+ },
101
+ disconnectSSE: () => {
102
+ const { eventSource, setSseConnected, setEventSource } = get();
103
+ if (eventSource) {
104
+ eventSource.close();
105
+ setEventSource(null);
106
+ }
107
+ setSseConnected(false);
108
+ }
109
+ });
110
+ const usePrinterStore = create((set, get) => __spreadValues(__spreadValues({}, createPrinterSlice(set)), createSSESlice(set, get)));
111
+ export {
112
+ usePrinterStore as default
113
+ };
114
+ //# sourceMappingURL=usePrinterStore-DjE7a9VN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usePrinterStore-DjE7a9VN.js","sources":["../src/usePrinterStore.js"],"sourcesContent":["import { create } from 'zustand';\r\n\r\nconst createPrinterSlice = (set, get) => ({\r\n printerStatus: {\r\n name: 'Aguardando...',\r\n connected: false,\r\n status: 'disconnected',\r\n hasDefaultPrinter: false,\r\n message: 'Conectando ao servidor...',\r\n printer: null\r\n },\r\n setPrinterStatus: (status) => set(() => ({ printerStatus: status })),\r\n updatePrinterStatus: (updates) => set((state) => ({\r\n printerStatus: { ...state.printerStatus, ...updates }\r\n }))\r\n});\r\n\r\nconst createSSESlice = (set, get) => ({\r\n sseConnected: false,\r\n eventSource: null,\r\n setSseConnected: (connected) => set(() => ({ sseConnected: connected })),\r\n setEventSource: (eventSource) => set(() => ({ eventSource })),\r\n \r\n connectToSSE: () => {\r\n const { eventSource, setSseConnected, updatePrinterStatus, setEventSource } = get();\r\n \r\n // Verificar se estamos em ambiente browser\r\n if (typeof EventSource === 'undefined') {\r\n console.log('EventSource não disponível em ambiente Node.js');\r\n setSseConnected(false);\r\n updatePrinterStatus({ connected: false, status: 'disconnected' });\r\n return;\r\n }\r\n \r\n // Se já existe uma conexão, feche-a primeiro\r\n if (eventSource) {\r\n eventSource.close();\r\n }\r\n \r\n try {\r\n const newEventSource = new EventSource('http://localhost:9999/printer/status/stream');\r\n setEventSource(newEventSource);\r\n \r\n newEventSource.onopen = () => {\r\n console.log('Conexão SSE estabelecida com a impressora');\r\n setSseConnected(true);\r\n updatePrinterStatus({ status: 'connecting' });\r\n };\r\n \r\n newEventSource.addEventListener('printer-status', (event) => {\r\n try {\r\n const data = JSON.parse(event.data);\r\n console.log('message =>>>>>>>>>',data);\r\n let status = 'disconnected';\r\n let name = 'Nenhuma impressora';\r\n \r\n if (!data.hasDefaultPrinter) {\r\n status = 'no-printer';\r\n name = 'Sem impressora configurada';\r\n } else if (data.isConnected && data.printer) {\r\n status = 'connected';\r\n name = data.printer.name || 'Impressora';\r\n } else {\r\n status = 'disconnected';\r\n name = data.printer?.name || 'Impressora';\r\n }\r\n \r\n updatePrinterStatus({\r\n name,\r\n connected: data.isConnected || false,\r\n status,\r\n hasDefaultPrinter: data.hasDefaultPrinter || false,\r\n message: data.message || '',\r\n printer: data.printer || null\r\n });\r\n } catch (error) {\r\n console.warn('Erro ao processar dados da impressora:', error);\r\n }\r\n });\r\n \r\n newEventSource.onerror = (error) => {\r\n console.error('Erro na conexão SSE:', error);\r\n setSseConnected(false);\r\n updatePrinterStatus({ connected: false, status: 'disconnected' });\r\n newEventSource.close();\r\n setEventSource(null);\r\n \r\n // Tentar reconectar após 5 segundos\r\n setTimeout(() => {\r\n get().connectToSSE();\r\n }, 5000);\r\n };\r\n } catch (error) {\r\n console.error('Erro ao conectar SSE:', error);\r\n setSseConnected(false);\r\n updatePrinterStatus({ connected: false, status: 'disconnected' });\r\n }\r\n },\r\n \r\n disconnectSSE: () => {\r\n const { eventSource, setSseConnected, setEventSource } = get();\r\n if (eventSource) {\r\n eventSource.close();\r\n setEventSource(null);\r\n }\r\n setSseConnected(false);\r\n }\r\n});\r\n\r\nconst usePrinterStore = create((set, get) => ({\r\n ...createPrinterSlice(set, get),\r\n ...createSSESlice(set, get)\r\n}));\r\n\r\nexport default usePrinterStore;"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAEA,MAAM,qBAAqB,CAAC,KAAK,SAAS;AAAA,EACxC,eAAe;AAAA,IACb,MAAM;AAAA,IACN,WAAW;AAAA,IACX,QAAQ;AAAA,IACR,mBAAmB;AAAA,IACnB,SAAS;AAAA,IACT,SAAS;AAAA,EACb;AAAA,EACE,kBAAkB,CAAC,WAAW,IAAI,OAAO,EAAE,eAAe,OAAM,EAAG;AAAA,EACnE,qBAAqB,CAAC,YAAY,IAAI,CAAC,WAAW;AAAA,IAChD,eAAe,kCAAK,MAAM,gBAAkB;AAAA,EAChD,EAAI;AACJ;AAEA,MAAM,iBAAiB,CAAC,KAAK,SAAS;AAAA,EACpC,cAAc;AAAA,EACd,aAAa;AAAA,EACb,iBAAiB,CAAC,cAAc,IAAI,OAAO,EAAE,cAAc,UAAS,EAAG;AAAA,EACvE,gBAAgB,CAAC,gBAAgB,IAAI,OAAO,EAAE,YAAW,EAAG;AAAA,EAE5D,cAAc,MAAM;AAClB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O,QAAQ,eAAc,CAAE;AAChE,uBAAe,MAAK;AACpB,uBAAe,IAAI;AAGnB,mBAAW,MAAM;AACf,cAAG,EAAG;QACR,GAAG,GAAI;AAAA,MACT;AAAA,IACF,SAAS,OAAO;AACd,cAAQ,MAAM,yBAAyB,KAAK;AAC5C,sBAAgB,KAAK;AACrB,0BAAoB,EAAE,WAAW,OAAO,QAAQ,eAAc,CAAE;AAAA,IAClE;AAAA,EACF;AAAA,EAEA,eAAe,MAAM;AACnB,UAAM,EAAE,aAAa,iBAAiB,eAAc,IAAK,IAAG;AAC5D,QAAI,aAAa;AACf,kBAAY,MAAK;AACjB,qBAAe,IAAI;AAAA,IACrB;AACA,oBAAgB,KAAK;AAAA,EACvB;AACF;AAEK,MAAC,kBAAkB,OAAO,CAAC,KAAK,QAAS,kCACzC,mBAAmB,GAAQ,IAC3B,eAAe,KAAK,GAAG,EAC1B;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "etiquetas.js",
3
- "version": "1.0.0-alpha.15",
3
+ "version": "1.0.0-alpha.16",
4
4
  "type": "module",
5
5
  "main": "dist/etiquetas.umd.js",
6
6
  "module": "dist/etiquetas.es.js",