🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@sunmi/max-print

Package Overview
Dependencies
Maintainers
3
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@sunmi/max-print - npm Package Compare versions

Comparing version
1.0.9
to
2.2.2
+134
-20
convertTemplate.mjs

@@ -16,6 +16,6 @@ // ==================== 主导出函数 ====================

* 模板转换器 - 将模板和数据转换为打印指令
* @version 2.2.0
* @version 2.2.2
*/
// ==================== 常量配置 ====================
const VERSION = "2.2.0";
const VERSION = "2.2.2";

@@ -60,3 +60,3 @@ // ========== 字体大小配置(唯一维护点) ==========

*/
static parseTemplateData(text, lang, obj) {
static parseTemplateData(text, lang, obj, templateConfig, i18nData = null) {
if (!text || typeof text !== "string") return "";

@@ -66,3 +66,2 @@ if (!/\{\{/.test(text)) return text;

let result = text;
// 处理数据变量 {{variable}} 或 {{obj.key}}

@@ -73,17 +72,40 @@ const dataKeys = result.match(/{{[a-zA-Z0-9\.]+}}/g);

const cleanKey = key.replace(/^\{\{|\}\}$/g, "");
const value = this.getNestedValue(obj, cleanKey);
const displayValue = (value != null && ["string", "number"].includes(typeof value)) ? value : "";
result = result.replaceAll(key, displayValue);
const { supported = [], supportedIds = [] } = templateConfig?.param?.multiLanguage ?? {};
if (templateConfig?.param?.enableMultiLanguage === true && supportedIds.includes(key) && i18nData) {
const [firstLang, secondLang] = supported;
const firstValue = i18nData[firstLang]?.[cleanKey];
const secondValue = i18nData[secondLang]?.[cleanKey];
const displayValue = `${firstValue !== null && ["string", "number"].includes(typeof firstValue) ? firstValue : ''}${secondValue !== null && ["string", "number"].includes(typeof secondValue) ? `(${secondValue})` : ''}`;
result = result.replaceAll(key, displayValue);
} else {
const value = this.getNestedValue(obj, cleanKey);
const displayValue = (value != null && ["string", "number"].includes(typeof value)) ? value : "";
result = result.replaceAll(key, displayValue);
}
});
}
// 处理国际化变量 {{key|l}}
const langKeys = result.match(/{{[a-zA-Z0-9\-]+\|l}}/g);
if (langKeys) {
langKeys.forEach((key) => {
langKeys.forEach(key => {
const cleanKey = key.replace(/^\{\{|\|l\}\}$/g, "");
const value = lang?.[cleanKey];
const displayValue = (value != null && ["string", "number"].includes(typeof value)) ? value : "";
result = result.replaceAll(key, displayValue);
const { supported = [], supportedIds = [] } = templateConfig?.param?.multiLanguage ?? {};
if (templateConfig?.param?.enableMultiLanguage === true && supportedIds.includes(key) && i18nData) {
const [firstLang, secondLang] = supported;
const firstValue = i18nData[firstLang]?.[cleanKey];
const secondValue = i18nData[secondLang]?.[cleanKey];
const displayValue = `${firstValue !== null && ["string", "number"].includes(typeof firstValue) ? firstValue : ''}${secondValue !== null && ["string", "number"].includes(typeof secondValue) ? `(${secondValue})` : ''}`;
result = result.replaceAll(key, displayValue);
} else {
const value = lang?.[cleanKey];
const displayValue = (value != null && ["string", "number"].includes(typeof value)) ? value : "";
result = result.replaceAll(key, displayValue);
}
});
}

@@ -183,3 +205,2 @@

if (typeof key === "string") {
// 先从传入的fontConfig查找,再从DEFAULT_FONT_CONFIG查找
const resolvedKey = FONT_SIZE_MAP[key] || key;

@@ -233,6 +254,7 @@ size = this.fontConfig[resolvedKey] || DEFAULT_FONT_CONFIG[resolvedKey];

const { text, ...other } = param;
const finalBold = bold ?? other.bold;
const parsedText = TemplateUtils.parseTemplateData(text, lang, obj || {});
const templateConfig = this.context.getTemplateConfig();
const parsedText = TemplateUtils.parseTemplateData(text, lang, obj || {}, templateConfig, this.context.template.lang);
let params = {

@@ -291,2 +313,3 @@ value: parsedText,

align: other.align,
weight: other.weight,
...(other.maxWidth && { maxWidth: other.maxWidth }),

@@ -380,6 +403,5 @@ };

*/
convertQrCode(param, obj, lang, options = {}) {
convertQrCode(param, obj, lang, options = {}, isColumnChild = false) {
const { code, ...other } = param;
const processedCode = TemplateUtils.parseTemplateData(code, lang, obj);
// 直接是base64图片

@@ -390,3 +412,4 @@ if (processedCode.match(/^data:image\/png;base64,/)) {

align: other.align,
}, obj, lang, false, options);
weight: other.weight
}, obj, lang, isColumnChild, options);
}

@@ -578,6 +601,6 @@

const visibleColumns = columns.filter(item => item.show !== false);
const templateConfig = this.context.getTemplateConfig();
// 检查每列的值并统计有值的列数
const columnsWithValues = visibleColumns.map(item => {
const parsedText = TemplateUtils.parseTemplateData(item.text, lang, obj);
const parsedText = TemplateUtils.parseTemplateData(item.text, lang, obj, templateConfig, this.context.template.lang);
const hasValue = parsedText && parsedText.trim() !== '';

@@ -690,2 +713,5 @@ return {

break;
case "qr":
result.push(...this.converter.convertQrCode(processedItem.param, obj, lang, childOptions, true))
break;
default:

@@ -858,4 +884,82 @@ console.warn(`Unknown item type in columnInColumn: ${processedItem.type}`);

// 如果指令已经是 columns 类型,使用嵌套 rows 的方式
if (instruction.type === 'columns' && instruction.params && instruction.params.items) {
// 多列已使用了多行类型且多行内的子集数量是多余非多行的子集数量
if (instruction.params.items.some(item => item.type === 'rows')) {
const firstColumn = instruction.params.items[0]?.items ?? [];
if (firstColumn.length > 0) {
firstColumn.forEach((item, i) => {
// item.value = `${i === 0 ? lineNumber.toString() : ((this.context.lineNumberCounter++)).toString()} ${item.value}`
item.params.items.unshift(i === 0 ? lineNumberItem : {
type: "text",
value: `${((this.context.lineNumberCounter++)).toString()}`,
// TODO: 使用固定宽度
weight: 1, // 行号列权重始终为1
align: 0,
size: 20
});
// item.params.items[1].weight = 9
});
return instruction;
}
// const otherTypeNum = instruction.params.items.filter(item => item.type !== 'rows').length;
// // rows 类型的子集数量最大值
// const maxRowsTypeNum = instruction.params.items.reduce((max, item) => {
// if (item.type === 'rows') {
// return Math.max(max, item.items.length);
// }
// return max;
// }, 0)
// if (maxRowsTypeNum > otherTypeNum) {
// const wrappedInstruction = {
// type: "columns",
// params: {
// items: [
// {
// type: "rows",
// weight: 1,
// items: [
// // 根据 maxRowsTypeNum 生成行号列
// ...Array.from({ length: maxRowsTypeNum }, (_, i) => ({
// type: "text",
// value: i === 0 ? `${(this.context.lineNumberCounter-1).toString()}`:`${((this.context.lineNumberCounter++) ).toString()
// }`,
// weight: 1, // 行号列权重始终为1
// align: 0,
// size: 20
// }))
// ]
// },
// {
// type: "rows",
// weight: 9, // 使用原始权重总计
// items: [
// {
// type: "columns",
// params: {
// items: instruction.params.items // 保持原有的 items 不变
// },
// // 将原始指令的 UUID 传递到内层的 columns
// ...(originalUUID && { templateUUID: originalUUID })
// }
// ]
// }
// ]
// }
// }
// return wrappedInstruction;
// }
}
const wrappedInstruction = {

@@ -893,2 +997,3 @@ type: "columns",

// 获取原指令的值,确保不为空

@@ -1007,3 +1112,3 @@ const originalValue = instruction.params ? instruction.params.value : instruction.value;

}
console.log('convertResult===', result)
this.addPrintEndCommands(result);

@@ -1141,2 +1246,11 @@ return result;

}
/**
* 获取模板中的配置
*
*/
getTemplateConfig() {
return this.template.list.find(item => item.type === 'config')
}
}

@@ -1143,0 +1257,0 @@

+4
-4

@@ -1,4 +0,4 @@

function F(U,d={}){let A="2.2.0",C={small:20,middle:24,large:28,extraLarge:32,xxl:36,xxxl:64},y={s:"small",m:"middle",l:"large",xl:"extraLarge",xxl:"xxl",xxxl:"xxxl"},w=new Map([[0,""],[1,"stroke"],[2,"dot"]]);class m{static getFontSize(e,t){let n=y[t]||"middle";return e[n]||C[n]}static parseTemplateData(e,t,n){if(!e||typeof e!="string")return"";if(!/\{\{/.test(e))return e;let r=e,s=r.match(/{{[a-zA-Z0-9\.]+}}/g);s&&s.forEach(l=>{let c=l.replace(/^\{\{|\}\}$/g,""),a=this.getNestedValue(n,c),p=a!=null&&["string","number"].includes(typeof a)?a:"";r=r.replaceAll(l,p)});let o=r.match(/{{[a-zA-Z0-9\-]+\|l}}/g);return o&&o.forEach(l=>{let c=l.replace(/^\{\{|\|l\}\}$/g,""),a=t?.[c],p=a!=null&&["string","number"].includes(typeof a)?a:"";r=r.replaceAll(l,p)}),r}static getNestedValue(e,t){return typeof e=="string"?e:t.split(".").reduce((n,r)=>n?.[r],e)}static shouldBold(e,t,n,r){return!!e}static generateIndent(e,t,n){if(t!==0)return"";let r="----------------".substring(0,e);return n!==2?r.replace(/\-/g," "):r}}class b{static shouldPrint(e,t){return!(e.show===!1||!this.checkHideFields(e,t)||!this.checkExcludeFields(e,t))}static checkHideFields(e,t){return e.hideFields?e.hideFields.some(r=>{let s=t[r];return s&&(!Array.isArray(s)||s.length>0)}):!0}static checkExcludeFields(e,t){return e.excludeFields?!e.excludeFields.some(r=>{let s=t[r];return s&&(!Array.isArray(s)||s.length>0)}):!0}}class D{constructor(e){this.fontConfig=e}processSize(e,t){let n=t==="size"?e[t]:t,r=n;if(typeof n=="string"){let s=y[n]||n;r=this.fontConfig[s]||C[s]}return{...e,size:r||24}}processAlign(e){return e!==void 0?e:0}processMargins(e){let t={};return e.type==="divider"?(t.marginTop=e.upline??3,t.marginBottom=e.bottomBlank??3):(e.upline!==void 0&&(t.marginTop=e.upline),e.bottomBlank!==void 0&&(t.marginBottom=e.bottomBlank)),t}}class S{constructor(e){this.context=e,this.styleProcessor=new D(e.fontConfig)}convertText(e,t,n,r={}){let{isColumnChild:s=!1,bold:o,size:l,templatePath:c}=r,{text:a,...p}=e,u=o??p.bold,f={value:m.parseTemplateData(a,n,t||{}),...p,...this.styleProcessor.processSize(p,l??"size"),align:this.styleProcessor.processAlign(p.align),bold:m.shouldBold(u,t,"name",n)},N=null;if(c){let P=this.context.createUUIDMapping(c,e,t);P&&(f.templateUUID=P,N=P)}!s&&this.context.type!=="printPic"&&(f={params:f});let v=[{type:"text",...f}];return N&&v[0].params&&(v[0].templateUUID=N),v}convertImage(e,t,n,r=!1,s={}){let{data:o,...l}=e,{templatePath:c}=s;if(!o&&!this.context.enableUUID)return[];let p={value:m.parseTemplateData(o,n,t)?.replace(/^data:image\/[a-zA-Z0-9]+;base64,/,"")||"",align:l.align,...l.maxWidth&&{maxWidth:l.maxWidth}},u=null;if(c){let f=this.context.createUUIDMapping(c,e,t);f&&(p.templateUUID=f,u=f)}!r&&this.context.type!=="printPic"&&(p={params:p});let h=[{type:"image",...p}];return u&&h[0].params&&(h[0].templateUUID=u),h}convertStaticImage(e,t,n,r={}){let{url:s,...o}=e,l=m.parseTemplateData(s,n,t);return this.convertImage({data:l,align:o.align},t,n,!1,r)}convertDivider(e,t=null,n={}){let{templatePath:r}=n,s=n.isColumnChild||!1,o={value:w.get(e.style)||"",marginTop:e?.marginTop??3,marginBottom:e?.marginBottom??3},l=null;if(r){let a=this.context.createUUIDMapping(r,e,t);a&&(o.templateUUID=a,l=a)}!s&&this.context.type!=="printPic"&&(o={params:o});let c=[{type:"dividing",...o}];return l&&c[0].params&&(c[0].templateUUID=l),c}convertQrCode(e,t,n,r={}){let{code:s,...o}=e,l=m.parseTemplateData(s,n,t);return l.match(/^data:image\/png;base64,/)?this.convertImage({data:l,align:o.align},t,n,!1,r):this.context.type==="printPic"?[{type:"qr",value:l,align:o.align}]:[{type:"qrcode",params:{...o,value:l}}]}convertBarCode(e,t,n,r={}){let{code:s,...o}=e,l=m.parseTemplateData(s,n,t);return this.context.type==="printPic"?[{type:"barcode",value:l,height:10,format:e.symbology,...o}]:[{type:"barcode",params:{...o,value:l,format:e.symbology}}]}}class ${constructor(e,t){this.context=e,this.converter=t}convertColumns(e,t,n,r={}){let{columns:s,level:o,dataKey:l,titleBold:c,bodyBold:a,headerSize:p,bodySize:u,fields:h}=e,f=[];return this.hasColumnTitles(s)&&f.push(this.createColumnHeader(s,t,n,c,p,r,l)),l&&this.context.data[l]&&Array.isArray(this.context.data[l])?this.context.data[l].forEach((N,v)=>{let P={...r,templatePath:r.templatePath?`${r.templatePath}.data[${v}]`:`data[${v}]`};f.push(...this.createColumnRows(s,N,n,o,0,a,u,h,P,l))}):f.push(...this.createColumnRows(s,t,n,o,0,a,u,h,r,l)),f}convertColumnInColumn(e,t,n,r={}){return!e?.columns||!Array.isArray(e.columns)?[]:[{type:"columns",params:{items:this.processNestedColumnItems(e.columns,t,n,r)},...this.context.enableUUID&&r.templatePath?{templateUUID:this.context.createUUIDMapping(r.templatePath,e,t)}:{}}]}hasColumnTitles(e){return e.some(t=>t.title!=null)}createColumnHeader(e,t,n,r,s,o={},l=null){let c=e.filter(a=>a.show!==!1).map(a=>{let{title:p,...u}=a;return{...this.converter.styleProcessor.processSize(u,s),text:p}});return{type:"columns",params:{items:c.reduce((a,p,u)=>{let h={isColumnChild:!0,bold:r,templatePath:o.templatePath?`${o.templatePath}.header[${u}]`:`header[${u}]`};return a.push(...this.converter.convertText(p,t,n,h)),a},[])},...this.context.enableUUID&&o.templatePath?{templateUUID:this.context.createUUIDMapping(`${o.templatePath}.header`,{titles:c},t,l)}:{}}}createColumnRows(e,t,n,r,s,o,l,c=null,a={},p=null){let u=c?.find(g=>g?.dataId===t?.dataId),h=u?.param?.bold??o,f=u?.param?.size??l,v=e.filter(g=>g.show!==!1).map(g=>{let x=m.parseTemplateData(g.text,n,t),I=x&&x.trim()!=="";return{...g,parsedText:x,hasValue:I}}),P=v.filter(g=>g.hasValue).length,L=v;if(P===1){let g=v.reduce((x,I)=>x+(I.weight||1),0);L=v.map(x=>({...x,weight:x.hasValue?g:0}))}let B=[{type:"columns",params:{items:L.reduce((g,x,I)=>{let V=m.generateIndent(s,I,this.context.columnIndent),O={isColumnChild:!0,bold:h,size:f,templatePath:a.templatePath?`${a.templatePath}.row[${I}]`:`row[${I}]`};return g.push(...this.converter.convertText({...x,text:V+x.parsedText,weight:x.weight},t,n,O)),g},[])},...this.context.enableUUID&&a.templatePath?{templateUUID:this.context.createUUIDMapping(`${a.templatePath}.row`,L,t,p)}:{}}];return r&&Array.isArray(t[r])&&t[r].forEach((g,x)=>{let I={...a,templatePath:a.templatePath?`${a.templatePath}.children[${x}]`:`children[${x}]`};B.push(...this.createColumnRows(e,g,n,r,s+1,o,l,c,I,p))}),B}processNestedColumnItems(e,t,n,r={}){let s=[];for(let o=0;o<e.length;o++){let l=e[o];if(!b.shouldPrint(l,t))continue;let c=this.applyMargins(l),a={...r,templatePath:r.templatePath?`${r.templatePath}.items[${o}]`:`items[${o}]`};switch(c.type){case"text":s.push(...this.converter.convertText(c.param,t,n,{isColumnChild:!0,templatePath:a.templatePath}));break;case"image":s.push(...this.converter.convertImage(c.param,t,n,!0,a));break;case"staticImage":s.push(...this.converter.convertStaticImage(c.param,t,n,a));break;case"divider":s.push(...this.converter.convertDivider(c.param,t,{isColumnChild:!0,templatePath:a.templatePath}));break;case"row":s.push(this.processRowType(c,t,n,a));break;case"column":s.push(...this.convertColumns(c.param,t,n,a));break;default:console.warn(`Unknown item type in columnInColumn: ${c.type}`)}}return s}processRowType(e,t,n,r={}){if(!e.param?.rows||!Array.isArray(e.param.rows))return null;let s=e.param.rows.map((o,l)=>{let c={...r,templatePath:r.templatePath?`${r.templatePath}.rows[${l}]`:`rows[${l}]`},a=this.processNestedColumnItems([o],t,n,c);return a.length===1&&a[0].type==="columns"?a[0]:{type:"columns",params:{items:a}}});return{type:"rows",weight:e.param.weight||1,items:s,...this.context.enableUUID&&r.templatePath?{templateUUID:this.context.createUUIDMapping(r.templatePath,e.param,t)}:{}}}applyMargins(e){let t=this.converter.styleProcessor.processMargins(e);return{...e,param:{...e.param,...t}}}}class k{constructor(e){this.context=e,this.componentConverter=new S(e),this.columnProcessor=new $(e,this.componentConverter)}processComponent(e,t=""){if(!b.shouldPrint(e,this.context.data))return[];let n=this.applyMargins(e),{param:r,loopKey:s}=n;return s?this.processLoopComponent(n,t):this.processSingleComponent(n,null,t)}processLoopComponent(e,t=""){let n=this.context.data[e.loopKey]||[],r=[];for(let s=0;s<n.length;s++){let o=n[s],l=`${t}.loop[${s}]`,c=this.processSingleComponent({...e,loopKey:void 0},o,l);r.push(...c)}return r}processSingleComponent(e,t=null,n=""){let r=t||this.context.data,{param:s,type:o}=e,l={templatePath:n};switch(o){case"text":return this.componentConverter.convertText(s,r,this.context.lang,l);case"column":return this.columnProcessor.convertColumns(s,r,this.context.lang,l);case"columnInColumn":return this.columnProcessor.convertColumnInColumn(s,r,this.context.lang,l);case"image":return this.componentConverter.convertImage(s,r,this.context.lang,!1,l);case"staticImage":return this.componentConverter.convertStaticImage(s,r,this.context.lang,l);case"divider":return this.componentConverter.convertDivider(s,r,l);case"qr":return this.componentConverter.convertQrCode(s,r,this.context.lang,l);case"brcode":return this.componentConverter.convertBarCode(s,r,this.context.lang,l);case"config":return[];default:return console.warn(`Unknown component type: ${o}`),[]}}wrapWithLineNumber(e){if(!this.context.enableLineNumbers||e.type==="cutPaper"||e.type==="beep"||e.type==="dividing")return e;let n={type:"text",value:`${(this.context.lineNumberCounter++).toString()}`,weight:1,align:0,size:20},r=e.templateUUID;if(e.type==="columns"&&e.params&&e.params.items)return{type:"columns",params:{...e.params.marginTop&&{marginTop:e.params.marginTop},items:[n,{type:"rows",weight:9,items:[{type:"columns",params:{items:e.params.items},...r&&{templateUUID:r}}]}]},_isLineNumberWrapped:!0,...r&&{templateUUID:r}};let s=e.params?e.params.value:e.value,o=s!=null?String(s):"";return{type:"columns",params:{items:[n,{type:e.type,weight:9,...e.params||{},value:o,align:e.params?e.params.align||0:e.align||0,size:e.params?e.params.size||24:e.size||24,bold:e.params?e.params.bold||!1:e.bold||!1,...r&&{templateUUID:r}}]},_isLineNumberWrapped:!0,...r&&{templateUUID:r}}}wrapInstructionsWithLineNumbers(e){return this.context.enableLineNumbers?e.map(t=>this.wrapWithLineNumber(t)):e}applyMargins(e){let t=this.componentConverter.styleProcessor.processMargins(e);return{...e,param:{...e.param,...t}}}addPrintEndCommands(e){e.push({type:"cutPaper",params:{mode:1}}),this.context.enableBuzz&&e.push({type:"beep",params:{beepN:1,beepT:2}})}convert(){if(console.log(`convertTemplate version: ${A}`),!this.context.data||!this.context.template?.list)return[];let e=[];for(let t=0;t<this.context.template.list.length;t++){let n=this.context.template.list[t],r=`list.${t}`,s=this.processComponent(n,r);this.context.enableLineNumbers?e.push(...this.wrapInstructionsWithLineNumbers(s)):e.push(...s)}if(this.context.enableUUID){let t=this.context.getUUIDMappings();e._uuidMappings=t}return this.addPrintEndCommands(e),e}}class z{constructor({type:e,template:t,data:n,langKey:r,options:s={}}){this.type=e,this.data=n,this.template=this.parseTemplate(t),this.lang=this.parseLang(r),this.fontConfig=s.fontSize||C,this.enableBuzz=s.enableBuzz||!1,this.columnIndent=s.columnIndent||"",this.marginLeft=s.marginLeft||0;let o=this.template.list?.find(l=>l.type==="config");this.enableLineNumbers=o?.param?.enableLineNumbers||s.enableLineNumbers||!1,this.lineNumberCounter=1,this.qrCodeGenerator=s.qrCodeGenerator||(typeof max<"u"?max.converter?.qrCode:null),this.enableUUID=s.enableUUID||!1,this.uuidMapping=new Map,this.templateMapping=new Map}generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}createUUIDMapping(e,t,n=null,r=null){if(!this.enableUUID)return null;if(this.templateMapping.has(e))return this.templateMapping.get(e);let s=n;r&&(e.includes(".row")||e.includes(".header"))&&(s={...n,namespace:r,dataId:n?.dataId||`${r}.row`});let o=this.generateUUID();return this.uuidMapping.set(o,{templatePath:e,component:t,renderData:s,timestamp:Date.now()}),this.templateMapping.set(e,o),o}getUUIDMappings(){return this.enableUUID?{uuidToTemplate:Object.fromEntries(this.uuidMapping),templateToUuid:Object.fromEntries(this.templateMapping)}:null}parseTemplate(e){return{...e,list:typeof e?.list=="string"?JSON.parse(e?.list):e?.list,lang:typeof e?.lang=="string"?JSON.parse(e?.lang):e?.lang}}parseLang(e){let t=e||this.template.defaultLang;if(this.template.lang?.[t])return this.template.lang[t];if(this.template.lang&&t){let r=Object.keys(this.template.lang)?.find(s=>s.toLowerCase().startsWith(t.toLowerCase()+"-"));if(r)return this.template.lang[r]}return this.template.lang}}try{let i=new z({...U,options:d});return new k(i).convert()}catch(i){return console.error("Template conversion failed:",i),[]}finally{console.warn("Template conversion end")}}function E(U,d){function A(i){return(i.params?.value||i.value)==="dot"?["\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014".substring(0,d)]:["----------------------------------------------------------".substring(0,d)]}function C(i){let e=0;for(let t=0;t<i.length;t++){let n=i.charAt(t);/[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/.test(n)?e+=2:e+=1}return e}function y(i,e){let t=0,n="";for(let r=0;r<i.length;r++){let s=i.charAt(r),o=/[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/.test(s)?2:1;if(t+o>e)break;n+=s,t+=o}return n}function w(i,e){let t=[];return(i!=null?String(i):"").split(/\n/g).forEach(r=>{for(;r.length>0;){let s=y(r,e);t.push(s);let o=0,l=0;for(let c=0;c<r.length;c++){let a=r.charAt(c),p=/[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/.test(a)?2:1;if(l+p>e)break;l+=p,o++}r=r.substring(o)}}),t}let m=" ";function b(i,e,t){let n=C(i);if(e<=n)return i;let r=e-n;switch(t){case"right":i=m.substring(0,r)+i;break;case"left":i=i+m.substring(0,r);break;case"center":i=m.substring(0,Math.floor(r/2))+i+m.substring(0,Math.ceil(r/2));break}return i}function D(i,e,t){return w(i,e).map(r=>b(r,e,t==null||t==0?"left":t==2?"right":"center"))}function S(i,e){return D(i.params.value,e,i.params.align)}function $(i){let e=i.params.items.map(a=>{let p=!1,u="";return a.value?(p=a.value.trim()!=="",u=a.value):a.type==="rows"&&(u=k(a).join(`
`),p=u.trim()!==""),{...a,hasValue:p,textContent:u}}),t=e.filter(a=>a.hasValue).length,n=e;if(t===1){let a=e.reduce((p,u)=>p+(u.weight||1),0);n=e.map(p=>({...p,weight:p.hasValue?a:0}))}let r=n.reduce((a,p)=>a+(p.weight||1),0),s=n.map(a=>Math.floor(d*(a.weight||1)/r));s[s.length-1]+=d-s.reduce((a,p)=>a+p,0);let o=0,l=n.map((a,p)=>{let u;if(a.type==="rows"){let h=k(a);u=h.length>0?h:[""]}else u=D(a.textContent||a.value||"",s[p],a.align);return o=Math.max(o,u.length),u}),c=[];for(let a=0;a<o;a++)c.push(l.reduce((p,u,h)=>p+(u[a]?u[a]:b("",s[h],"left")),""));return c}function k(i){let e=[];return i.items&&Array.isArray(i.items)&&i.items.forEach(t=>{e.push(...z(t))}),e}function z(i){switch(i.type){case"dividing":case"divider":return A(i);case"text":return S(i,d);case"columns":return $(i);case"rows":return k(i);case"cutPaper":return["========== \u5207\u7EB8 =========="];case"beep":return["*** \u8702\u9E23 ***"];case"qrcode":return[`[QR\u7801: ${i.params?.value||"N/A"}]`];case"barcode":return[`[\u6761\u5F62\u7801: ${i.params?.value||"N/A"}]`];case"image":return["[\u56FE\u7247]"];default:return console.warn(`Unknown item type in toStringText: ${i.type}`),[]}}return U.reduce((i,e)=>(i.push(...z(e)),i),[])}import T from"fs";import M from"path";import{execSync as W}from"child_process";function R(U){try{let d=W("adb devices",{encoding:"utf8"});console.log("ADB devices:",d),d.includes(" device")?(W("adb shell mkdir -p /sdcard/MaxFile/test/",{encoding:"utf8"}),console.log("Created directory: /sdcard/MaxFile/test/"),W(`adb push "${U}" /sdcard/MaxFile/test/max.json`,{encoding:"utf8"}),console.log("Successfully pushed printData.json to /sdcard/MaxFile/test/max.json on Android device")):console.log("No Android device connected. Skipping file push.")}catch(d){console.error("Error pushing file to Android device:",d.message)}}async function Q(U,d,A={}){let C=await F({type:"print",template:U,data:d,langKey:"zh-CN"},{...U.options,...A}),y=M.join(process.cwd(),"output");T.existsSync(y)||T.mkdirSync(y,{recursive:!0});let w=M.join(y,"printData.json");T.writeFileSync(w,JSON.stringify(C,null,2),"utf8"),console.log(`PrintData saved to: ${w}`);let m=M.join(y,"template.json");U.data=d,T.writeFileSync(m,JSON.stringify(U,null,2),"utf8"),console.log(`Template saved to: ${m}`);let b=M.join(M.dirname(import.meta.url.replace("file://","")),"convertTemplate.mjs"),D=M.join(y,"convertTemplate.js");T.existsSync(b)&&(T.copyFileSync(b,D),console.log(`ConvertTemplate saved to: ${D}`)),R(w);let S=E(C,60).join(`
`),$=M.join(y,"receipt.txt");T.writeFileSync($,S,"utf8"),console.log(`Receipt text saved to: ${$}`),console.log(`
--- Receipt Preview ---`),console.log(S)}export{F as convertTemplate,Q as print,R as sendToPrinter};
function E(C,y={}){let L="2.2.2",T={small:20,middle:24,large:28,extraLarge:32,xxl:36,xxxl:64},U={s:"small",m:"middle",l:"large",xl:"extraLarge",xxl:"xxl",xxxl:"xxxl"},D=new Map([[0,""],[1,"stroke"],[2,"dot"]]);class g{static getFontSize(e,t){let n=U[t]||"middle";return e[n]||T[n]}static parseTemplateData(e,t,n,s,r=null){if(!e||typeof e!="string")return"";if(!/\{\{/.test(e))return e;let o=e,l=o.match(/{{[a-zA-Z0-9\.]+}}/g);l&&l.forEach(a=>{let c=a.replace(/^\{\{|\}\}$/g,""),{supported:u=[],supportedIds:h=[]}=s?.param?.multiLanguage??{};if(s?.param?.enableMultiLanguage===!0&&h.includes(a)&&r){let[m,f]=u,x=r[m]?.[c],d=r[f]?.[c],b=`${x!==null&&["string","number"].includes(typeof x)?x:""}${d!==null&&["string","number"].includes(typeof d)?`(${d})`:""}`;o=o.replaceAll(a,b)}else{let m=this.getNestedValue(n,c),f=m!=null&&["string","number"].includes(typeof m)?m:"";o=o.replaceAll(a,f)}});let p=o.match(/{{[a-zA-Z0-9\-]+\|l}}/g);return p&&p.forEach(a=>{let c=a.replace(/^\{\{|\|l\}\}$/g,""),{supported:u=[],supportedIds:h=[]}=s?.param?.multiLanguage??{};if(s?.param?.enableMultiLanguage===!0&&h.includes(a)&&r){let[m,f]=u,x=r[m]?.[c],d=r[f]?.[c],b=`${x!==null&&["string","number"].includes(typeof x)?x:""}${d!==null&&["string","number"].includes(typeof d)?`(${d})`:""}`;o=o.replaceAll(a,b)}else{let m=t?.[c],f=m!=null&&["string","number"].includes(typeof m)?m:"";o=o.replaceAll(a,f)}}),o}static getNestedValue(e,t){return typeof e=="string"?e:t.split(".").reduce((n,s)=>n?.[s],e)}static shouldBold(e,t,n,s){return!!e}static generateIndent(e,t,n){if(t!==0)return"";let s="----------------".substring(0,e);return n!==2?s.replace(/\-/g," "):s}}class P{static shouldPrint(e,t){return!(e.show===!1||!this.checkHideFields(e,t)||!this.checkExcludeFields(e,t))}static checkHideFields(e,t){return e.hideFields?e.hideFields.some(s=>{let r=t[s];return r&&(!Array.isArray(r)||r.length>0)}):!0}static checkExcludeFields(e,t){return e.excludeFields?!e.excludeFields.some(s=>{let r=t[s];return r&&(!Array.isArray(r)||r.length>0)}):!0}}class ${constructor(e){this.fontConfig=e}processSize(e,t){let n=t==="size"?e[t]:t,s=n;if(typeof n=="string"){let r=U[n]||n;s=this.fontConfig[r]||T[r]}return{...e,size:s||24}}processAlign(e){return e!==void 0?e:0}processMargins(e){let t={};return e.type==="divider"?(t.marginTop=e.upline??3,t.marginBottom=e.bottomBlank??3):(e.upline!==void 0&&(t.marginTop=e.upline),e.bottomBlank!==void 0&&(t.marginBottom=e.bottomBlank)),t}}class N{constructor(e){this.context=e,this.styleProcessor=new $(e.fontConfig)}convertText(e,t,n,s={}){let{isColumnChild:r=!1,bold:o,size:l,templatePath:p}=s,{text:a,...c}=e,u=o??c.bold,h=this.context.getTemplateConfig(),f={value:g.parseTemplateData(a,n,t||{},h,this.context.template.lang),...c,...this.styleProcessor.processSize(c,l??"size"),align:this.styleProcessor.processAlign(c.align),bold:g.shouldBold(u,t,"name",n)},x=null;if(p){let b=this.context.createUUIDMapping(p,e,t);b&&(f.templateUUID=b,x=b)}!r&&this.context.type!=="printPic"&&(f={params:f});let d=[{type:"text",...f}];return x&&d[0].params&&(d[0].templateUUID=x),d}convertImage(e,t,n,s=!1,r={}){let{data:o,...l}=e,{templatePath:p}=r;if(!o&&!this.context.enableUUID)return[];let c={value:g.parseTemplateData(o,n,t)?.replace(/^data:image\/[a-zA-Z0-9]+;base64,/,"")||"",align:l.align,weight:l.weight,...l.maxWidth&&{maxWidth:l.maxWidth}},u=null;if(p){let m=this.context.createUUIDMapping(p,e,t);m&&(c.templateUUID=m,u=m)}!s&&this.context.type!=="printPic"&&(c={params:c});let h=[{type:"image",...c}];return u&&h[0].params&&(h[0].templateUUID=u),h}convertStaticImage(e,t,n,s={}){let{url:r,...o}=e,l=g.parseTemplateData(r,n,t);return this.convertImage({data:l,align:o.align},t,n,!1,s)}convertDivider(e,t=null,n={}){let{templatePath:s}=n,r=n.isColumnChild||!1,o={value:D.get(e.style)||"",marginTop:e?.marginTop??3,marginBottom:e?.marginBottom??3},l=null;if(s){let a=this.context.createUUIDMapping(s,e,t);a&&(o.templateUUID=a,l=a)}!r&&this.context.type!=="printPic"&&(o={params:o});let p=[{type:"dividing",...o}];return l&&p[0].params&&(p[0].templateUUID=l),p}convertQrCode(e,t,n,s={},r=!1){let{code:o,...l}=e,p=g.parseTemplateData(o,n,t);return p.match(/^data:image\/png;base64,/)?this.convertImage({data:p,align:l.align,weight:l.weight},t,n,r,s):this.context.type==="printPic"?[{type:"qr",value:p,align:l.align}]:[{type:"qrcode",params:{...l,value:p}}]}convertBarCode(e,t,n,s={}){let{code:r,...o}=e,l=g.parseTemplateData(r,n,t);return this.context.type==="printPic"?[{type:"barcode",value:l,height:10,format:e.symbology,...o}]:[{type:"barcode",params:{...o,value:l,format:e.symbology}}]}}class A{constructor(e,t){this.context=e,this.converter=t}convertColumns(e,t,n,s={}){let{columns:r,level:o,dataKey:l,titleBold:p,bodyBold:a,headerSize:c,bodySize:u,fields:h}=e,m=[];return this.hasColumnTitles(r)&&m.push(this.createColumnHeader(r,t,n,p,c,s,l)),l&&this.context.data[l]&&Array.isArray(this.context.data[l])?this.context.data[l].forEach((f,x)=>{let d={...s,templatePath:s.templatePath?`${s.templatePath}.data[${x}]`:`data[${x}]`};m.push(...this.createColumnRows(r,f,n,o,0,a,u,h,d,l))}):m.push(...this.createColumnRows(r,t,n,o,0,a,u,h,s,l)),m}convertColumnInColumn(e,t,n,s={}){return!e?.columns||!Array.isArray(e.columns)?[]:[{type:"columns",params:{items:this.processNestedColumnItems(e.columns,t,n,s)},...this.context.enableUUID&&s.templatePath?{templateUUID:this.context.createUUIDMapping(s.templatePath,e,t)}:{}}]}hasColumnTitles(e){return e.some(t=>t.title!=null)}createColumnHeader(e,t,n,s,r,o={},l=null){let p=e.filter(a=>a.show!==!1).map(a=>{let{title:c,...u}=a;return{...this.converter.styleProcessor.processSize(u,r),text:c}});return{type:"columns",params:{items:p.reduce((a,c,u)=>{let h={isColumnChild:!0,bold:s,templatePath:o.templatePath?`${o.templatePath}.header[${u}]`:`header[${u}]`};return a.push(...this.converter.convertText(c,t,n,h)),a},[])},...this.context.enableUUID&&o.templatePath?{templateUUID:this.context.createUUIDMapping(`${o.templatePath}.header`,{titles:p},t,l)}:{}}}createColumnRows(e,t,n,s,r,o,l,p=null,a={},c=null){let u=p?.find(v=>v?.dataId===t?.dataId),h=u?.param?.bold??o,m=u?.param?.size??l,f=e.filter(v=>v.show!==!1),x=this.context.getTemplateConfig(),d=f.map(v=>{let I=g.parseTemplateData(v.text,n,t,x,this.context.template.lang),w=I&&I.trim()!=="";return{...v,parsedText:I,hasValue:w}}),b=d.filter(v=>v.hasValue).length,V=d;if(b===1){let v=d.reduce((I,w)=>I+(w.weight||1),0);V=d.map(I=>({...I,weight:I.hasValue?v:0}))}let B=[{type:"columns",params:{items:V.reduce((v,I,w)=>{let O=g.generateIndent(r,w,this.context.columnIndent),R={isColumnChild:!0,bold:h,size:m,templatePath:a.templatePath?`${a.templatePath}.row[${w}]`:`row[${w}]`};return v.push(...this.converter.convertText({...I,text:O+I.parsedText,weight:I.weight},t,n,R)),v},[])},...this.context.enableUUID&&a.templatePath?{templateUUID:this.context.createUUIDMapping(`${a.templatePath}.row`,V,t,c)}:{}}];return s&&Array.isArray(t[s])&&t[s].forEach((v,I)=>{let w={...a,templatePath:a.templatePath?`${a.templatePath}.children[${I}]`:`children[${I}]`};B.push(...this.createColumnRows(e,v,n,s,r+1,o,l,p,w,c))}),B}processNestedColumnItems(e,t,n,s={}){let r=[];for(let o=0;o<e.length;o++){let l=e[o];if(!P.shouldPrint(l,t))continue;let p=this.applyMargins(l),a={...s,templatePath:s.templatePath?`${s.templatePath}.items[${o}]`:`items[${o}]`};switch(p.type){case"text":r.push(...this.converter.convertText(p.param,t,n,{isColumnChild:!0,templatePath:a.templatePath}));break;case"image":r.push(...this.converter.convertImage(p.param,t,n,!0,a));break;case"staticImage":r.push(...this.converter.convertStaticImage(p.param,t,n,a));break;case"divider":r.push(...this.converter.convertDivider(p.param,t,{isColumnChild:!0,templatePath:a.templatePath}));break;case"row":r.push(this.processRowType(p,t,n,a));break;case"column":r.push(...this.convertColumns(p.param,t,n,a));break;case"qr":r.push(...this.converter.convertQrCode(p.param,t,n,a,!0));break;default:console.warn(`Unknown item type in columnInColumn: ${p.type}`)}}return r}processRowType(e,t,n,s={}){if(!e.param?.rows||!Array.isArray(e.param.rows))return null;let r=e.param.rows.map((o,l)=>{let p={...s,templatePath:s.templatePath?`${s.templatePath}.rows[${l}]`:`rows[${l}]`},a=this.processNestedColumnItems([o],t,n,p);return a.length===1&&a[0].type==="columns"?a[0]:{type:"columns",params:{items:a}}});return{type:"rows",weight:e.param.weight||1,items:r,...this.context.enableUUID&&s.templatePath?{templateUUID:this.context.createUUIDMapping(s.templatePath,e.param,t)}:{}}}applyMargins(e){let t=this.converter.styleProcessor.processMargins(e);return{...e,param:{...e.param,...t}}}}class z{constructor(e){this.context=e,this.componentConverter=new N(e),this.columnProcessor=new A(e,this.componentConverter)}processComponent(e,t=""){if(!P.shouldPrint(e,this.context.data))return[];let n=this.applyMargins(e),{param:s,loopKey:r}=n;return r?this.processLoopComponent(n,t):this.processSingleComponent(n,null,t)}processLoopComponent(e,t=""){let n=this.context.data[e.loopKey]||[],s=[];for(let r=0;r<n.length;r++){let o=n[r],l=`${t}.loop[${r}]`,p=this.processSingleComponent({...e,loopKey:void 0},o,l);s.push(...p)}return s}processSingleComponent(e,t=null,n=""){let s=t||this.context.data,{param:r,type:o}=e,l={templatePath:n};switch(o){case"text":return this.componentConverter.convertText(r,s,this.context.lang,l);case"column":return this.columnProcessor.convertColumns(r,s,this.context.lang,l);case"columnInColumn":return this.columnProcessor.convertColumnInColumn(r,s,this.context.lang,l);case"image":return this.componentConverter.convertImage(r,s,this.context.lang,!1,l);case"staticImage":return this.componentConverter.convertStaticImage(r,s,this.context.lang,l);case"divider":return this.componentConverter.convertDivider(r,s,l);case"qr":return this.componentConverter.convertQrCode(r,s,this.context.lang,l);case"brcode":return this.componentConverter.convertBarCode(r,s,this.context.lang,l);case"config":return[];default:return console.warn(`Unknown component type: ${o}`),[]}}wrapWithLineNumber(e){if(!this.context.enableLineNumbers||e.type==="cutPaper"||e.type==="beep"||e.type==="dividing")return e;let n={type:"text",value:`${(this.context.lineNumberCounter++).toString()}`,weight:1,align:0,size:20},s=e.templateUUID;if(e.type==="columns"&&e.params&&e.params.items){if(e.params.items.some(a=>a.type==="rows")){let a=e.params.items[0]?.items??[];if(a.length>0)return a.forEach((c,u)=>{c.params.items.unshift(u===0?n:{type:"text",value:`${(this.context.lineNumberCounter++).toString()}`,weight:1,align:0,size:20})}),e}return{type:"columns",params:{...e.params.marginTop&&{marginTop:e.params.marginTop},items:[n,{type:"rows",weight:9,items:[{type:"columns",params:{items:e.params.items},...s&&{templateUUID:s}}]}]},_isLineNumberWrapped:!0,...s&&{templateUUID:s}}}let r=e.params?e.params.value:e.value,o=r!=null?String(r):"";return{type:"columns",params:{items:[n,{type:e.type,weight:9,...e.params||{},value:o,align:e.params?e.params.align||0:e.align||0,size:e.params?e.params.size||24:e.size||24,bold:e.params?e.params.bold||!1:e.bold||!1,...s&&{templateUUID:s}}]},_isLineNumberWrapped:!0,...s&&{templateUUID:s}}}wrapInstructionsWithLineNumbers(e){return this.context.enableLineNumbers?e.map(t=>this.wrapWithLineNumber(t)):e}applyMargins(e){let t=this.componentConverter.styleProcessor.processMargins(e);return{...e,param:{...e.param,...t}}}addPrintEndCommands(e){e.push({type:"cutPaper",params:{mode:1}}),this.context.enableBuzz&&e.push({type:"beep",params:{beepN:1,beepT:2}})}convert(){if(console.log(`convertTemplate version: ${L}`),!this.context.data||!this.context.template?.list)return[];let e=[];for(let t=0;t<this.context.template.list.length;t++){let n=this.context.template.list[t],s=`list.${t}`,r=this.processComponent(n,s);this.context.enableLineNumbers?e.push(...this.wrapInstructionsWithLineNumbers(r)):e.push(...r)}if(this.context.enableUUID){let t=this.context.getUUIDMappings();e._uuidMappings=t}return console.log("convertResult===",e),this.addPrintEndCommands(e),e}}class k{constructor({type:e,template:t,data:n,langKey:s,options:r={}}){this.type=e,this.data=n,this.template=this.parseTemplate(t),this.lang=this.parseLang(s),this.fontConfig=r.fontSize||T,this.enableBuzz=r.enableBuzz||!1,this.columnIndent=r.columnIndent||"",this.marginLeft=r.marginLeft||0;let o=this.template.list?.find(l=>l.type==="config");this.enableLineNumbers=o?.param?.enableLineNumbers||r.enableLineNumbers||!1,this.lineNumberCounter=1,this.qrCodeGenerator=r.qrCodeGenerator||(typeof max<"u"?max.converter?.qrCode:null),this.enableUUID=r.enableUUID||!1,this.uuidMapping=new Map,this.templateMapping=new Map}generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}createUUIDMapping(e,t,n=null,s=null){if(!this.enableUUID)return null;if(this.templateMapping.has(e))return this.templateMapping.get(e);let r=n;s&&(e.includes(".row")||e.includes(".header"))&&(r={...n,namespace:s,dataId:n?.dataId||`${s}.row`});let o=this.generateUUID();return this.uuidMapping.set(o,{templatePath:e,component:t,renderData:r,timestamp:Date.now()}),this.templateMapping.set(e,o),o}getUUIDMappings(){return this.enableUUID?{uuidToTemplate:Object.fromEntries(this.uuidMapping),templateToUuid:Object.fromEntries(this.templateMapping)}:null}parseTemplate(e){return{...e,list:typeof e?.list=="string"?JSON.parse(e?.list):e?.list,lang:typeof e?.lang=="string"?JSON.parse(e?.lang):e?.lang}}parseLang(e){let t=e||this.template.defaultLang;if(this.template.lang?.[t])return this.template.lang[t];if(this.template.lang&&t){let s=Object.keys(this.template.lang)?.find(r=>r.toLowerCase().startsWith(t.toLowerCase()+"-"));if(s)return this.template.lang[s]}return this.template.lang}getTemplateConfig(){return this.template.list.find(e=>e.type==="config")}}try{let i=new k({...C,options:y});return new z(i).convert()}catch(i){return console.error("Template conversion failed:",i),[]}finally{console.warn("Template conversion end")}}function F(C,y){function L(i){return(i.params?.value||i.value)==="dot"?["\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014".substring(0,y)]:["----------------------------------------------------------".substring(0,y)]}function T(i){let e=0;for(let t=0;t<i.length;t++){let n=i.charAt(t);/[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/.test(n)?e+=2:e+=1}return e}function U(i,e){let t=0,n="";for(let s=0;s<i.length;s++){let r=i.charAt(s),o=/[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/.test(r)?2:1;if(t+o>e)break;n+=r,t+=o}return n}function D(i,e){let t=[];return(i!=null?String(i):"").split(/\n/g).forEach(s=>{for(;s.length>0;){let r=U(s,e);t.push(r);let o=0,l=0;for(let p=0;p<s.length;p++){let a=s.charAt(p),c=/[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/.test(a)?2:1;if(l+c>e)break;l+=c,o++}s=s.substring(o)}}),t}let g=" ";function P(i,e,t){let n=T(i);if(e<=n)return i;let s=e-n;switch(t){case"right":i=g.substring(0,s)+i;break;case"left":i=i+g.substring(0,s);break;case"center":i=g.substring(0,Math.floor(s/2))+i+g.substring(0,Math.ceil(s/2));break}return i}function $(i,e,t){return D(i,e).map(s=>P(s,e,t==null||t==0?"left":t==2?"right":"center"))}function N(i,e){return $(i.params.value,e,i.params.align)}function A(i){let e=i.params.items.map(a=>{let c=!1,u="";return a.value?(c=a.value.trim()!=="",u=a.value):a.type==="rows"&&(u=z(a).join(`
`),c=u.trim()!==""),{...a,hasValue:c,textContent:u}}),t=e.filter(a=>a.hasValue).length,n=e;if(t===1){let a=e.reduce((c,u)=>c+(u.weight||1),0);n=e.map(c=>({...c,weight:c.hasValue?a:0}))}let s=n.reduce((a,c)=>a+(c.weight||1),0),r=n.map(a=>Math.floor(y*(a.weight||1)/s));r[r.length-1]+=y-r.reduce((a,c)=>a+c,0);let o=0,l=n.map((a,c)=>{let u;if(a.type==="rows"){let h=z(a);u=h.length>0?h:[""]}else u=$(a.textContent||a.value||"",r[c],a.align);return o=Math.max(o,u.length),u}),p=[];for(let a=0;a<o;a++)p.push(l.reduce((c,u,h)=>c+(u[a]?u[a]:P("",r[h],"left")),""));return p}function z(i){let e=[];return i.items&&Array.isArray(i.items)&&i.items.forEach(t=>{e.push(...k(t))}),e}function k(i){switch(i.type){case"dividing":case"divider":return L(i);case"text":return N(i,y);case"columns":return A(i);case"rows":return z(i);case"cutPaper":return["========== \u5207\u7EB8 =========="];case"beep":return["*** \u8702\u9E23 ***"];case"qrcode":return[`[QR\u7801: ${i.params?.value||"N/A"}]`];case"barcode":return[`[\u6761\u5F62\u7801: ${i.params?.value||"N/A"}]`];case"image":return["[\u56FE\u7247]"];default:return console.warn(`Unknown item type in toStringText: ${i.type}`),[]}}return C.reduce((i,e)=>(i.push(...k(e)),i),[])}import M from"fs";import S from"path";import{execSync as W}from"child_process";function K(C){try{let y=W("adb devices",{encoding:"utf8"});console.log("ADB devices:",y),y.includes(" device")?(W("adb shell mkdir -p /sdcard/MaxFile/test/",{encoding:"utf8"}),console.log("Created directory: /sdcard/MaxFile/test/"),W(`adb push "${C}" /sdcard/MaxFile/test/max.json`,{encoding:"utf8"}),console.log("Successfully pushed printData.json to /sdcard/MaxFile/test/max.json on Android device")):console.log("No Android device connected. Skipping file push.")}catch(y){console.error("Error pushing file to Android device:",y.message)}}async function Y(C,y,L={}){let T=await E({type:"print",template:C,data:y,langKey:"zh-CN"},{...C.options,...L}),U=S.join(process.cwd(),"output");M.existsSync(U)||M.mkdirSync(U,{recursive:!0});let D=S.join(U,"printData.json");M.writeFileSync(D,JSON.stringify(T,null,2),"utf8"),console.log(`PrintData saved to: ${D}`);let g=S.join(U,"template.json");C.data=y,M.writeFileSync(g,JSON.stringify(C,null,2),"utf8"),console.log(`Template saved to: ${g}`);let P=S.join(S.dirname(import.meta.url.replace("file://","")),"convertTemplate.mjs"),$=S.join(U,"convertTemplate.js");M.existsSync(P)&&(M.copyFileSync(P,$),console.log(`ConvertTemplate saved to: ${$}`)),K(D);let N=F(T,60).join(`
`),A=S.join(U,"receipt.txt");M.writeFileSync(A,N,"utf8"),console.log(`Receipt text saved to: ${A}`),console.log(`
--- Receipt Preview ---`),console.log(N)}export{E as convertTemplate,Y as print,K as sendToPrinter};
{
"name": "@sunmi/max-print",
"version": "1.0.9",
"version": "2.2.2",
"type": "module",

@@ -44,2 +44,2 @@ "description": "Max print utility package",

}
}
}