@lark.js/mvc 0.0.10 → 0.0.12

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/vite.cjs CHANGED
@@ -5,6 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
8
11
  var __commonJS = (cb, mod) => function __require() {
9
12
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
13
  };
@@ -30,10 +33,18 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
33
  ));
31
34
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
35
 
36
+ // ../../node_modules/.pnpm/tsup@8.5.1_@swc+core@1.15.4_34a04ed47198e6dd24361ae1f6711a67/node_modules/tsup/assets/cjs_shims.js
37
+ var init_cjs_shims = __esm({
38
+ "../../node_modules/.pnpm/tsup@8.5.1_@swc+core@1.15.4_34a04ed47198e6dd24361ae1f6711a67/node_modules/tsup/assets/cjs_shims.js"() {
39
+ "use strict";
40
+ }
41
+ });
42
+
33
43
  // ../../node_modules/.pnpm/@babel+parser@7.29.7/node_modules/@babel/parser/lib/index.js
34
44
  var require_lib = __commonJS({
35
45
  "../../node_modules/.pnpm/@babel+parser@7.29.7/node_modules/@babel/parser/lib/index.js"(exports2) {
36
46
  "use strict";
47
+ init_cjs_shims();
37
48
  Object.defineProperty(exports2, "__esModule", {
38
49
  value: true
39
50
  });
@@ -14518,7 +14529,7 @@ var require_lib = __commonJS({
14518
14529
  options = Object.assign({}, options);
14519
14530
  try {
14520
14531
  options.sourceType = "module";
14521
- const parser = getParser(options, input);
14532
+ const parser = getParser2(options, input);
14522
14533
  const ast = parser.parse();
14523
14534
  if (parser.sawUnambiguousESM) {
14524
14535
  return ast;
@@ -14526,7 +14537,7 @@ var require_lib = __commonJS({
14526
14537
  if (parser.ambiguousScriptDifferentAst) {
14527
14538
  try {
14528
14539
  options.sourceType = "script";
14529
- return getParser(options, input).parse();
14540
+ return getParser2(options, input).parse();
14530
14541
  } catch (_unused) {
14531
14542
  }
14532
14543
  } else {
@@ -14536,17 +14547,17 @@ var require_lib = __commonJS({
14536
14547
  } catch (moduleError) {
14537
14548
  try {
14538
14549
  options.sourceType = "script";
14539
- return getParser(options, input).parse();
14550
+ return getParser2(options, input).parse();
14540
14551
  } catch (_unused2) {
14541
14552
  }
14542
14553
  throw moduleError;
14543
14554
  }
14544
14555
  } else {
14545
- return getParser(options, input).parse();
14556
+ return getParser2(options, input).parse();
14546
14557
  }
14547
14558
  }
14548
14559
  function parseExpression(input, options) {
14549
- const parser = getParser(options, input);
14560
+ const parser = getParser2(options, input);
14550
14561
  if (parser.options.strictMode) {
14551
14562
  parser.state.strict = true;
14552
14563
  }
@@ -14560,7 +14571,7 @@ var require_lib = __commonJS({
14560
14571
  return tokenTypes2;
14561
14572
  }
14562
14573
  var tokTypes = generateExportedTokenTypes(tt);
14563
- function getParser(options, input) {
14574
+ function getParser2(options, input) {
14564
14575
  let cls = Parser;
14565
14576
  const pluginsMap = /* @__PURE__ */ new Map();
14566
14577
  if (options != null && options.plugins) {
@@ -14609,14 +14620,22 @@ var require_lib = __commonJS({
14609
14620
  var vite_exports = {};
14610
14621
  __export(vite_exports, {
14611
14622
  default: () => vite_default,
14612
- larkMvcPlugin: () => larkMvcPlugin
14623
+ larkMvcPlugin: () => larkMvcPlugin,
14624
+ larkMvcPluginLegacy: () => larkMvcPluginLegacy
14613
14625
  });
14614
14626
  module.exports = __toCommonJS(vite_exports);
14627
+ init_cjs_shims();
14615
14628
  var import_path = __toESM(require("path"), 1);
14616
14629
  var import_fs = __toESM(require("fs"), 1);
14617
14630
 
14618
14631
  // src/compiler.ts
14619
- var import_parser = __toESM(require_lib(), 1);
14632
+ init_cjs_shims();
14633
+
14634
+ // src/compiler/compile-template.ts
14635
+ init_cjs_shims();
14636
+
14637
+ // src/compiler/template-syntax.ts
14638
+ init_cjs_shims();
14620
14639
  var SPLITTER = String.fromCharCode(30);
14621
14640
  var VIEW_ID_PLACEHOLDER = String.fromCharCode(31);
14622
14641
  function jsObjectToUrlParams(paramsStr) {
@@ -14737,7 +14756,7 @@ function convertArtSyntax(source, debug) {
14737
14756
  }
14738
14757
  if (blockStack.length > 0) {
14739
14758
  const unclosed = blockStack.map((b) => `"${b.ctrl}" at line ${b.line}`).join(", ");
14740
- throw new Error(`[@lark.js/mvc error] unclosed block(s): ${unclosed}`);
14759
+ throw new Error(`Unclosed block(s): ${unclosed}`);
14741
14760
  }
14742
14761
  return result.join("");
14743
14762
  }
@@ -14836,7 +14855,7 @@ function convertArtExpression(code, debug, lineNo, blockStack = []) {
14836
14855
  const object = tokens[0];
14837
14856
  if (tokens.length > 1 && tokens[1] !== "as") {
14838
14857
  throw new Error(
14839
- `[@lark.js/mvc error] bad forOf syntax: {{${code}}}. Expected "as" keyword, got "${tokens[1]}". Usage: {{forOf list as item [index]}}`
14858
+ `Bad forOf syntax: {{${code}}}. Expected "as" keyword, got "${tokens[1]}". Usage: {{forOf list as item [index]}}`
14840
14859
  );
14841
14860
  }
14842
14861
  const restTokens = tokens.slice(2);
@@ -14863,7 +14882,7 @@ function convertArtExpression(code, debug, lineNo, blockStack = []) {
14863
14882
  const object = tokens[0];
14864
14883
  if (tokens.length > 1 && tokens[1] !== "as") {
14865
14884
  throw new Error(
14866
- `[@lark.js/mvc error] bad forIn syntax: {{${code}}}. Expected "as" keyword, got "${tokens[1]}". Usage: {{forIn obj as val [key]}}`
14885
+ `Bad forIn syntax: {{${code}}}. Expected "as" keyword, got "${tokens[1]}". Usage: {{forIn obj as val [key]}}`
14867
14886
  );
14868
14887
  }
14869
14888
  const restTokens2 = tokens.slice(2);
@@ -14889,13 +14908,11 @@ function convertArtExpression(code, debug, lineNo, blockStack = []) {
14889
14908
  const expectedCtrl = keyword.substring(1);
14890
14909
  const last = blockStack.pop();
14891
14910
  if (!last) {
14892
- throw new Error(
14893
- `[@lark.js/mvc error] unexpected {{${code}}}: no matching open block`
14894
- );
14911
+ throw new Error(`Unexpected {{${code}}}: no matching open block`);
14895
14912
  }
14896
14913
  if (last.ctrl !== expectedCtrl) {
14897
14914
  throw new Error(
14898
- `[@lark.js/mvc error] unexpected {{${code}}}: expected {{/${last.ctrl}}} to close block opened at line ${last.line}`
14915
+ `Unexpected {{${code}}}: expected {{/${last.ctrl}}} to close block opened at line ${last.line}`
14899
14916
  );
14900
14917
  }
14901
14918
  return `${debugPrefix}<%}%>`;
@@ -14956,112 +14973,219 @@ function parseAsExpr(expr) {
14956
14973
  bad: false
14957
14974
  };
14958
14975
  }
14959
- function compileToFunction(source, debug, file) {
14960
- const matcher = /<%([@=!:])?([\s\S]*?)%>|$/g;
14961
- let index = 0;
14962
- let funcSource = `$out+='`;
14963
- let hasAtRule = false;
14964
- const escapeSlashRegExp = /\\|'/g;
14965
- const escapeBreakReturnRegExp = /\r|\n/g;
14966
- source.replace(matcher, (match, operate, content, offset) => {
14967
- funcSource += source.substring(index, offset).replace(escapeSlashRegExp, "\\$&").replace(escapeBreakReturnRegExp, "\\n");
14968
- index = offset + match.length;
14969
- if (debug) {
14970
- let expr = source.substring(
14971
- index - match.length + 2 + (operate ? 1 : 0),
14972
- index - 2
14973
- );
14974
- const x11 = String.fromCharCode(17);
14975
- const artRegExp = new RegExp(`^'(\\d+)${x11}([^${x11}]+)${x11}'$`);
14976
- const artM = expr.match(artRegExp);
14977
- let art = "";
14978
- let line = -1;
14979
- if (artM) {
14980
- expr = expr.replace(artRegExp, "");
14981
- art = artM[2];
14982
- line = parseInt(artM[1], 10);
14983
- } else {
14984
- expr = expr.replace(escapeSlashRegExp, "\\$&").replace(escapeBreakReturnRegExp, "\\n");
14976
+
14977
+ // src/compiler/compile-to-vdom-function.ts
14978
+ init_cjs_shims();
14979
+ var import_htmlparser2 = require("htmlparser2");
14980
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
14981
+ "area",
14982
+ "base",
14983
+ "br",
14984
+ "col",
14985
+ "embed",
14986
+ "hr",
14987
+ "img",
14988
+ "input",
14989
+ "link",
14990
+ "meta",
14991
+ "param",
14992
+ "source",
14993
+ "track",
14994
+ "wbr"
14995
+ ]);
14996
+ function vdomEscapeStr(s) {
14997
+ return s.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\x1e/g, "\\x1e");
14998
+ }
14999
+ function vdomResolveAttrValue(rawValue, exprStore) {
15000
+ const hasPlaceholders = rawValue.includes("\0");
15001
+ const hasViewId = rawValue.includes("");
15002
+ if (!hasPlaceholders && !hasViewId) {
15003
+ return `'${vdomEscapeStr(rawValue)}'`;
15004
+ }
15005
+ const segments = [];
15006
+ let remaining = rawValue;
15007
+ while (remaining.length > 0) {
15008
+ const phIdx = remaining.indexOf("\0");
15009
+ const viIdx = remaining.indexOf("");
15010
+ let nextSpecial = -1;
15011
+ let specialType = null;
15012
+ if (phIdx >= 0 && (viIdx < 0 || phIdx <= viIdx)) {
15013
+ nextSpecial = phIdx;
15014
+ specialType = "ph";
15015
+ } else if (viIdx >= 0) {
15016
+ nextSpecial = viIdx;
15017
+ specialType = "vi";
15018
+ }
15019
+ if (nextSpecial === -1) {
15020
+ if (remaining) segments.push(`'${vdomEscapeStr(remaining)}'`);
15021
+ break;
15022
+ }
15023
+ if (nextSpecial > 0) {
15024
+ segments.push(`'${vdomEscapeStr(remaining.substring(0, nextSpecial))}'`);
15025
+ }
15026
+ if (specialType === "vi") {
15027
+ segments.push("$viewId");
15028
+ remaining = remaining.substring(nextSpecial + 1);
15029
+ } else {
15030
+ const closeIdx = remaining.indexOf("\0", nextSpecial + 1);
15031
+ if (closeIdx === -1) {
15032
+ segments.push(`'${vdomEscapeStr(remaining.substring(nextSpecial))}'`);
15033
+ break;
14985
15034
  }
14986
- if (operate === "@") {
14987
- hasAtRule = true;
14988
- funcSource += `'+($dbgExpr='<%${operate + expr}%>',$refFn($refAlt,${content}))+'`;
14989
- } else if (operate === "=" || operate === ":") {
14990
- funcSource += `'+($dbgExpr='<%${operate + expr}%>',$encHtml(${content}))+'`;
14991
- } else if (operate === "!") {
14992
- if (!content.startsWith("$encUri(") || !content.endsWith(")")) {
14993
- content = `$strSafe(${content})`;
14994
- }
14995
- funcSource += `'+($dbgExpr='<%${operate + expr}%>',${content})+'`;
14996
- } else if (content) {
14997
- if (line > -1) {
14998
- funcSource += `';$dbgLine=${line};$dbgArt='${art}';`;
14999
- content = "";
15035
+ const idx = parseInt(remaining.substring(nextSpecial + 1, closeIdx));
15036
+ const expr = exprStore[idx];
15037
+ if (expr.op === "=" || expr.op === ":") {
15038
+ segments.push(`$n(${expr.content})`);
15039
+ } else if (expr.op === "!") {
15040
+ if (expr.content.startsWith("$encUri(") && expr.content.endsWith(")")) {
15041
+ segments.push(expr.content);
15000
15042
  } else {
15001
- funcSource += `';`;
15002
- }
15003
- if (funcSource.endsWith(`+'';`)) {
15004
- funcSource = funcSource.substring(0, funcSource.length - 4) + ";";
15005
- }
15006
- if (expr) {
15007
- funcSource += `$dbgExpr='<%${expr}%>';`;
15043
+ segments.push(`$n(${expr.content})`);
15008
15044
  }
15009
- funcSource += content + `;$out+='`;
15045
+ } else if (expr.op === "@") {
15046
+ segments.push(`$refFn($refAlt,${expr.content})`);
15047
+ } else {
15048
+ segments.push(`$n(${expr.content})`);
15010
15049
  }
15011
- } else {
15012
- if (operate === "@") {
15013
- hasAtRule = true;
15014
- funcSource += `'+$refFn($refAlt,${content})+'`;
15015
- } else if (operate === "=" || operate === ":") {
15016
- funcSource += `'+$encHtml(${content})+'`;
15017
- } else if (operate === "!") {
15018
- if (!content.startsWith("$encUri(") || !content.endsWith(")")) {
15019
- content = `$strSafe(${content})`;
15020
- }
15021
- funcSource += `'+${content}+'`;
15022
- } else if (content) {
15023
- funcSource += `';`;
15024
- if (funcSource.endsWith(`+'';`)) {
15025
- funcSource = funcSource.substring(0, funcSource.length - 4) + ";";
15050
+ remaining = remaining.substring(closeIdx + 1);
15051
+ }
15052
+ }
15053
+ if (segments.length === 0) return "''";
15054
+ if (segments.length === 1) return segments[0];
15055
+ return segments.join("+");
15056
+ }
15057
+ function vdomBuildPropsFromAttribs(attribs, exprStore) {
15058
+ if (!attribs) return "null";
15059
+ const keys = Object.keys(attribs);
15060
+ if (keys.length === 0) return "null";
15061
+ const entries = [];
15062
+ for (const name of keys) {
15063
+ const value = attribs[name];
15064
+ const valueExpr = vdomResolveAttrValue(value, exprStore);
15065
+ entries.push(`'${vdomEscapeStr(name)}':${valueExpr}`);
15066
+ }
15067
+ return `{${entries.join(",")}}`;
15068
+ }
15069
+ function compileToVDomFunction(source, debug, file) {
15070
+ const lines = [];
15071
+ let varCounter = 0;
15072
+ let propsCounter = 0;
15073
+ const exprStore = [];
15074
+ const protectedSource = source.replace(
15075
+ /<%([@=!:])?([\s\S]*?)%>/g,
15076
+ (_, op, content) => {
15077
+ const idx = exprStore.length;
15078
+ exprStore.push({ op: op || "", content: (content || "").trim() });
15079
+ return `\0${idx}\0`;
15080
+ }
15081
+ );
15082
+ const doc = (0, import_htmlparser2.parseDocument)(protectedSource, {
15083
+ recognizeSelfClosing: true,
15084
+ lowerCaseTags: false,
15085
+ lowerCaseAttributeNames: false,
15086
+ decodeEntities: false
15087
+ });
15088
+ const rootVar = `$v${varCounter++}`;
15089
+ lines.push(`let ${rootVar}=[]`);
15090
+ const maxVars = 30;
15091
+ const varDecls = [];
15092
+ for (let i = 1; i < maxVars; i++) {
15093
+ varDecls.push(`$v${i}`);
15094
+ }
15095
+ lines.push(`let ${varDecls.join(",")}`);
15096
+ function allocVar() {
15097
+ if (varCounter >= maxVars) return `$v${maxVars - 1}`;
15098
+ return `$v${varCounter++}`;
15099
+ }
15100
+ function emitNode(node, parentVar) {
15101
+ const type = node.type;
15102
+ if (type === "text") {
15103
+ emitText(node.data || "", parentVar);
15104
+ } else if (type === "tag" || type === "script" || type === "style") {
15105
+ emitElement(node, parentVar);
15106
+ }
15107
+ }
15108
+ function emitText(text, parentVar) {
15109
+ const parts = text.split(/\x00(\d+)\x00/);
15110
+ for (let i = 0; i < parts.length; i++) {
15111
+ if (i % 2 === 0) {
15112
+ const trimmed = parts[i];
15113
+ if (trimmed.trim()) {
15114
+ lines.push(`${parentVar}.push($c(0,'${vdomEscapeStr(trimmed)}'))`);
15026
15115
  }
15027
- funcSource += `${content};$out+='`;
15116
+ } else {
15117
+ const idx = parseInt(parts[i]);
15118
+ const expr = exprStore[idx];
15119
+ emitExpr(expr, parentVar);
15028
15120
  }
15029
15121
  }
15030
- return match;
15031
- });
15032
- funcSource += `';`;
15033
- funcSource = funcSource.replace(/\$out\+='';/g, "");
15034
- funcSource = funcSource.replace(/\$out\+=''\+/g, "$out+=");
15122
+ }
15123
+ function emitExpr(expr, parentVar) {
15124
+ if (expr.op === "=" || expr.op === ":") {
15125
+ lines.push(`${parentVar}.push($c(0,$n(${expr.content})))`);
15126
+ } else if (expr.op === "!") {
15127
+ if (expr.content.startsWith("$encUri(") && expr.content.endsWith(")")) {
15128
+ lines.push(`${parentVar}.push($c(0,${expr.content}))`);
15129
+ } else {
15130
+ lines.push(`${parentVar}.push($c(0,$n(${expr.content})))`);
15131
+ }
15132
+ } else if (expr.op === "@") {
15133
+ lines.push(`${parentVar}.push($c(0,$refFn($refAlt,${expr.content})))`);
15134
+ } else if (expr.content) {
15135
+ lines.push(expr.content);
15136
+ }
15137
+ }
15138
+ function emitElement(node, parentVar) {
15139
+ const tagName = node.name || "";
15140
+ const children = node.children || [];
15141
+ const childVar = allocVar();
15142
+ const propsKey = `__p${propsCounter++}`;
15143
+ const props = vdomBuildPropsFromAttribs(node.attribs, exprStore);
15144
+ lines.push(`let ${propsKey}=${props}`);
15145
+ lines.push(`${childVar}=[]`);
15146
+ for (const child of children) {
15147
+ emitNode(child, childVar);
15148
+ }
15149
+ const isVoid = VOID_ELEMENTS.has(tagName) && children.length === 0;
15150
+ const childrenArg = isVoid ? "1" : childVar;
15151
+ lines.push(
15152
+ `${parentVar}.push($c('${tagName}',${propsKey},${childrenArg}))`
15153
+ );
15154
+ }
15155
+ for (const child of doc.children) {
15156
+ emitNode(child, rootVar);
15157
+ }
15158
+ lines.push(`return $c($viewId,0,${rootVar})`);
15159
+ const body = lines.join(";");
15160
+ let funcBody = body;
15035
15161
  if (debug) {
15036
15162
  const filePart = file ? `\\r\\n\\tat file:${file}` : "";
15037
- funcSource = `let $dbgExpr,$dbgArt,$dbgLine;try{${funcSource}}catch(ex){let msg='render view error:'+(ex.message||ex);if($dbgArt)msg+='\\r\\n\\tsrc art:{{'+$dbgArt+'}}\\r\\n\\tat line:'+$dbgLine;msg+='\\r\\n\\t'+($dbgArt?'translate to:':'expr:');msg+=$dbgExpr+'${filePart}';throw msg;}`;
15163
+ funcBody = `let $dbgExpr,$dbgArt,$dbgLine;try{${body}}catch(ex){let msg='render view error:'+(ex.message||ex);msg+='${filePart}';throw msg;}`;
15038
15164
  }
15039
15165
  const viewIdRegExp = new RegExp(String.fromCharCode(31), "g");
15040
- funcSource = funcSource.replace(viewIdRegExp, `'+$viewId+'`);
15041
- void hasAtRule;
15166
+ funcBody = funcBody.replace(viewIdRegExp, `'+$viewId+'`);
15042
15167
  const refFallback = "if(!$refAlt)$refAlt=$data;";
15043
- const fullSource = `${refFallback}let $splitter='\\x1e',$tmp,$out=''{{VARS}};${funcSource}return $out`;
15044
- return `($data,$viewId,$refAlt,$encHtml,$strSafe,$encUri,$refFn,$encQuote)=>{${fullSource}}`;
15168
+ const fullSource = `${refFallback}let $splitter='\\x1e'{{VARS}};${funcBody}`;
15169
+ return `($data,$viewId,$refAlt,$n,$refFn,$encUri,$encQuote)=>{${fullSource}}`;
15045
15170
  }
15046
- function compileTemplate(source, options = {}) {
15047
- const { debug = false, globalVars = [], file } = options;
15048
- const { protectedSource, comments } = protectComments(source);
15049
- const converted = convertArtSyntax(protectedSource, debug);
15050
- const viewEventProcessed = processViewEvents(converted);
15051
- const finalSource = restoreComments(viewEventProcessed, comments);
15052
- const funcBody = compileToFunction(finalSource, debug, file);
15053
- const varDeclarations = globalVars.map((key) => `,${key}=$data.${key}`).join("");
15054
- const funcWithVars = funcBody.replace("{{VARS}}", () => varDeclarations);
15055
- return `import { encHtml as __larkEncHtml, strSafe as __larkStrSafe, encUri as __larkEncUri, encQuote as __larkEncQuote, refFn as __larkRefFn } from "@lark.js/mvc/runtime";
15056
- export default function(data, viewId, refData) {
15057
- let $data = data || {},
15058
- $viewId = viewId || '';
15059
- return (${funcWithVars})($data, $viewId, refData,
15060
- __larkEncHtml, __larkStrSafe, __larkEncUri, __larkRefFn, __larkEncQuote
15061
- );
15062
- }`;
15171
+
15172
+ // src/compiler/swc/extract-global-vars.ts
15173
+ init_cjs_shims();
15174
+ var parseSyncFn = null;
15175
+ var parseSyncLoadAttempted = false;
15176
+ async function getParser() {
15177
+ if (!parseSyncLoadAttempted) {
15178
+ parseSyncLoadAttempted = true;
15179
+ try {
15180
+ const swc = await import("@swc/core");
15181
+ parseSyncFn = swc.parseSync;
15182
+ } catch (err) {
15183
+ console.error("failed to load @swc/core", err);
15184
+ }
15185
+ }
15186
+ return parseSyncFn;
15063
15187
  }
15064
- function extractGlobalVars(source) {
15188
+ async function extractGlobalVars(source) {
15065
15189
  const { protectedSource, comments: _comments } = protectComments(source);
15066
15190
  const viewEventProcessed = processViewEvents(protectedSource);
15067
15191
  const converted = convertArtSyntax(viewEventProcessed, false);
@@ -15090,12 +15214,15 @@ function extractGlobalVars(source) {
15090
15214
  );
15091
15215
  let fn = fnParts.join("");
15092
15216
  fn = `(function(){${fn}})`;
15217
+ const parseSync = await getParser();
15218
+ if (!parseSync) {
15219
+ return fallbackExtractVariables(source);
15220
+ }
15093
15221
  let ast;
15094
15222
  try {
15095
- ast = (0, import_parser.parse)(fn, {
15096
- sourceType: "script",
15097
- allowReturnOutsideFunction: true,
15098
- allowAwaitOutsideFunction: true
15223
+ ast = parseSync(fn, {
15224
+ syntax: "ecmascript",
15225
+ target: "es2022"
15099
15226
  });
15100
15227
  } catch {
15101
15228
  return fallbackExtractVariables(source);
@@ -15103,55 +15230,55 @@ function extractGlobalVars(source) {
15103
15230
  const globalExists = {};
15104
15231
  for (const name of BUILTIN_GLOBALS) globalExists[name] = 1;
15105
15232
  const globalVars = /* @__PURE__ */ Object.create(null);
15106
- const fnRange = [];
15107
- walkAst(ast, {
15233
+ const fnNodes = [];
15234
+ walkSwcAst(ast, {
15108
15235
  VariableDeclarator(node) {
15109
15236
  if (node.id.type === "Identifier") {
15110
- const name = node.id.name;
15237
+ const name = node.id.value;
15111
15238
  globalExists[name] = node.init ? 3 : 2;
15112
15239
  }
15113
15240
  },
15114
15241
  FunctionDeclaration(node) {
15115
- if (node.id) {
15116
- globalExists[node.id.name] = 3;
15242
+ if (node.identifier) {
15243
+ globalExists[node.identifier.value] = 3;
15117
15244
  }
15118
- fnRange.push(node);
15245
+ fnNodes.push(node);
15119
15246
  },
15120
15247
  FunctionExpression(node) {
15121
- fnRange.push(node);
15248
+ fnNodes.push(node);
15122
15249
  },
15123
15250
  ArrowFunctionExpression(node) {
15124
- fnRange.push(node);
15251
+ fnNodes.push(node);
15125
15252
  },
15126
15253
  CallExpression(node) {
15127
15254
  if (node.callee.type === "Identifier") {
15128
- globalExists[node.callee.name] = 1;
15255
+ globalExists[node.callee.value] = 1;
15129
15256
  }
15130
15257
  }
15131
15258
  });
15132
15259
  const functionParams = /* @__PURE__ */ Object.create(null);
15133
- for (const fnNode of fnRange) {
15134
- const params = "params" in fnNode ? fnNode.params : [];
15135
- for (const p of params) {
15136
- if (p.type === "Identifier") {
15137
- functionParams[p.name] = 1;
15138
- } else if (p.type === "AssignmentPattern" && p.left.type === "Identifier") {
15139
- functionParams[p.left.name] = 1;
15140
- } else if (p.type === "RestElement" && p.argument.type === "Identifier") {
15141
- functionParams[p.argument.name] = 1;
15260
+ for (const fnNode of fnNodes) {
15261
+ const patterns = getParamPatterns(fnNode);
15262
+ for (const pat of patterns) {
15263
+ if (pat.type === "Identifier") {
15264
+ functionParams[pat.value] = 1;
15265
+ } else if (pat.type === "AssignmentPattern" && pat.left.type === "Identifier") {
15266
+ functionParams[pat.left.value] = 1;
15267
+ } else if (pat.type === "RestElement" && pat.argument.type === "Identifier") {
15268
+ functionParams[pat.argument.value] = 1;
15142
15269
  }
15143
15270
  }
15144
15271
  }
15145
- walkAst(ast, {
15272
+ walkSwcAst(ast, {
15146
15273
  Identifier(node) {
15147
- const name = node.name;
15274
+ const name = node.value;
15148
15275
  if (globalExists[name]) return;
15149
15276
  if (functionParams[name]) return;
15150
15277
  globalVars[name] = 1;
15151
15278
  },
15152
15279
  AssignmentExpression(node) {
15153
15280
  if (node.left.type === "Identifier") {
15154
- const name = node.left.name;
15281
+ const name = node.left.value;
15155
15282
  if (!globalExists[name] || globalExists[name] === 1) {
15156
15283
  globalExists[name] = (globalExists[name] || 0) + 1;
15157
15284
  }
@@ -15160,6 +15287,12 @@ function extractGlobalVars(source) {
15160
15287
  });
15161
15288
  return Object.keys(globalVars);
15162
15289
  }
15290
+ function getParamPatterns(fnNode) {
15291
+ if (fnNode.type === "ArrowFunctionExpression") {
15292
+ return fnNode.params;
15293
+ }
15294
+ return fnNode.params.map((p) => p.pat);
15295
+ }
15163
15296
  function fallbackExtractVariables(source) {
15164
15297
  const vars = /* @__PURE__ */ new Set();
15165
15298
  const outputRegExp = /\{\{[:=!@]\s*([a-zA-Z_$][\w$]*)[^}]*\}\}/g;
@@ -15177,41 +15310,39 @@ function fallbackExtractVariables(source) {
15177
15310
  }
15178
15311
  return Array.from(vars).filter((v) => !BUILTIN_GLOBALS.has(v));
15179
15312
  }
15180
- function walkAst(ast, visitors) {
15313
+ function walkSwcAst(ast, visitors) {
15181
15314
  function visit(node) {
15182
15315
  const type = node.type;
15183
15316
  if (visitors[type]) {
15184
15317
  visitors[type](node);
15185
15318
  }
15186
- const bag = node;
15187
15319
  for (const key of Object.keys(node)) {
15188
- if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "range")
15189
- continue;
15320
+ if (key === "type" || key === "span" || key === "ctxt") continue;
15190
15321
  if (type === "MemberExpression" && key === "property") {
15191
15322
  const me = node;
15192
- if (!me.computed) continue;
15323
+ if (me.property.type !== "Computed") continue;
15193
15324
  }
15194
- if (type === "ObjectProperty" && key === "key") {
15195
- const op = node;
15196
- if (!op.computed) continue;
15325
+ if (type === "KeyValueProperty" && key === "key") {
15326
+ const kv = node;
15327
+ if (kv.key.type !== "Computed") continue;
15197
15328
  }
15198
- if (type === "ObjectMethod" && key === "key") {
15199
- const om = node;
15200
- if (!om.computed) continue;
15329
+ if (type === "MethodProperty" && key === "key") {
15330
+ const mp = node;
15331
+ if (mp.key.type !== "Computed") continue;
15201
15332
  }
15202
- const child = bag[key];
15333
+ const child = Reflect.get(node, key);
15203
15334
  if (Array.isArray(child)) {
15204
15335
  for (const item of child) {
15205
- if (isAstNode(item)) visit(item);
15336
+ if (isSwcNode(item)) visit(item);
15206
15337
  }
15207
- } else if (isAstNode(child)) {
15338
+ } else if (isSwcNode(child)) {
15208
15339
  visit(child);
15209
15340
  }
15210
15341
  }
15211
15342
  }
15212
15343
  visit(ast);
15213
15344
  }
15214
- function isAstNode(v) {
15345
+ function isSwcNode(v) {
15215
15346
  return !!v && typeof v === "object" && typeof v.type === "string";
15216
15347
  }
15217
15348
  var BUILTIN_GLOBALS = /* @__PURE__ */ new Set([
@@ -15356,7 +15487,7 @@ var BUILTIN_GLOBALS = /* @__PURE__ */ new Set([
15356
15487
  "decodeURIComponent",
15357
15488
  "encodeURI",
15358
15489
  "decodeURI",
15359
- // Babel helpers
15490
+ // SWC helpers
15360
15491
  "arguments",
15361
15492
  "this",
15362
15493
  "require",
@@ -15364,32 +15495,505 @@ var BUILTIN_GLOBALS = /* @__PURE__ */ new Set([
15364
15495
  "Lark"
15365
15496
  ]);
15366
15497
 
15367
- // src/vite.ts
15368
- var LARK_TEMPLATE_SUFFIX = "?lark-template";
15369
- function larkMvcPlugin(options = {}) {
15370
- const { debug = false } = options;
15371
- return {
15372
- name: "lark-template",
15373
- enforce: "pre",
15374
- resolveId(source, importer) {
15375
- if (source.endsWith(".html") && importer) {
15376
- return import_path.default.resolve(import_path.default.dirname(importer), source) + LARK_TEMPLATE_SUFFIX;
15498
+ // src/compiler/extract-global-vars.ts
15499
+ init_cjs_shims();
15500
+ var import_parser = __toESM(require_lib(), 1);
15501
+ async function extractGlobalVars2(source) {
15502
+ const { protectedSource, comments: _comments } = protectComments(source);
15503
+ const viewEventProcessed = processViewEvents(protectedSource);
15504
+ const converted = convertArtSyntax(viewEventProcessed, false);
15505
+ const template = restoreComments(converted, _comments);
15506
+ const templateCmdRegExp = /<%([@=!:])?([\s\S]*?)%>|$/g;
15507
+ const fnParts = [];
15508
+ const htmlStore = {};
15509
+ let htmlIndex = 0;
15510
+ let lastIndex = 0;
15511
+ const htmlKey = String.fromCharCode(5);
15512
+ template.replace(
15513
+ templateCmdRegExp,
15514
+ (match, operate, content, offset) => {
15515
+ const start = operate ? 3 : 2;
15516
+ const htmlText = template.substring(lastIndex, offset + start);
15517
+ const key = htmlKey + htmlIndex++ + htmlKey;
15518
+ htmlStore[key] = htmlText;
15519
+ lastIndex = offset + match.length - 2;
15520
+ if (operate && content.trim()) {
15521
+ fnParts.push(';"' + key + '";', "[" + content + "]");
15522
+ } else {
15523
+ fnParts.push(';"' + key + '";', content || "");
15524
+ }
15525
+ return match;
15526
+ }
15527
+ );
15528
+ let fn = fnParts.join("");
15529
+ fn = `(function(){${fn}})`;
15530
+ let ast;
15531
+ try {
15532
+ ast = (0, import_parser.parse)(fn, {
15533
+ sourceType: "script",
15534
+ allowReturnOutsideFunction: true,
15535
+ allowAwaitOutsideFunction: true
15536
+ });
15537
+ } catch {
15538
+ return fallbackExtractVariables2(source);
15539
+ }
15540
+ const globalExists = {};
15541
+ for (const name of BUILTIN_GLOBALS2) globalExists[name] = 1;
15542
+ const globalVars = /* @__PURE__ */ Object.create(null);
15543
+ const fnRange = [];
15544
+ walkAst(ast, {
15545
+ VariableDeclarator(node) {
15546
+ if (node.id.type === "Identifier") {
15547
+ const name = node.id.name;
15548
+ globalExists[name] = node.init ? 3 : 2;
15377
15549
  }
15378
- return void 0;
15379
15550
  },
15380
- load(id) {
15381
- if (id.endsWith(LARK_TEMPLATE_SUFFIX)) {
15382
- const filePath = id.slice(0, -LARK_TEMPLATE_SUFFIX.length);
15383
- const raw = import_fs.default.readFileSync(filePath, "utf-8");
15384
- const globalVars = extractGlobalVars(raw);
15385
- return compileTemplate(raw, { debug, globalVars });
15551
+ FunctionDeclaration(node) {
15552
+ if (node.id) {
15553
+ globalExists[node.id.name] = 3;
15554
+ }
15555
+ fnRange.push(node);
15556
+ },
15557
+ FunctionExpression(node) {
15558
+ fnRange.push(node);
15559
+ },
15560
+ ArrowFunctionExpression(node) {
15561
+ fnRange.push(node);
15562
+ },
15563
+ CallExpression(node) {
15564
+ if (node.callee.type === "Identifier") {
15565
+ globalExists[node.callee.name] = 1;
15386
15566
  }
15387
- return void 0;
15388
15567
  }
15389
- };
15390
- }
15391
- var vite_default = larkMvcPlugin;
15568
+ });
15569
+ const functionParams = /* @__PURE__ */ Object.create(null);
15570
+ for (const fnNode of fnRange) {
15571
+ const params = "params" in fnNode ? fnNode.params : [];
15572
+ for (const p of params) {
15573
+ if (p.type === "Identifier") {
15574
+ functionParams[p.name] = 1;
15575
+ } else if (p.type === "AssignmentPattern" && p.left.type === "Identifier") {
15576
+ functionParams[p.left.name] = 1;
15577
+ } else if (p.type === "RestElement" && p.argument.type === "Identifier") {
15578
+ functionParams[p.argument.name] = 1;
15579
+ }
15580
+ }
15581
+ }
15582
+ walkAst(ast, {
15583
+ Identifier(node) {
15584
+ const name = node.name;
15585
+ if (globalExists[name]) return;
15586
+ if (functionParams[name]) return;
15587
+ globalVars[name] = 1;
15588
+ },
15589
+ AssignmentExpression(node) {
15590
+ if (node.left.type === "Identifier") {
15591
+ const name = node.left.name;
15592
+ if (!globalExists[name] || globalExists[name] === 1) {
15593
+ globalExists[name] = (globalExists[name] || 0) + 1;
15594
+ }
15595
+ }
15596
+ }
15597
+ });
15598
+ return Object.keys(globalVars);
15599
+ }
15600
+ function fallbackExtractVariables2(source) {
15601
+ const vars = /* @__PURE__ */ new Set();
15602
+ const outputRegExp = /\{\{[:=!@]\s*([a-zA-Z_$][\w$]*)[^}]*\}\}/g;
15603
+ let m;
15604
+ while ((m = outputRegExp.exec(source)) !== null) {
15605
+ vars.add(m[1]);
15606
+ }
15607
+ const eachRegExp = /\{\{forOf\s+([a-zA-Z_$][\w$]*)\s+as/g;
15608
+ while ((m = eachRegExp.exec(source)) !== null) {
15609
+ vars.add(m[1]);
15610
+ }
15611
+ const ifRegExp = /\{\{(?:else\s+)?if\s+([a-zA-Z_$][\w$]*)[^}]*\}\}/g;
15612
+ while ((m = ifRegExp.exec(source)) !== null) {
15613
+ vars.add(m[1]);
15614
+ }
15615
+ return Array.from(vars).filter((v) => !BUILTIN_GLOBALS2.has(v));
15616
+ }
15617
+ function walkAst(ast, visitors) {
15618
+ function visit(node) {
15619
+ const type = node.type;
15620
+ if (visitors[type]) {
15621
+ visitors[type](node);
15622
+ }
15623
+ for (const key of Object.keys(node)) {
15624
+ if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "range")
15625
+ continue;
15626
+ if (type === "MemberExpression" && key === "property") {
15627
+ const me = node;
15628
+ if (!me.computed) continue;
15629
+ }
15630
+ if (type === "ObjectProperty" && key === "key") {
15631
+ const op = node;
15632
+ if (!op.computed) continue;
15633
+ }
15634
+ if (type === "ObjectMethod" && key === "key") {
15635
+ const om = node;
15636
+ if (!om.computed) continue;
15637
+ }
15638
+ const child = Reflect.get(node, key);
15639
+ if (Array.isArray(child)) {
15640
+ for (const item of child) {
15641
+ if (isAstNode(item)) visit(item);
15642
+ }
15643
+ } else if (isAstNode(child)) {
15644
+ visit(child);
15645
+ }
15646
+ }
15647
+ }
15648
+ visit(ast);
15649
+ }
15650
+ function isAstNode(v) {
15651
+ return !!v && typeof v === "object" && typeof v.type === "string";
15652
+ }
15653
+ var BUILTIN_GLOBALS2 = /* @__PURE__ */ new Set([
15654
+ // ─── Template runtime helpers (injected by compileToFunction) ───────
15655
+ //
15656
+ // These variables appear in the generated template function signature
15657
+ // or body. They must be excluded from extractGlobalVars() so that
15658
+ // they are not mistaken for user data variables and destructured from $data.
15659
+ // SPLITTER character constant (same as \x1e), used as namespace separator
15660
+ // for refData keys, event attribute encoding, and internal data structures.
15661
+ // Declared as: let $splitter='\x1e'
15662
+ "$splitter",
15663
+ // Data — the data object passed from Updater to the template function.
15664
+ // User variables are destructured from $data at the top of the function:
15665
+ // let {name, age} = $data;
15666
+ // This is the first parameter of the generated arrow function.
15667
+ "$data",
15668
+ // Null-safe toString: v => '' + (v == null ? '' : v)
15669
+ // Converts null/undefined to empty string, otherwise calls toString().
15670
+ // Wraps every {{!raw}} output to prevent "null" / "undefined" rendering.
15671
+ "$strSafe",
15672
+ // HTML entity encoder: v => $strSafe(v).replace(/[&<>"'`]/g, entityMap)
15673
+ // Encodes &, <, >, ", ', ` to HTML entities (&amp; &lt; etc.)
15674
+ // Applied to all {{=escaped}} and {{:binding}} outputs.
15675
+ "$encHtml",
15676
+ // HTML entity map — internal object used by $encHtml:
15677
+ // {'&':'amp','<':'gt','>':'gt','"':'#34','\'':'#39','`':'#96'}
15678
+ // Not a standalone function; referenced inside $encHtml's closure.
15679
+ "$entMap",
15680
+ // HTML entity RegExp — internal regexp used by $encHtml:
15681
+ // /[&<>"'`]/g
15682
+ "$entReg",
15683
+ // HTML entity replacer function — internal helper used by $encHtml:
15684
+ // m => '&' + $entMap[m] + ';'
15685
+ // Maps matched character to its entity string.
15686
+ "$entFn",
15687
+ // Output buffer — the string accumulator for rendered HTML.
15688
+ // All template output is appended via $out += '...'.
15689
+ // Declared as: let $out = ''
15690
+ "$out",
15691
+ // Reference lookup: (refData, value) => key
15692
+ // Finds or allocates a SPLITTER-prefixed key in refData for a given
15693
+ // object reference. Used by {{@ref}} operator for passing object
15694
+ // references to child views via v-lark attributes.
15695
+ "$refFn",
15696
+ // URI encoder: v => encodeURIComponent($strSafe(v)).replace(/[!')(*]/g, extraMap)
15697
+ // Extends encodeURIComponent with encoding of ! ' ( ) *.
15698
+ // Applied to values in @event URL parameters and {{!uri}} contexts.
15699
+ "$encUri",
15700
+ // URI encode map — internal object used by $encUri:
15701
+ // {'!':'%21','\'':'%27','(':'%28',')':'%29','*':'%2A'}
15702
+ "$uriMap",
15703
+ // URI encode replacer — internal helper used by $encUri:
15704
+ // m => $uriMap[m]
15705
+ "$uriFn",
15706
+ // URI encode regexp — internal regexp used by $encUri:
15707
+ // /[!')(*]/g
15708
+ "$uriReg",
15709
+ // Quote encoder: v => $strSafe(v).replace(/['"\\]/g, '\\$&')
15710
+ // Escapes quotes and backslashes for safe embedding in HTML attribute
15711
+ // values (e.g. data-json='...').
15712
+ "$encQuote",
15713
+ // Quote encode regexp — internal regexp used by $encQuote:
15714
+ // /['"\\]/g
15715
+ "$qReg",
15716
+ // View ID — the unique identifier of the owning View instance.
15717
+ // Injected into @event attribute values at render time so that
15718
+ // EventDelegator can dispatch events to the correct View handler.
15719
+ // The \x1f placeholder in compiled output is replaced with '+$viewId+'.
15720
+ "$viewId",
15721
+ // Debug: current expression text — stores the template expression being
15722
+ // evaluated, for error reporting. Only present in debug mode.
15723
+ // e.g. $dbgExpr='<%=user.name%>'
15724
+ "$dbgExpr",
15725
+ // Debug: original art syntax — stores the {{}} template syntax before
15726
+ // conversion, for error reporting. Only present in debug mode.
15727
+ // e.g. $dbgArt='{{=user.name}}'
15728
+ "$dbgArt",
15729
+ // Debug: source line number — tracks the current line in the template
15730
+ // source, for error reporting. Only present in debug mode.
15731
+ "$dbgLine",
15732
+ // RefData alias — fallback reference lookup table.
15733
+ // Defaults to $data when no explicit $refAlt is provided.
15734
+ // Ensures $refFn() does not crash when @ operator is used without refData.
15735
+ "$refAlt",
15736
+ // Temporary variable — used by the compiler for intermediate
15737
+ // expression results in generated code (e.g. loop variables,
15738
+ // conditional branches). Declared as: let $tmp
15739
+ "$tmp",
15740
+ // JS literals
15741
+ "undefined",
15742
+ "null",
15743
+ "true",
15744
+ "false",
15745
+ "NaN",
15746
+ "Infinity",
15747
+ // JS built-in globals
15748
+ "window",
15749
+ "self",
15750
+ "globalThis",
15751
+ "document",
15752
+ "console",
15753
+ "JSON",
15754
+ "Math",
15755
+ "Intl",
15756
+ "Promise",
15757
+ "Symbol",
15758
+ "Number",
15759
+ "String",
15760
+ "Boolean",
15761
+ "Array",
15762
+ "Object",
15763
+ "Date",
15764
+ "RegExp",
15765
+ "Error",
15766
+ "TypeError",
15767
+ "RangeError",
15768
+ "SyntaxError",
15769
+ "Map",
15770
+ "Set",
15771
+ "WeakMap",
15772
+ "WeakSet",
15773
+ "Proxy",
15774
+ "Reflect",
15775
+ "ArrayBuffer",
15776
+ "DataView",
15777
+ "Float32Array",
15778
+ "Float64Array",
15779
+ "Int8Array",
15780
+ "Int16Array",
15781
+ "Int32Array",
15782
+ "Uint8Array",
15783
+ "Uint16Array",
15784
+ "Uint32Array",
15785
+ "Uint8ClampedArray",
15786
+ // Functions
15787
+ "parseInt",
15788
+ "parseFloat",
15789
+ "isNaN",
15790
+ "isFinite",
15791
+ "encodeURIComponent",
15792
+ "decodeURIComponent",
15793
+ "encodeURI",
15794
+ "decodeURI",
15795
+ // Babel helpers
15796
+ "arguments",
15797
+ "this",
15798
+ "require",
15799
+ // Lark framework
15800
+ "Lark"
15801
+ ]);
15802
+
15803
+ // src/compiler/compile-template.ts
15804
+ function compileToFunction(source, debug, file) {
15805
+ const matcher = /<%([@=!:])?([\s\S]*?)%>|$/g;
15806
+ let index = 0;
15807
+ let funcSource = `$out+='`;
15808
+ let hasAtRule = false;
15809
+ const escapeSlashRegExp = /\\|'/g;
15810
+ const escapeBreakReturnRegExp = /\r|\n/g;
15811
+ source.replace(matcher, (match, operate, content, offset) => {
15812
+ funcSource += source.substring(index, offset).replace(escapeSlashRegExp, "\\$&").replace(escapeBreakReturnRegExp, "\\n");
15813
+ index = offset + match.length;
15814
+ if (debug) {
15815
+ let expr = source.substring(
15816
+ index - match.length + 2 + (operate ? 1 : 0),
15817
+ index - 2
15818
+ );
15819
+ const x11 = String.fromCharCode(17);
15820
+ const artRegExp = new RegExp(`^'(\\d+)${x11}([^${x11}]+)${x11}'$`);
15821
+ const artM = expr.match(artRegExp);
15822
+ let art = "";
15823
+ let line = -1;
15824
+ if (artM) {
15825
+ expr = expr.replace(artRegExp, "");
15826
+ art = artM[2];
15827
+ line = parseInt(artM[1], 10);
15828
+ } else {
15829
+ expr = expr.replace(escapeSlashRegExp, "\\$&").replace(escapeBreakReturnRegExp, "\\n");
15830
+ }
15831
+ if (operate === "@") {
15832
+ hasAtRule = true;
15833
+ funcSource += `'+($dbgExpr='<%${operate + expr}%>',$refFn($refAlt,${content}))+'`;
15834
+ } else if (operate === "=" || operate === ":") {
15835
+ funcSource += `'+($dbgExpr='<%${operate + expr}%>',$encHtml(${content}))+'`;
15836
+ } else if (operate === "!") {
15837
+ if (!content.startsWith("$encUri(") || !content.endsWith(")")) {
15838
+ content = `$strSafe(${content})`;
15839
+ }
15840
+ funcSource += `'+($dbgExpr='<%${operate + expr}%>',${content})+'`;
15841
+ } else if (content) {
15842
+ if (line > -1) {
15843
+ funcSource += `';$dbgLine=${line};$dbgArt='${art}';`;
15844
+ content = "";
15845
+ } else {
15846
+ funcSource += `';`;
15847
+ }
15848
+ if (funcSource.endsWith(`+'';`)) {
15849
+ funcSource = funcSource.substring(0, funcSource.length - 4) + ";";
15850
+ }
15851
+ if (expr) {
15852
+ funcSource += `$dbgExpr='<%${expr}%>';`;
15853
+ }
15854
+ funcSource += content + `;$out+='`;
15855
+ }
15856
+ } else {
15857
+ if (operate === "@") {
15858
+ hasAtRule = true;
15859
+ funcSource += `'+$refFn($refAlt,${content})+'`;
15860
+ } else if (operate === "=" || operate === ":") {
15861
+ funcSource += `'+$encHtml(${content})+'`;
15862
+ } else if (operate === "!") {
15863
+ if (!content.startsWith("$encUri(") || !content.endsWith(")")) {
15864
+ content = `$strSafe(${content})`;
15865
+ }
15866
+ funcSource += `'+${content}+'`;
15867
+ } else if (content) {
15868
+ funcSource += `';`;
15869
+ if (funcSource.endsWith(`+'';`)) {
15870
+ funcSource = funcSource.substring(0, funcSource.length - 4) + ";";
15871
+ }
15872
+ funcSource += `${content};$out+='`;
15873
+ }
15874
+ }
15875
+ return match;
15876
+ });
15877
+ funcSource += `';`;
15878
+ funcSource = funcSource.replace(/\$out\+='';/g, "");
15879
+ funcSource = funcSource.replace(/\$out\+=''\+/g, "$out+=");
15880
+ if (debug) {
15881
+ const filePart = file ? `\\r\\n\\tat file:${file}` : "";
15882
+ funcSource = `let $dbgExpr,$dbgArt,$dbgLine;try{${funcSource}}catch(ex){let msg='render view error:'+(ex.message||ex);if($dbgArt)msg+='\\r\\n\\tsrc art:{{'+$dbgArt+'}}\\r\\n\\tat line:'+$dbgLine;msg+='\\r\\n\\t'+($dbgArt?'translate to:':'expr:');msg+=$dbgExpr+'${filePart}';throw msg;}`;
15883
+ }
15884
+ const viewIdRegExp = new RegExp(String.fromCharCode(31), "g");
15885
+ funcSource = funcSource.replace(viewIdRegExp, `'+$viewId+'`);
15886
+ void hasAtRule;
15887
+ const refFallback = "if(!$refAlt)$refAlt=$data;";
15888
+ const fullSource = `${refFallback}let $splitter='\\x1e',$tmp,$out=''{{VARS}};${funcSource}return $out`;
15889
+ return `($data,$viewId,$refAlt,$encHtml,$strSafe,$encUri,$refFn,$encQuote)=>{${fullSource}}`;
15890
+ }
15891
+ async function compileTemplate(source, options = {}) {
15892
+ const { debug = false, file, virtualDom = false, useSwc = false } = options;
15893
+ const globalVars = options.globalVars ?? await (useSwc ? extractGlobalVars(source) : extractGlobalVars2(source));
15894
+ const { protectedSource, comments } = protectComments(source);
15895
+ const converted = convertArtSyntax(protectedSource, debug);
15896
+ const viewEventProcessed = processViewEvents(converted);
15897
+ const finalSource = restoreComments(viewEventProcessed, comments);
15898
+ const varDeclarations = globalVars.map((key) => `,${key}=$data.${key}`).join("");
15899
+ if (virtualDom) {
15900
+ const funcBody2 = compileToVDomFunction(finalSource, debug, file);
15901
+ const funcWithVars2 = funcBody2.replace("{{VARS}}", () => varDeclarations);
15902
+ return `import { vdomCreate as __larkC } from "@lark.js/mvc";
15903
+ import { strSafe as __larkStrSafe, encUri as __larkEncUri, encQuote as __larkEncQuote, refFn as __larkRefFn } from "@lark.js/mvc/runtime";
15904
+ export default function(data, viewId, refData) {
15905
+ let $data = data || {},
15906
+ $viewId = viewId || '',
15907
+ $c = __larkC,
15908
+ $n = __larkStrSafe;
15909
+ return (${funcWithVars2})($data, $viewId, refData,
15910
+ $n, __larkRefFn, __larkEncUri, __larkEncQuote
15911
+ );
15912
+ }`;
15913
+ }
15914
+ const funcBody = compileToFunction(finalSource, debug, file);
15915
+ const funcWithVars = funcBody.replace("{{VARS}}", () => varDeclarations);
15916
+ return `import { encHtml as __larkEncHtml, strSafe as __larkStrSafe, encUri as __larkEncUri, encQuote as __larkEncQuote, refFn as __larkRefFn } from "@lark.js/mvc/runtime";
15917
+ export default function(data, viewId, refData) {
15918
+ let $data = data || {},
15919
+ $viewId = viewId || '';
15920
+ return (${funcWithVars})($data, $viewId, refData,
15921
+ __larkEncHtml, __larkStrSafe, __larkEncUri, __larkRefFn, __larkEncQuote
15922
+ );
15923
+ }`;
15924
+ }
15925
+
15926
+ // src/vite.ts
15927
+ var LARK_TEMPLATE_SUFFIX = "?lark-template";
15928
+ function larkMvcPlugin(options = {}) {
15929
+ const { debug = false, virtualDom = false, useSwc = false } = options;
15930
+ let root = __dirname;
15931
+ return {
15932
+ name: "lark-template",
15933
+ enforce: "pre",
15934
+ configResolved(config) {
15935
+ root = config.root;
15936
+ },
15937
+ resolveId(source, importer) {
15938
+ const sourcePath = source.split("?")[0];
15939
+ if (sourcePath.endsWith(".html") && importer) {
15940
+ const importerPath = importer.split("?")[0];
15941
+ let resolved = import_path.default.resolve(import_path.default.dirname(importerPath), sourcePath);
15942
+ if (!import_fs.default.existsSync(resolved)) {
15943
+ const rootResolved = import_path.default.join(root, resolved);
15944
+ if (import_fs.default.existsSync(rootResolved)) {
15945
+ resolved = rootResolved;
15946
+ }
15947
+ }
15948
+ return resolved + LARK_TEMPLATE_SUFFIX;
15949
+ }
15950
+ return void 0;
15951
+ },
15952
+ async load(id) {
15953
+ const qIdx = id.indexOf("?");
15954
+ const query = qIdx >= 0 ? id.slice(qIdx + 1) : "";
15955
+ if (query.split("&").includes("lark-template")) {
15956
+ let filePath = qIdx >= 0 ? id.slice(0, qIdx) : id;
15957
+ if (!import_fs.default.existsSync(filePath)) {
15958
+ const rootResolved = import_path.default.join(root, filePath);
15959
+ if (import_fs.default.existsSync(rootResolved)) {
15960
+ filePath = rootResolved;
15961
+ }
15962
+ }
15963
+ if (!import_fs.default.existsSync(filePath)) return void 0;
15964
+ const raw = import_fs.default.readFileSync(filePath, "utf-8");
15965
+ const globalVars = await extractGlobalVars2(raw);
15966
+ return compileTemplate(raw, { debug, globalVars, virtualDom, useSwc });
15967
+ }
15968
+ return void 0;
15969
+ }
15970
+ };
15971
+ }
15972
+ var vite_default = larkMvcPlugin;
15973
+ function larkMvcPluginLegacy(options = {}) {
15974
+ const { debug = false, virtualDom = false, useSwc = false } = options;
15975
+ return {
15976
+ name: "lark-template",
15977
+ enforce: "pre",
15978
+ resolveId(source, importer) {
15979
+ if (source.endsWith(".html") && importer) {
15980
+ return import_path.default.resolve(import_path.default.dirname(importer), source) + LARK_TEMPLATE_SUFFIX;
15981
+ }
15982
+ return void 0;
15983
+ },
15984
+ async load(id) {
15985
+ if (id.endsWith(LARK_TEMPLATE_SUFFIX)) {
15986
+ const filePath = id.slice(0, -LARK_TEMPLATE_SUFFIX.length);
15987
+ const raw = import_fs.default.readFileSync(filePath, "utf-8");
15988
+ const globalVars = await extractGlobalVars2(raw);
15989
+ return compileTemplate(raw, { debug, globalVars, virtualDom, useSwc });
15990
+ }
15991
+ return void 0;
15992
+ }
15993
+ };
15994
+ }
15392
15995
  // Annotate the CommonJS export names for ESM import in node:
15393
15996
  0 && (module.exports = {
15394
- larkMvcPlugin
15997
+ larkMvcPlugin,
15998
+ larkMvcPluginLegacy
15395
15999
  });