@simahfud/pine-to-kline 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1996 @@
1
+ var B = Object.defineProperty;
2
+ var U = (i, t, e) => t in i ? B(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
3
+ var p = (i, t, e) => U(i, typeof t != "symbol" ? t + "" : t, e);
4
+ /**
5
+ * pine-to-kline — Token
6
+ * @license Apache-2.0
7
+ */
8
+ class N {
9
+ constructor(t, e, s, r) {
10
+ this.type = t, this.value = e, this.line = s, this.column = r;
11
+ }
12
+ is(t) {
13
+ return this.type === t;
14
+ }
15
+ isAny(...t) {
16
+ return t.includes(this.type);
17
+ }
18
+ toString() {
19
+ return `Token(${this.type}, ${JSON.stringify(this.value)}, ${this.line}:${this.column})`;
20
+ }
21
+ }
22
+ /**
23
+ * pine-to-kline — Token Types
24
+ * All PineScript v5/v6 token categories
25
+ * @license Apache-2.0
26
+ */
27
+ var a = /* @__PURE__ */ ((i) => (i.NUMBER = "NUMBER", i.STRING = "STRING", i.COLOR_LITERAL = "COLOR_LITERAL", i.IDENTIFIER = "IDENTIFIER", i.IF = "IF", i.ELSE = "ELSE", i.FOR = "FOR", i.TO = "TO", i.BY = "BY", i.IN = "IN", i.WHILE = "WHILE", i.SWITCH = "SWITCH", i.VAR = "VAR", i.VARIP = "VARIP", i.TRUE = "TRUE", i.FALSE = "FALSE", i.NA = "NA", i.AND = "AND", i.OR = "OR", i.NOT = "NOT", i.IMPORT = "IMPORT", i.EXPORT = "EXPORT", i.TYPE = "TYPE", i.METHOD = "METHOD", i.BREAK = "BREAK", i.CONTINUE = "CONTINUE", i.RETURN = "RETURN", i.INDICATOR = "INDICATOR", i.STRATEGY = "STRATEGY", i.LIBRARY = "LIBRARY", i.PLUS = "PLUS", i.MINUS = "MINUS", i.STAR = "STAR", i.SLASH = "SLASH", i.PERCENT = "PERCENT", i.POWER = "POWER", i.EQ = "EQ", i.NEQ = "NEQ", i.LT = "LT", i.GT = "GT", i.LTE = "LTE", i.GTE = "GTE", i.ASSIGN = "ASSIGN", i.REASSIGN = "REASSIGN", i.PLUS_ASSIGN = "PLUS_ASSIGN", i.MINUS_ASSIGN = "MINUS_ASSIGN", i.STAR_ASSIGN = "STAR_ASSIGN", i.SLASH_ASSIGN = "SLASH_ASSIGN", i.PERCENT_ASSIGN = "PERCENT_ASSIGN", i.LPAREN = "LPAREN", i.RPAREN = "RPAREN", i.LBRACKET = "LBRACKET", i.RBRACKET = "RBRACKET", i.COMMA = "COMMA", i.DOT = "DOT", i.COLON = "COLON", i.QUESTION = "QUESTION", i.ARROW = "ARROW", i.NEWLINE = "NEWLINE", i.INDENT = "INDENT", i.DEDENT = "DEDENT", i.EOF = "EOF", i.COMMENT = "COMMENT", i.COMPILER_ANNOTATION = "COMPILER_ANNOTATION", i))(a || {});
28
+ const G = {
29
+ if: "IF",
30
+ else: "ELSE",
31
+ for: "FOR",
32
+ to: "TO",
33
+ by: "BY",
34
+ in: "IN",
35
+ while: "WHILE",
36
+ switch: "SWITCH",
37
+ var: "VAR",
38
+ varip: "VARIP",
39
+ true: "TRUE",
40
+ false: "FALSE",
41
+ na: "NA",
42
+ and: "AND",
43
+ or: "OR",
44
+ not: "NOT",
45
+ import: "IMPORT",
46
+ export: "EXPORT",
47
+ type: "TYPE",
48
+ method: "METHOD",
49
+ break: "BREAK",
50
+ continue: "CONTINUE",
51
+ return: "RETURN"
52
+ /* RETURN */
53
+ // Pine type keywords are treated as identifiers, not reserved
54
+ // (int, float, bool, string, color, etc.)
55
+ };
56
+ /**
57
+ * pine-to-kline — Error Classes
58
+ * @license Apache-2.0
59
+ */
60
+ class x extends Error {
61
+ constructor(t, e, s, r) {
62
+ super(t), this.line = e, this.column = s, this.source = r, this.name = "PineError";
63
+ }
64
+ toString() {
65
+ const t = this.line != null ? ` at line ${this.line}` : "", e = this.column != null ? `:${this.column}` : "";
66
+ return `${this.name}: ${this.message}${t}${e}`;
67
+ }
68
+ }
69
+ class S extends x {
70
+ constructor(t, e, s) {
71
+ super(t, e, s), this.name = "LexerError";
72
+ }
73
+ }
74
+ class C extends x {
75
+ constructor(t, e, s) {
76
+ super(t, e, s), this.name = "ParseError";
77
+ }
78
+ }
79
+ class Ht extends x {
80
+ constructor(t, e, s) {
81
+ super(t, e, s), this.name = "RuntimeError";
82
+ }
83
+ }
84
+ class jt extends x {
85
+ constructor(t) {
86
+ super(t), this.name = "AdapterError";
87
+ }
88
+ }
89
+ /**
90
+ * pine-to-kline — Lexer (Tokenizer)
91
+ * Converts PineScript source code into a stream of tokens.
92
+ * Handles indentation-significant syntax (INDENT/DEDENT).
93
+ * @license Apache-2.0
94
+ */
95
+ class O {
96
+ constructor(t) {
97
+ p(this, "source");
98
+ p(this, "tokens", []);
99
+ p(this, "pos", 0);
100
+ p(this, "line", 1);
101
+ p(this, "column", 1);
102
+ p(this, "indentStack", [0]);
103
+ p(this, "atLineStart", !0);
104
+ this.source = t.replace(/\r\n/g, `
105
+ `).replace(/\r/g, `
106
+ `);
107
+ }
108
+ tokenize() {
109
+ for (this.tokens = [], this.pos = 0, this.line = 1, this.column = 1, this.indentStack = [0], this.atLineStart = !0; this.pos < this.source.length; ) {
110
+ this.atLineStart && (this.handleIndentation(), this.atLineStart = !1);
111
+ const t = this.current();
112
+ if (t === void 0) break;
113
+ if (t === " " || t === " ") {
114
+ this.advance();
115
+ continue;
116
+ }
117
+ if (t === `
118
+ `) {
119
+ this.emitNewline();
120
+ continue;
121
+ }
122
+ if (t === "/" && this.peek() === "/") {
123
+ this.readComment();
124
+ continue;
125
+ }
126
+ if (this.isDigit(t) || t === "." && this.peek() !== void 0 && this.isDigit(this.peek())) {
127
+ this.readNumber();
128
+ continue;
129
+ }
130
+ if (t === '"' || t === "'") {
131
+ this.readString(t);
132
+ continue;
133
+ }
134
+ if (t === "#" && this.isHexDigit(this.peek())) {
135
+ this.readColor();
136
+ continue;
137
+ }
138
+ if (this.isAlpha(t) || t === "_") {
139
+ this.readIdentifier();
140
+ continue;
141
+ }
142
+ if (!this.readOperator())
143
+ throw new S(`Unexpected character: '${t}'`, this.line, this.column);
144
+ }
145
+ for (; this.indentStack.length > 1; )
146
+ this.indentStack.pop(), this.tokens.push(new N(a.DEDENT, "", this.line, this.column));
147
+ return this.tokens.push(new N(a.EOF, "", this.line, this.column)), this.filterTokens(this.tokens);
148
+ }
149
+ // ─── Indentation ────────────────────────────────────────────
150
+ handleIndentation() {
151
+ let t = 0;
152
+ for (; this.pos < this.source.length; ) {
153
+ const s = this.source[this.pos];
154
+ if (s === " ")
155
+ t++, this.pos++, this.column++;
156
+ else if (s === " ")
157
+ t += 4, this.pos++, this.column++;
158
+ else
159
+ break;
160
+ }
161
+ if (this.pos < this.source.length && this.source[this.pos] === `
162
+ ` || this.pos < this.source.length && this.source[this.pos] === "/" && this.pos + 1 < this.source.length && this.source[this.pos + 1] === "/")
163
+ return;
164
+ const e = this.indentStack[this.indentStack.length - 1];
165
+ if (t > e)
166
+ this.indentStack.push(t), this.tokens.push(new N(a.INDENT, "", this.line, 1));
167
+ else if (t < e)
168
+ for (; this.indentStack.length > 1 && this.indentStack[this.indentStack.length - 1] > t; )
169
+ this.indentStack.pop(), this.tokens.push(new N(a.DEDENT, "", this.line, 1));
170
+ }
171
+ // ─── Newlines ───────────────────────────────────────────────
172
+ emitNewline() {
173
+ const t = this.tokens[this.tokens.length - 1];
174
+ (!t || t.type !== a.NEWLINE && t.type !== a.INDENT) && this.tokens.push(new N(a.NEWLINE, `
175
+ `, this.line, this.column)), this.advance(), this.line++, this.column = 1, this.atLineStart = !0;
176
+ }
177
+ // ─── Comments ───────────────────────────────────────────────
178
+ readComment() {
179
+ const t = this.column;
180
+ let e = "";
181
+ if (this.advance(), this.advance(), this.current() === "@") {
182
+ for (e = "//@", this.advance(); this.pos < this.source.length && this.current() !== `
183
+ `; )
184
+ e += this.current(), this.advance();
185
+ this.tokens.push(new N(a.COMPILER_ANNOTATION, e.trim(), this.line, t));
186
+ return;
187
+ }
188
+ for (; this.pos < this.source.length && this.current() !== `
189
+ `; )
190
+ e += this.current(), this.advance();
191
+ }
192
+ // ─── Numbers ────────────────────────────────────────────────
193
+ readNumber() {
194
+ const t = this.column;
195
+ let e = "";
196
+ for (; this.pos < this.source.length && (this.isDigit(this.current()) || this.current() === "."); )
197
+ e += this.current(), this.advance();
198
+ if (this.current() === "e" || this.current() === "E")
199
+ for (e += this.current(), this.advance(), (this.current() === "+" || this.current() === "-") && (e += this.current(), this.advance()); this.pos < this.source.length && this.isDigit(this.current()); )
200
+ e += this.current(), this.advance();
201
+ this.tokens.push(new N(a.NUMBER, e, this.line, t));
202
+ }
203
+ // ─── Strings ────────────────────────────────────────────────
204
+ readString(t) {
205
+ const e = this.column, s = this.line;
206
+ let r = "";
207
+ for (this.advance(); this.pos < this.source.length; ) {
208
+ const n = this.current();
209
+ if (n === "\\") {
210
+ this.advance();
211
+ const l = this.current();
212
+ l === "n" ? r += `
213
+ ` : l === "t" ? r += " " : l === "\\" ? r += "\\" : l === t ? r += t : r += "\\" + (l ?? ""), this.advance();
214
+ continue;
215
+ }
216
+ if (n === t) {
217
+ this.advance(), this.tokens.push(new N(a.STRING, r, s, e));
218
+ return;
219
+ }
220
+ if (n === `
221
+ `)
222
+ throw new S("Unterminated string literal", s, e);
223
+ r += n, this.advance();
224
+ }
225
+ throw new S("Unterminated string literal", s, e);
226
+ }
227
+ // ─── Color Literals ─────────────────────────────────────────
228
+ readColor() {
229
+ const t = this.column;
230
+ let e = "#";
231
+ for (this.advance(); this.pos < this.source.length && this.isHexDigit(this.current()); )
232
+ e += this.current(), this.advance();
233
+ if (e.length !== 7 && e.length !== 9)
234
+ throw new S(`Invalid color literal: ${e}`, this.line, t);
235
+ this.tokens.push(new N(a.COLOR_LITERAL, e, this.line, t));
236
+ }
237
+ // ─── Identifiers & Keywords ─────────────────────────────────
238
+ readIdentifier() {
239
+ const t = this.column;
240
+ let e = "";
241
+ for (; this.pos < this.source.length && (this.isAlphaNumeric(this.current()) || this.current() === "_"); )
242
+ e += this.current(), this.advance();
243
+ const s = G[e];
244
+ s ? this.tokens.push(new N(s, e, this.line, t)) : this.tokens.push(new N(a.IDENTIFIER, e, this.line, t));
245
+ }
246
+ // ─── Operators & Delimiters ─────────────────────────────────
247
+ readOperator() {
248
+ const t = this.current(), e = this.peek(), s = this.column;
249
+ if (e !== void 0) {
250
+ const n = t + e, l = {
251
+ "==": a.EQ,
252
+ "!=": a.NEQ,
253
+ "<=": a.LTE,
254
+ ">=": a.GTE,
255
+ ":=": a.REASSIGN,
256
+ "+=": a.PLUS_ASSIGN,
257
+ "-=": a.MINUS_ASSIGN,
258
+ "*=": a.STAR_ASSIGN,
259
+ "/=": a.SLASH_ASSIGN,
260
+ "%=": a.PERCENT_ASSIGN,
261
+ "=>": a.ARROW,
262
+ "**": a.POWER
263
+ };
264
+ if (l[n])
265
+ return this.advance(), this.advance(), this.tokens.push(new N(l[n], n, this.line, s)), !0;
266
+ }
267
+ const r = {
268
+ "+": a.PLUS,
269
+ "-": a.MINUS,
270
+ "*": a.STAR,
271
+ "/": a.SLASH,
272
+ "%": a.PERCENT,
273
+ "<": a.LT,
274
+ ">": a.GT,
275
+ "=": a.ASSIGN,
276
+ "(": a.LPAREN,
277
+ ")": a.RPAREN,
278
+ "[": a.LBRACKET,
279
+ "]": a.RBRACKET,
280
+ ",": a.COMMA,
281
+ ".": a.DOT,
282
+ ":": a.COLON,
283
+ "?": a.QUESTION
284
+ };
285
+ return r[t] ? (this.advance(), this.tokens.push(new N(r[t], t, this.line, s)), !0) : !1;
286
+ }
287
+ // ─── Post-Processing ───────────────────────────────────────
288
+ /**
289
+ * Filter out meaningless tokens and handle line continuation.
290
+ * Pine uses implicit line continuation after certain tokens:
291
+ * binary operators, commas, opening brackets/parens.
292
+ */
293
+ filterTokens(t) {
294
+ const e = [], s = /* @__PURE__ */ new Set([
295
+ a.PLUS,
296
+ a.MINUS,
297
+ a.STAR,
298
+ a.SLASH,
299
+ a.PERCENT,
300
+ a.POWER,
301
+ a.EQ,
302
+ a.NEQ,
303
+ a.LT,
304
+ a.GT,
305
+ a.LTE,
306
+ a.GTE,
307
+ a.AND,
308
+ a.OR,
309
+ a.COMMA,
310
+ a.ASSIGN,
311
+ a.REASSIGN,
312
+ a.PLUS_ASSIGN,
313
+ a.MINUS_ASSIGN,
314
+ a.STAR_ASSIGN,
315
+ a.SLASH_ASSIGN,
316
+ a.PERCENT_ASSIGN,
317
+ a.QUESTION,
318
+ a.COLON,
319
+ a.ARROW,
320
+ a.LPAREN,
321
+ a.LBRACKET
322
+ ]);
323
+ let r = 0, n = 0;
324
+ for (let l = 0; l < t.length; l++) {
325
+ const h = t[l];
326
+ if (h.type === a.LPAREN && r++, h.type === a.RPAREN && r--, h.type === a.LBRACKET && n++, h.type === a.RBRACKET && n--, !(h.type === a.NEWLINE && (r > 0 || n > 0))) {
327
+ if (h.type === a.NEWLINE) {
328
+ const c = e[e.length - 1];
329
+ if (c && s.has(c.type))
330
+ continue;
331
+ }
332
+ (h.type === a.INDENT || h.type === a.DEDENT) && (r > 0 || n > 0) || e.push(h);
333
+ }
334
+ }
335
+ return e;
336
+ }
337
+ // ─── Helpers ────────────────────────────────────────────────
338
+ current() {
339
+ return this.source[this.pos];
340
+ }
341
+ peek(t = 1) {
342
+ return this.source[this.pos + t];
343
+ }
344
+ advance() {
345
+ this.pos++, this.column++;
346
+ }
347
+ isDigit(t) {
348
+ return t >= "0" && t <= "9";
349
+ }
350
+ isAlpha(t) {
351
+ return t >= "a" && t <= "z" || t >= "A" && t <= "Z" || t === "_";
352
+ }
353
+ isAlphaNumeric(t) {
354
+ return this.isAlpha(t) || this.isDigit(t);
355
+ }
356
+ isHexDigit(t) {
357
+ return t ? t >= "0" && t <= "9" || t >= "a" && t <= "f" || t >= "A" && t <= "F" : !1;
358
+ }
359
+ }
360
+ /**
361
+ * pine-to-kline — Parser
362
+ * Recursive descent parser: Token[] → AST (ProgramNode)
363
+ * @license Apache-2.0
364
+ */
365
+ const V = /* @__PURE__ */ new Set(["plot", "plotshape", "plotarrow", "plotbar", "plotcandle", "plotchar", "bgcolor", "fill"]), P = /* @__PURE__ */ new Set(["int", "float", "bool", "string", "color", "label", "line", "box", "table", "series", "simple"]);
366
+ class _ {
367
+ constructor(t) {
368
+ p(this, "tokens");
369
+ p(this, "pos", 0);
370
+ this.tokens = t;
371
+ }
372
+ parse() {
373
+ const t = [], e = [];
374
+ for (this.skipNewlines(); !this.isAtEnd() && (this.skipNewlines(), !this.isAtEnd()); ) {
375
+ if (this.check(a.COMPILER_ANNOTATION)) {
376
+ e.push({ type: "Annotation", value: this.advance().value, line: this.previous().line }), this.skipNewlines();
377
+ continue;
378
+ }
379
+ const s = this.parseStatement();
380
+ s && t.push(s), this.skipNewlines();
381
+ }
382
+ return { type: "Program", body: t, annotations: e };
383
+ }
384
+ // ─── Statement Parsing ──────────────────────────────────────
385
+ parseStatement() {
386
+ if (this.check(a.VAR) || this.check(a.VARIP))
387
+ return this.parseVarDecl();
388
+ if (this.check(a.IF)) return this.parseIf();
389
+ if (this.check(a.FOR)) return this.parseFor();
390
+ if (this.check(a.WHILE)) return this.parseWhile();
391
+ if (this.check(a.SWITCH)) return this.parseSwitch();
392
+ if (this.check(a.BREAK))
393
+ return this.advance(), { type: "Break", line: this.previous().line };
394
+ if (this.check(a.CONTINUE))
395
+ return this.advance(), { type: "Continue", line: this.previous().line };
396
+ if (this.check(a.RETURN)) return this.parseReturn();
397
+ if (this.check(a.IDENTIFIER))
398
+ return this.parseIdentifierStatement();
399
+ if (this.check(a.LBRACKET))
400
+ return this.parseTupleAssign();
401
+ const t = this.parseExpression();
402
+ return { type: "ExpressionStatement", expression: t, line: t.line };
403
+ }
404
+ parseIdentifierStatement() {
405
+ var s, r, n, l, h, c;
406
+ const t = this.peek();
407
+ if ((t.value === "indicator" || t.value === "strategy" || t.value === "library") && ((s = this.peekAt(1)) == null ? void 0 : s.type) === a.LPAREN)
408
+ return this.parseIndicator();
409
+ if (V.has(t.value) && ((r = this.peekAt(1)) == null ? void 0 : r.type) === a.LPAREN)
410
+ return this.parsePlotCall();
411
+ if (t.value === "hline" && ((n = this.peekAt(1)) == null ? void 0 : n.type) === a.LPAREN)
412
+ return this.parseHlineCall();
413
+ if (((l = this.peekAt(1)) == null ? void 0 : l.type) === a.LPAREN && this.isFunctionDef())
414
+ return this.parseFunctionDef();
415
+ if (P.has(t.value) && ((h = this.peekAt(1)) == null ? void 0 : h.type) === a.IDENTIFIER)
416
+ return this.parseTypedDecl();
417
+ if ((c = this.peekAt(1)) != null && c.isAny(a.ASSIGN, a.REASSIGN, a.PLUS_ASSIGN, a.MINUS_ASSIGN, a.STAR_ASSIGN, a.SLASH_ASSIGN, a.PERCENT_ASSIGN))
418
+ return this.parseAssignment();
419
+ const e = this.parseExpression();
420
+ return { type: "ExpressionStatement", expression: e, line: e.line };
421
+ }
422
+ // ─── Indicator / Strategy ───────────────────────────────────
423
+ parseIndicator() {
424
+ const t = this.advance();
425
+ this.expect(a.LPAREN);
426
+ const e = this.parseCallArgs();
427
+ return this.expect(a.RPAREN), {
428
+ type: "Indicator",
429
+ name: e.positional[0] ?? { type: "StringLiteral", value: "Untitled", line: t.line },
430
+ args: e.named,
431
+ line: t.line
432
+ };
433
+ }
434
+ // ─── Variable Declarations ─────────────────────────────────
435
+ parseVarDecl() {
436
+ const t = this.check(a.VAR), e = this.check(a.VARIP);
437
+ this.advance();
438
+ let s = null;
439
+ this.check(a.IDENTIFIER) && P.has(this.peek().value) && (s = this.advance().value);
440
+ const r = this.expect(a.IDENTIFIER).value;
441
+ this.expect(a.ASSIGN);
442
+ const n = this.parseExpression();
443
+ return { type: "VarDecl", persistent: t, persistentTick: e, name: r, typeAnnotation: s, value: n, line: n.line };
444
+ }
445
+ parseTypedDecl() {
446
+ const t = this.advance().value, e = this.expect(a.IDENTIFIER).value;
447
+ this.expect(a.ASSIGN);
448
+ const s = this.parseExpression();
449
+ return { type: "VarDecl", persistent: !1, persistentTick: !1, name: e, typeAnnotation: t, value: s, line: s.line };
450
+ }
451
+ parseAssignment() {
452
+ const t = this.advance().value, e = this.advance(), s = this.parseExpression();
453
+ return { type: "Assign", target: t, operator: e.value, value: s, line: e.line };
454
+ }
455
+ parseTupleAssign() {
456
+ this.expect(a.LBRACKET);
457
+ const t = [];
458
+ for (t.push(this.expect(a.IDENTIFIER).value); this.match(a.COMMA); )
459
+ t.push(this.expect(a.IDENTIFIER).value);
460
+ this.expect(a.RBRACKET), this.expect(a.ASSIGN);
461
+ const e = this.parseExpression();
462
+ return { type: "VarDecl", persistent: !1, persistentTick: !1, name: t, typeAnnotation: null, value: e, line: e.line };
463
+ }
464
+ // ─── Control Flow ──────────────────────────────────────────
465
+ parseIf() {
466
+ const t = this.advance().line, e = this.parseExpression();
467
+ this.skipNewlines();
468
+ const s = this.parseBlock(), r = [];
469
+ let n = null;
470
+ for (; this.check(a.ELSE); )
471
+ if (this.advance(), this.check(a.IF)) {
472
+ this.advance();
473
+ const l = this.parseExpression();
474
+ this.skipNewlines();
475
+ const h = this.parseBlock();
476
+ r.push({ condition: l, body: h });
477
+ } else {
478
+ this.skipNewlines(), n = this.parseBlock();
479
+ break;
480
+ }
481
+ return { type: "If", condition: e, body: s, elseIf: r, elseBody: n, line: t };
482
+ }
483
+ parseFor() {
484
+ const t = this.advance().line, e = this.expect(a.IDENTIFIER).value;
485
+ if (this.check(a.IN)) {
486
+ this.advance();
487
+ const h = this.parseExpression();
488
+ this.skipNewlines();
489
+ const c = this.parseBlock();
490
+ return { type: "ForIn", variable: e, iterable: h, body: c, line: t };
491
+ }
492
+ this.expect(a.ASSIGN);
493
+ const s = this.parseExpression();
494
+ this.expect(a.TO);
495
+ const r = this.parseExpression();
496
+ let n = null;
497
+ this.check(a.BY) && (this.advance(), n = this.parseExpression()), this.skipNewlines();
498
+ const l = this.parseBlock();
499
+ return { type: "For", variable: e, start: s, end: r, step: n, body: l, line: t };
500
+ }
501
+ parseWhile() {
502
+ const t = this.advance().line, e = this.parseExpression();
503
+ this.skipNewlines();
504
+ const s = this.parseBlock();
505
+ return { type: "While", condition: e, body: s, line: t };
506
+ }
507
+ parseSwitch() {
508
+ const t = this.advance().line;
509
+ let e = null;
510
+ !this.check(a.NEWLINE) && !this.check(a.INDENT) && (e = this.parseExpression()), this.skipNewlines();
511
+ const s = [];
512
+ let r = null;
513
+ if (this.match(a.INDENT)) {
514
+ for (; !this.check(a.DEDENT) && !this.isAtEnd() && (this.skipNewlines(), !this.check(a.DEDENT)); ) {
515
+ if (this.check(a.ARROW))
516
+ this.advance(), this.skipNewlines(), r = this.parseBlock();
517
+ else {
518
+ const n = this.parseExpression();
519
+ this.expect(a.ARROW), this.skipNewlines();
520
+ const l = this.parseBlockOrExpr();
521
+ s.push({ condition: n, body: l });
522
+ }
523
+ this.skipNewlines();
524
+ }
525
+ this.check(a.DEDENT) && this.advance();
526
+ }
527
+ return { type: "Switch", expression: e, cases: s, defaultBody: r, line: t };
528
+ }
529
+ parseReturn() {
530
+ const t = this.advance().line;
531
+ let e = null;
532
+ return !this.check(a.NEWLINE) && !this.check(a.DEDENT) && !this.isAtEnd() && (e = this.parseExpression()), { type: "Return", value: e, line: t };
533
+ }
534
+ // ─── Function Definition ───────────────────────────────────
535
+ isFunctionDef() {
536
+ var s;
537
+ let t = 0, e = this.pos + 1;
538
+ for (; e < this.tokens.length; ) {
539
+ if (this.tokens[e].type === a.LPAREN && t++, this.tokens[e].type === a.RPAREN && (t--, t === 0))
540
+ return ((s = this.tokens[e + 1]) == null ? void 0 : s.type) === a.ARROW;
541
+ if (this.tokens[e].type === a.NEWLINE || this.tokens[e].type === a.EOF) return !1;
542
+ e++;
543
+ }
544
+ return !1;
545
+ }
546
+ parseFunctionDef() {
547
+ const t = this.advance().value;
548
+ this.expect(a.LPAREN);
549
+ const e = [];
550
+ if (!this.check(a.RPAREN))
551
+ do {
552
+ const r = this.expect(a.IDENTIFIER).value;
553
+ let n = null;
554
+ this.match(a.ASSIGN) && (n = this.parseExpression()), e.push({ name: r, defaultValue: n });
555
+ } while (this.match(a.COMMA));
556
+ this.expect(a.RPAREN), this.expect(a.ARROW), this.skipNewlines();
557
+ const s = this.parseBlock();
558
+ return { type: "FunctionDef", name: t, params: e, body: s, line: this.previous().line };
559
+ }
560
+ // ─── Plot / Hline ──────────────────────────────────────────
561
+ parsePlotCall() {
562
+ const t = this.advance().value;
563
+ this.expect(a.LPAREN);
564
+ const { positional: e, named: s } = this.parseCallArgs();
565
+ return this.expect(a.RPAREN), { type: "PlotCall", function: t, args: e, kwargs: s, line: this.previous().line };
566
+ }
567
+ parseHlineCall() {
568
+ this.advance(), this.expect(a.LPAREN);
569
+ const { positional: t, named: e } = this.parseCallArgs();
570
+ return this.expect(a.RPAREN), { type: "HlineCall", price: t[0], args: t.slice(1), kwargs: e, line: this.previous().line };
571
+ }
572
+ // ─── Expressions (Precedence Climbing) ─────────────────────
573
+ parseExpression() {
574
+ return this.parseTernary();
575
+ }
576
+ parseTernary() {
577
+ let t = this.parseOr();
578
+ if (this.match(a.QUESTION)) {
579
+ const e = this.parseExpression();
580
+ this.expect(a.COLON);
581
+ const s = this.parseExpression();
582
+ t = { type: "TernaryExpr", condition: t, consequent: e, alternate: s, line: t.line };
583
+ }
584
+ return t;
585
+ }
586
+ parseOr() {
587
+ let t = this.parseAnd();
588
+ for (; this.match(a.OR); ) {
589
+ const e = this.parseAnd();
590
+ t = { type: "BinaryExpr", operator: "or", left: t, right: e, line: t.line };
591
+ }
592
+ return t;
593
+ }
594
+ parseAnd() {
595
+ let t = this.parseComparison();
596
+ for (; this.match(a.AND); ) {
597
+ const e = this.parseComparison();
598
+ t = { type: "BinaryExpr", operator: "and", left: t, right: e, line: t.line };
599
+ }
600
+ return t;
601
+ }
602
+ parseComparison() {
603
+ let t = this.parseAddition();
604
+ for (; this.checkAny(a.EQ, a.NEQ, a.LT, a.GT, a.LTE, a.GTE); ) {
605
+ const e = this.advance().value, s = this.parseAddition();
606
+ t = { type: "BinaryExpr", operator: e, left: t, right: s, line: t.line };
607
+ }
608
+ return t;
609
+ }
610
+ parseAddition() {
611
+ let t = this.parseMultiplication();
612
+ for (; this.checkAny(a.PLUS, a.MINUS); ) {
613
+ const e = this.advance().value, s = this.parseMultiplication();
614
+ t = { type: "BinaryExpr", operator: e, left: t, right: s, line: t.line };
615
+ }
616
+ return t;
617
+ }
618
+ parseMultiplication() {
619
+ let t = this.parsePower();
620
+ for (; this.checkAny(a.STAR, a.SLASH, a.PERCENT); ) {
621
+ const e = this.advance().value, s = this.parsePower();
622
+ t = { type: "BinaryExpr", operator: e, left: t, right: s, line: t.line };
623
+ }
624
+ return t;
625
+ }
626
+ parsePower() {
627
+ let t = this.parseUnary();
628
+ if (this.match(a.POWER)) {
629
+ const e = this.parseUnary();
630
+ t = { type: "BinaryExpr", operator: "**", left: t, right: e, line: t.line };
631
+ }
632
+ return t;
633
+ }
634
+ parseUnary() {
635
+ if (this.match(a.MINUS)) {
636
+ const t = this.parseUnary();
637
+ return { type: "UnaryExpr", operator: "-", operand: t, line: t.line };
638
+ }
639
+ if (this.match(a.NOT)) {
640
+ const t = this.parseUnary();
641
+ return { type: "UnaryExpr", operator: "not", operand: t, line: t.line };
642
+ }
643
+ return this.parsePostfix();
644
+ }
645
+ parsePostfix() {
646
+ let t = this.parsePrimary();
647
+ for (; ; )
648
+ if (this.match(a.LBRACKET)) {
649
+ const e = this.parseExpression();
650
+ this.expect(a.RBRACKET), t = { type: "SeriesAccess", series: t, offset: e, line: t.line };
651
+ } else if (this.match(a.DOT)) {
652
+ const e = this.expect(a.IDENTIFIER).value;
653
+ if (this.check(a.LPAREN)) {
654
+ const s = this.buildCalleeName(t) + "." + e;
655
+ this.advance();
656
+ const { positional: r, named: n } = this.parseCallArgs();
657
+ this.expect(a.RPAREN), t = { type: "FunctionCall", callee: s, args: r, kwargs: n, line: t.line };
658
+ } else
659
+ t = { type: "MemberExpr", object: t, property: e, line: t.line };
660
+ } else if (this.check(a.LPAREN) && t.type === "Identifier") {
661
+ const e = t.name;
662
+ this.advance();
663
+ const { positional: s, named: r } = this.parseCallArgs();
664
+ this.expect(a.RPAREN), t = { type: "FunctionCall", callee: e, args: s, kwargs: r, line: t.line };
665
+ } else break;
666
+ return t;
667
+ }
668
+ parsePrimary() {
669
+ const t = this.peek();
670
+ if (this.check(a.NUMBER))
671
+ return this.advance(), { type: "NumberLiteral", value: parseFloat(t.value), line: t.line };
672
+ if (this.check(a.STRING))
673
+ return this.advance(), { type: "StringLiteral", value: t.value, line: t.line };
674
+ if (this.check(a.TRUE))
675
+ return this.advance(), { type: "BoolLiteral", value: !0, line: t.line };
676
+ if (this.check(a.FALSE))
677
+ return this.advance(), { type: "BoolLiteral", value: !1, line: t.line };
678
+ if (this.check(a.NA))
679
+ return this.advance(), { type: "NaLiteral", line: t.line };
680
+ if (this.check(a.COLOR_LITERAL))
681
+ return this.advance(), { type: "ColorLiteral", value: t.value, line: t.line };
682
+ if (this.match(a.LPAREN)) {
683
+ const e = this.parseExpression();
684
+ return this.expect(a.RPAREN), e;
685
+ }
686
+ if (this.check(a.IDENTIFIER))
687
+ return this.advance(), { type: "Identifier", name: t.value, line: t.line };
688
+ if (this.check(a.IF)) {
689
+ const e = this.parseIf();
690
+ return { type: "Identifier", name: "__if_expr__", line: e.line, _ifNode: e };
691
+ }
692
+ throw new C(`Unexpected token: ${t.type} (${t.value})`, t.line, t.column);
693
+ }
694
+ // ─── Call Arguments ────────────────────────────────────────
695
+ parseCallArgs() {
696
+ var s;
697
+ const t = [], e = [];
698
+ if (this.check(a.RPAREN)) return { positional: t, named: e };
699
+ do {
700
+ if (this.skipNewlines(), this.check(a.RPAREN)) break;
701
+ if (this.check(a.IDENTIFIER) && ((s = this.peekAt(1)) == null ? void 0 : s.type) === a.ASSIGN) {
702
+ const r = this.advance().value;
703
+ this.advance();
704
+ const n = this.parseExpression();
705
+ e.push({ key: r, value: n });
706
+ } else
707
+ t.push(this.parseExpression());
708
+ this.skipNewlines();
709
+ } while (this.match(a.COMMA));
710
+ return { positional: t, named: e };
711
+ }
712
+ // ─── Block Parsing ─────────────────────────────────────────
713
+ parseBlock() {
714
+ const t = [];
715
+ if (this.match(a.INDENT)) {
716
+ for (; !this.check(a.DEDENT) && !this.isAtEnd() && (this.skipNewlines(), !this.check(a.DEDENT)); ) {
717
+ const e = this.parseStatement();
718
+ e && t.push(e), this.skipNewlines();
719
+ }
720
+ this.check(a.DEDENT) && this.advance();
721
+ } else {
722
+ const e = this.parseStatement();
723
+ e && t.push(e);
724
+ }
725
+ return t;
726
+ }
727
+ parseBlockOrExpr() {
728
+ if (this.check(a.INDENT)) return this.parseBlock();
729
+ const t = this.parseExpression();
730
+ return [{ type: "ExpressionStatement", expression: t, line: t.line }];
731
+ }
732
+ // ─── Helpers ───────────────────────────────────────────────
733
+ buildCalleeName(t) {
734
+ return t.type === "Identifier" ? t.name : t.type === "MemberExpr" ? this.buildCalleeName(t.object) + "." + t.property : "__unknown__";
735
+ }
736
+ peek() {
737
+ return this.tokens[this.pos];
738
+ }
739
+ peekAt(t) {
740
+ return this.tokens[this.pos + t];
741
+ }
742
+ previous() {
743
+ return this.tokens[this.pos - 1];
744
+ }
745
+ isAtEnd() {
746
+ return this.pos >= this.tokens.length || this.tokens[this.pos].type === a.EOF;
747
+ }
748
+ advance() {
749
+ return this.isAtEnd() || this.pos++, this.previous();
750
+ }
751
+ check(t) {
752
+ return !this.isAtEnd() && this.peek().type === t;
753
+ }
754
+ checkAny(...t) {
755
+ return !this.isAtEnd() && t.includes(this.peek().type);
756
+ }
757
+ match(t) {
758
+ return this.check(t) ? (this.advance(), !0) : !1;
759
+ }
760
+ expect(t) {
761
+ if (this.check(t)) return this.advance();
762
+ const e = this.peek();
763
+ throw new C(`Expected ${t} but got ${e == null ? void 0 : e.type} (${e == null ? void 0 : e.value})`, e == null ? void 0 : e.line, e == null ? void 0 : e.column);
764
+ }
765
+ skipNewlines() {
766
+ for (; this.check(a.NEWLINE); ) this.advance();
767
+ }
768
+ }
769
+ /**
770
+ * pine-to-kline — Bar Context
771
+ * Provides per-bar OHLCV data as series for the runtime
772
+ * @license Apache-2.0
773
+ */
774
+ class M {
775
+ constructor(t) {
776
+ p(this, "dataList");
777
+ p(this, "open");
778
+ p(this, "high");
779
+ p(this, "low");
780
+ p(this, "close");
781
+ p(this, "volume");
782
+ p(this, "hl2");
783
+ p(this, "hlc3");
784
+ p(this, "ohlc4");
785
+ p(this, "time");
786
+ p(this, "barCount");
787
+ this.dataList = t, this.barCount = t.length, this.open = t.map((e) => e.open), this.high = t.map((e) => e.high), this.low = t.map((e) => e.low), this.close = t.map((e) => e.close), this.volume = t.map((e) => e.volume ?? 0), this.hl2 = t.map((e) => (e.high + e.low) / 2), this.hlc3 = t.map((e) => (e.high + e.low + e.close) / 3), this.ohlc4 = t.map((e) => (e.open + e.high + e.low + e.close) / 4), this.time = t.map((e) => e.timestamp);
788
+ }
789
+ /** Resolve a Pine source name to the data array */
790
+ resolveSource(t) {
791
+ return {
792
+ open: this.open,
793
+ high: this.high,
794
+ low: this.low,
795
+ close: this.close,
796
+ volume: this.volume,
797
+ hl2: this.hl2,
798
+ hlc3: this.hlc3,
799
+ ohlc4: this.ohlc4,
800
+ time: this.time
801
+ }[t] ?? this.close;
802
+ }
803
+ }
804
+ /**
805
+ * pine-to-kline — Variable Persistence
806
+ * Emulates Pine's `var` and `varip` semantics
807
+ * @license Apache-2.0
808
+ */
809
+ class W {
810
+ constructor() {
811
+ p(this, "vars", /* @__PURE__ */ new Map());
812
+ p(this, "varips", /* @__PURE__ */ new Map());
813
+ }
814
+ /** Initialize a `var` variable (set once, persists across bars) */
815
+ initVar(t, e) {
816
+ this.vars.has(t) || this.vars.set(t, e);
817
+ }
818
+ /** Initialize a `varip` variable */
819
+ initVarip(t, e) {
820
+ this.varips.has(t) || this.varips.set(t, e);
821
+ }
822
+ getVar(t) {
823
+ return this.vars.get(t);
824
+ }
825
+ setVar(t, e) {
826
+ this.vars.set(t, e);
827
+ }
828
+ hasVar(t) {
829
+ return this.vars.has(t);
830
+ }
831
+ getVarip(t) {
832
+ return this.varips.get(t);
833
+ }
834
+ setVarip(t, e) {
835
+ this.varips.set(t, e);
836
+ }
837
+ reset() {
838
+ this.vars.clear(), this.varips.clear();
839
+ }
840
+ }
841
+ /**
842
+ * pine-to-kline — Moving Average Functions
843
+ * Implements: sma, ema, rma, wma, hma, vwma, swma, dema, tema
844
+ * @license Apache-2.0
845
+ */
846
+ function L(i, t) {
847
+ return i.map((e, s) => {
848
+ if (s < t - 1) return NaN;
849
+ let r = 0;
850
+ for (let n = s - t + 1; n <= s; n++) r += i[n];
851
+ return r / t;
852
+ });
853
+ }
854
+ function m(i, t) {
855
+ const e = 2 / (t + 1), s = [];
856
+ for (let r = 0; r < i.length; r++) {
857
+ if (r === 0) {
858
+ s.push(i[r]);
859
+ continue;
860
+ }
861
+ s.push(i[r] * e + s[r - 1] * (1 - e));
862
+ }
863
+ return s;
864
+ }
865
+ function w(i, t) {
866
+ const e = 1 / t, s = [];
867
+ for (let r = 0; r < i.length; r++) {
868
+ if (r < t - 1) {
869
+ s.push(NaN);
870
+ continue;
871
+ }
872
+ if (r === t - 1) {
873
+ let n = 0;
874
+ for (let l = 0; l < t; l++) n += i[l];
875
+ s.push(n / t);
876
+ } else
877
+ s.push(e * i[r] + (1 - e) * s[r - 1]);
878
+ }
879
+ return s;
880
+ }
881
+ function y(i, t) {
882
+ const e = t * (t + 1) / 2;
883
+ return i.map((s, r) => {
884
+ if (r < t - 1) return NaN;
885
+ let n = 0;
886
+ for (let l = 0; l < t; l++)
887
+ n += i[r - l] * (t - l);
888
+ return n / e;
889
+ });
890
+ }
891
+ function H(i, t) {
892
+ const e = Math.floor(t / 2), s = Math.round(Math.sqrt(t)), r = y(i, e), n = y(i, t), l = r.map((h, c) => 2 * h - n[c]);
893
+ return y(l, s);
894
+ }
895
+ function j(i, t, e) {
896
+ return i.map((s, r) => {
897
+ if (r < e - 1) return NaN;
898
+ let n = 0, l = 0;
899
+ for (let h = r - e + 1; h <= r; h++)
900
+ n += i[h] * t[h], l += t[h];
901
+ return l === 0 ? NaN : n / l;
902
+ });
903
+ }
904
+ function $(i) {
905
+ return i.map((t, e) => e < 3 ? NaN : i[e] * (1 / 6) + i[e - 1] * (2 / 6) + i[e - 2] * (2 / 6) + i[e - 3] * (1 / 6));
906
+ }
907
+ function K(i, t) {
908
+ const e = m(i, t), s = m(e, t);
909
+ return e.map((r, n) => 2 * r - s[n]);
910
+ }
911
+ function Y(i, t) {
912
+ const e = m(i, t), s = m(e, t), r = m(s, t);
913
+ return e.map((n, l) => 3 * n - 3 * s[l] + r[l]);
914
+ }
915
+ /**
916
+ * pine-to-kline — Momentum Indicators
917
+ * Implements: rsi, macd, stoch, cci, mom, roc
918
+ * @license Apache-2.0
919
+ */
920
+ function Q(i, t) {
921
+ const e = [0], s = [0];
922
+ for (let l = 1; l < i.length; l++) {
923
+ const h = i[l] - i[l - 1];
924
+ e.push(h > 0 ? h : 0), s.push(h < 0 ? Math.abs(h) : 0);
925
+ }
926
+ const r = w(e, t), n = w(s, t);
927
+ return i.map((l, h) => isNaN(r[h]) || isNaN(n[h]) ? NaN : n[h] === 0 ? 100 : 100 - 100 / (1 + r[h] / n[h]));
928
+ }
929
+ function q(i, t = 12, e = 26, s = 9) {
930
+ const r = m(i, t), n = m(i, e), l = r.map((o, u) => o - n[u]), h = m(l, s), c = l.map((o, u) => o - h[u]);
931
+ return { macd: l, signal: h, hist: c };
932
+ }
933
+ function z(i, t, e, s) {
934
+ return i.map((r, n) => {
935
+ if (n < s - 1) return NaN;
936
+ let l = -1 / 0, h = 1 / 0;
937
+ for (let c = n - s + 1; c <= n; c++)
938
+ t[c] > l && (l = t[c]), e[c] < h && (h = e[c]);
939
+ return l === h ? 0 : (i[n] - h) / (l - h) * 100;
940
+ });
941
+ }
942
+ function X(i, t) {
943
+ const e = L(i, t);
944
+ return i.map((s, r) => {
945
+ if (r < t - 1) return NaN;
946
+ let n = 0;
947
+ for (let l = r - t + 1; l <= r; l++)
948
+ n += Math.abs(i[l] - e[r]);
949
+ return n /= t, n === 0 ? 0 : (i[r] - e[r]) / (0.015 * n);
950
+ });
951
+ }
952
+ function Z(i, t) {
953
+ return i.map((e, s) => s < t ? NaN : e - i[s - t]);
954
+ }
955
+ function J(i, t) {
956
+ return i.map((e, s) => {
957
+ if (s < t) return NaN;
958
+ const r = i[s - t];
959
+ return r === 0 ? 0 : (e - r) / r * 100;
960
+ });
961
+ }
962
+ /**
963
+ * pine-to-kline — Volatility Indicators
964
+ * Implements: atr, bb, kc, donchian
965
+ * @license Apache-2.0
966
+ */
967
+ function F(i, t, e, s) {
968
+ const r = i.map((n, l) => l === 0 ? n - t[l] : Math.max(
969
+ n - t[l],
970
+ Math.abs(n - e[l - 1]),
971
+ Math.abs(t[l] - e[l - 1])
972
+ ));
973
+ return w(r, s);
974
+ }
975
+ function tt(i, t, e = 2) {
976
+ const s = L(i, t);
977
+ return i.map((r, n) => {
978
+ if (n < t - 1) return { upper: NaN, basis: NaN, lower: NaN };
979
+ let l = 0;
980
+ for (let c = n - t + 1; c <= n; c++)
981
+ l += Math.pow(i[c] - s[n], 2);
982
+ const h = Math.sqrt(l / t);
983
+ return {
984
+ upper: s[n] + e * h,
985
+ basis: s[n],
986
+ lower: s[n] - e * h
987
+ };
988
+ });
989
+ }
990
+ function et(i, t, e, s, r, n = 1.5) {
991
+ const l = m(i, r), h = F(t, e, s, r);
992
+ return i.map((c, o) => ({
993
+ upper: l[o] + n * h[o],
994
+ basis: l[o],
995
+ lower: l[o] - n * h[o]
996
+ }));
997
+ }
998
+ function st(i, t, e) {
999
+ return i.map((s, r) => {
1000
+ if (r < e - 1) return { upper: NaN, basis: NaN, lower: NaN };
1001
+ let n = -1 / 0, l = 1 / 0;
1002
+ for (let h = r - e + 1; h <= r; h++)
1003
+ i[h] > n && (n = i[h]), t[h] < l && (l = t[h]);
1004
+ return {
1005
+ upper: n,
1006
+ basis: (n + l) / 2,
1007
+ lower: l
1008
+ };
1009
+ });
1010
+ }
1011
+ function it(i, t, e) {
1012
+ return i.map((s, r) => r === 0 ? s - t[r] : Math.max(
1013
+ s - t[r],
1014
+ Math.abs(s - e[r - 1]),
1015
+ Math.abs(t[r] - e[r - 1])
1016
+ ));
1017
+ }
1018
+ /**
1019
+ * pine-to-kline — Crossover Functions
1020
+ * Implements: crossover, crossunder, cross
1021
+ * @license Apache-2.0
1022
+ */
1023
+ function rt(i, t) {
1024
+ return i.map((e, s) => s === 0 ? !1 : i[s - 1] <= t[s - 1] && e > t[s]);
1025
+ }
1026
+ function nt(i, t) {
1027
+ return i.map((e, s) => s === 0 ? !1 : i[s - 1] >= t[s - 1] && e < t[s]);
1028
+ }
1029
+ function at(i, t) {
1030
+ return i.map((e, s) => s === 0 ? !1 : i[s - 1] <= t[s - 1] && i[s] > t[s] || i[s - 1] >= t[s - 1] && i[s] < t[s]);
1031
+ }
1032
+ function lt(i, t = 1) {
1033
+ return i.map((e, s) => s < t ? NaN : e - i[s - t]);
1034
+ }
1035
+ function ht(i, t) {
1036
+ return i.map((e, s) => {
1037
+ if (s < t) return !1;
1038
+ for (let r = s - t + 1; r <= s; r++)
1039
+ if (i[r] <= i[r - 1]) return !1;
1040
+ return !0;
1041
+ });
1042
+ }
1043
+ function ct(i, t) {
1044
+ return i.map((e, s) => {
1045
+ if (s < t) return !1;
1046
+ for (let r = s - t + 1; r <= s; r++)
1047
+ if (i[r] >= i[r - 1]) return !1;
1048
+ return !0;
1049
+ });
1050
+ }
1051
+ /**
1052
+ * pine-to-kline — TA Utility Functions
1053
+ * Implements: highest, lowest, highestbars, lowestbars, barssince, valuewhen, pivothigh, pivotlow
1054
+ * @license Apache-2.0
1055
+ */
1056
+ function ot(i, t) {
1057
+ return i.map((e, s) => {
1058
+ if (s < t - 1) return NaN;
1059
+ let r = -1 / 0;
1060
+ for (let n = s - t + 1; n <= s; n++)
1061
+ i[n] > r && (r = i[n]);
1062
+ return r;
1063
+ });
1064
+ }
1065
+ function ut(i, t) {
1066
+ return i.map((e, s) => {
1067
+ if (s < t - 1) return NaN;
1068
+ let r = 1 / 0;
1069
+ for (let n = s - t + 1; n <= s; n++)
1070
+ i[n] < r && (r = i[n]);
1071
+ return r;
1072
+ });
1073
+ }
1074
+ function pt(i, t) {
1075
+ return i.map((e, s) => {
1076
+ if (s < t - 1) return NaN;
1077
+ let r = -1 / 0, n = s;
1078
+ for (let l = s - t + 1; l <= s; l++)
1079
+ i[l] >= r && (r = i[l], n = l);
1080
+ return -(s - n);
1081
+ });
1082
+ }
1083
+ function ft(i, t) {
1084
+ return i.map((e, s) => {
1085
+ if (s < t - 1) return NaN;
1086
+ let r = 1 / 0, n = s;
1087
+ for (let l = s - t + 1; l <= s; l++)
1088
+ i[l] <= r && (r = i[l], n = l);
1089
+ return -(s - n);
1090
+ });
1091
+ }
1092
+ function Nt(i) {
1093
+ let t = NaN;
1094
+ return i.map((e) => (e ? t = 0 : isNaN(t) || t++, t));
1095
+ }
1096
+ function mt(i, t, e = 0) {
1097
+ const s = [], r = [];
1098
+ for (let n = 0; n < t.length; n++)
1099
+ i[n] && r.unshift(t[n]), s.push(r[e] ?? NaN);
1100
+ return s;
1101
+ }
1102
+ function Et(i, t, e) {
1103
+ return i.map((s, r) => {
1104
+ if (r < t || r + e >= i.length) return NaN;
1105
+ for (let n = r - t; n < r; n++)
1106
+ if (i[n] > s) return NaN;
1107
+ for (let n = r + 1; n <= r + e; n++)
1108
+ if (i[n] > s) return NaN;
1109
+ return s;
1110
+ });
1111
+ }
1112
+ function vt(i, t, e) {
1113
+ return i.map((s, r) => {
1114
+ if (r < t || r + e >= i.length) return NaN;
1115
+ for (let n = r - t; n < r; n++)
1116
+ if (i[n] < s) return NaN;
1117
+ for (let n = r + 1; n <= r + e; n++)
1118
+ if (i[n] < s) return NaN;
1119
+ return s;
1120
+ });
1121
+ }
1122
+ function dt(i) {
1123
+ let t = 0;
1124
+ return i.map((e) => (t += e, t));
1125
+ }
1126
+ function At(i, t) {
1127
+ return i.map((e, s) => {
1128
+ if (s < t - 1) return NaN;
1129
+ let r = 0;
1130
+ for (let h = s - t + 1; h <= s; h++) r += i[h];
1131
+ const n = r / t;
1132
+ let l = 0;
1133
+ for (let h = s - t + 1; h <= s; h++) l += Math.pow(i[h] - n, 2);
1134
+ return Math.sqrt(l / t);
1135
+ });
1136
+ }
1137
+ function It(i, t) {
1138
+ return i.map((e, s) => {
1139
+ if (s < t) return NaN;
1140
+ let r = 0;
1141
+ for (let n = s - t; n < s; n++)
1142
+ i[n] <= e && r++;
1143
+ return r / t * 100;
1144
+ });
1145
+ }
1146
+ /**
1147
+ * pine-to-kline — TA Namespace Barrel Export
1148
+ * @license Apache-2.0
1149
+ */
1150
+ const St = {
1151
+ // Moving averages
1152
+ "ta.sma": L,
1153
+ "ta.ema": m,
1154
+ "ta.rma": w,
1155
+ "ta.wma": y,
1156
+ "ta.hma": H,
1157
+ "ta.vwma": j,
1158
+ "ta.swma": $,
1159
+ "ta.dema": K,
1160
+ "ta.tema": Y,
1161
+ // Momentum
1162
+ "ta.rsi": Q,
1163
+ "ta.macd": q,
1164
+ "ta.stoch": z,
1165
+ "ta.cci": X,
1166
+ "ta.mom": Z,
1167
+ "ta.roc": J,
1168
+ // Volatility
1169
+ "ta.atr": F,
1170
+ "ta.bb": tt,
1171
+ "ta.kc": et,
1172
+ "ta.donchian": st,
1173
+ "ta.tr": it,
1174
+ // Crossover
1175
+ "ta.crossover": rt,
1176
+ "ta.crossunder": nt,
1177
+ "ta.cross": at,
1178
+ "ta.change": lt,
1179
+ "ta.rising": ht,
1180
+ "ta.falling": ct,
1181
+ // Utility
1182
+ "ta.highest": ot,
1183
+ "ta.lowest": ut,
1184
+ "ta.highestbars": pt,
1185
+ "ta.lowestbars": ft,
1186
+ "ta.barssince": Nt,
1187
+ "ta.valuewhen": mt,
1188
+ "ta.pivothigh": Et,
1189
+ "ta.pivotlow": vt,
1190
+ "ta.cum": dt,
1191
+ "ta.stdev": At,
1192
+ "ta.percentrank": It
1193
+ };
1194
+ /**
1195
+ * pine-to-kline — Math Namespace Functions
1196
+ * Wraps JavaScript Math.* to match Pine's math.* namespace
1197
+ * @license Apache-2.0
1198
+ */
1199
+ const Rt = {
1200
+ "math.abs": (i) => Math.abs(i),
1201
+ "math.ceil": (i) => Math.ceil(i),
1202
+ "math.floor": (i) => Math.floor(i),
1203
+ "math.round": (i, t) => {
1204
+ if (t === void 0) return Math.round(i);
1205
+ const e = Math.pow(10, t);
1206
+ return Math.round(i * e) / e;
1207
+ },
1208
+ "math.log": (i) => Math.log(i),
1209
+ "math.log10": (i) => Math.log10(i),
1210
+ "math.pow": (i, t) => Math.pow(i, t),
1211
+ "math.sqrt": (i) => Math.sqrt(i),
1212
+ "math.exp": (i) => Math.exp(i),
1213
+ "math.max": (...i) => Math.max(...i),
1214
+ "math.min": (...i) => Math.min(...i),
1215
+ "math.sign": (i) => Math.sign(i),
1216
+ "math.avg": (...i) => i.reduce((t, e) => t + e, 0) / i.length,
1217
+ "math.sum": (i, t) => {
1218
+ const e = [];
1219
+ for (let s = 0; s < i.length; s++) {
1220
+ if (s < t - 1) {
1221
+ e.push(NaN);
1222
+ continue;
1223
+ }
1224
+ let r = 0;
1225
+ for (let n = s - t + 1; n <= s; n++) r += i[n];
1226
+ e.push(r);
1227
+ }
1228
+ return e;
1229
+ },
1230
+ "math.sin": (i) => Math.sin(i),
1231
+ "math.cos": (i) => Math.cos(i),
1232
+ "math.tan": (i) => Math.tan(i),
1233
+ "math.asin": (i) => Math.asin(i),
1234
+ "math.acos": (i) => Math.acos(i),
1235
+ "math.atan": (i) => Math.atan(i),
1236
+ "math.random": () => Math.random(),
1237
+ "math.todegrees": (i) => i * (180 / Math.PI),
1238
+ "math.toradians": (i) => i * (Math.PI / 180)
1239
+ }, yt = {
1240
+ "math.pi": Math.PI,
1241
+ "math.e": Math.E,
1242
+ "math.phi": 1.618033988749895,
1243
+ "math.rphi": 0.618033988749895
1244
+ };
1245
+ /**
1246
+ * pine-to-kline — Color Constants
1247
+ * All Pine color.* constants → hex values
1248
+ * @license Apache-2.0
1249
+ */
1250
+ const d = {
1251
+ "color.aqua": "#00BCD4",
1252
+ "color.black": "#000000",
1253
+ "color.blue": "#2196F3",
1254
+ "color.fuchsia": "#E040FB",
1255
+ "color.gray": "#9E9E9E",
1256
+ "color.green": "#4CAF50",
1257
+ "color.lime": "#00E676",
1258
+ "color.maroon": "#880E4F",
1259
+ "color.navy": "#0D47A1",
1260
+ "color.olive": "#808000",
1261
+ "color.orange": "#FF9800",
1262
+ "color.purple": "#9C27B0",
1263
+ "color.red": "#F44336",
1264
+ "color.silver": "#B0BEC5",
1265
+ "color.teal": "#009688",
1266
+ "color.white": "#FFFFFF",
1267
+ "color.yellow": "#FFEB3B"
1268
+ };
1269
+ /**
1270
+ * pine-to-kline — Color Functions
1271
+ * Implements: color.new(), color.rgb(), color.from_gradient()
1272
+ * @license Apache-2.0
1273
+ */
1274
+ function wt(i, t) {
1275
+ const e = Math.round((1 - t / 100) * 255), s = i.startsWith("#") ? i : "#000000";
1276
+ return (s.length === 9 ? s.slice(0, 7) : s) + e.toString(16).padStart(2, "0");
1277
+ }
1278
+ function T(i, t, e, s = 0) {
1279
+ const r = (l) => Math.max(0, Math.min(255, Math.round(l))), n = Math.round((1 - s / 100) * 255);
1280
+ return "#" + r(i).toString(16).padStart(2, "0") + r(t).toString(16).padStart(2, "0") + r(e).toString(16).padStart(2, "0") + (n < 255 ? n.toString(16).padStart(2, "0") : "");
1281
+ }
1282
+ function xt(i, t, e, s, r) {
1283
+ const n = Math.max(0, Math.min(1, (i - t) / (e - t))), l = (u) => {
1284
+ const f = u.replace("#", "");
1285
+ return {
1286
+ r: parseInt(f.slice(0, 2), 16),
1287
+ g: parseInt(f.slice(2, 4), 16),
1288
+ b: parseInt(f.slice(4, 6), 16)
1289
+ };
1290
+ }, h = l(s), c = l(r), o = (u, f) => Math.round(u + (f - u) * n);
1291
+ return T(o(h.r, c.r), o(h.g, c.g), o(h.b, c.b));
1292
+ }
1293
+ const gt = {
1294
+ "color.new": wt,
1295
+ "color.rgb": T,
1296
+ "color.from_gradient": xt
1297
+ };
1298
+ /**
1299
+ * pine-to-kline — Input Functions
1300
+ * Handles input.int(), input.float(), input.bool(), etc.
1301
+ * These extract metadata for KlineChart calcParams.
1302
+ * @license Apache-2.0
1303
+ */
1304
+ let A = 0;
1305
+ function kt() {
1306
+ A = 0;
1307
+ }
1308
+ function Lt(i, t, e) {
1309
+ return {
1310
+ meta: {
1311
+ id: `input_${A++}`,
1312
+ type: "int",
1313
+ title: t ?? null,
1314
+ defaultValue: i,
1315
+ minval: e == null ? void 0 : e.minval,
1316
+ maxval: e == null ? void 0 : e.maxval,
1317
+ step: (e == null ? void 0 : e.step) ?? 1
1318
+ },
1319
+ value: i
1320
+ };
1321
+ }
1322
+ function bt(i, t, e) {
1323
+ return {
1324
+ meta: {
1325
+ id: `input_${A++}`,
1326
+ type: "float",
1327
+ title: t ?? null,
1328
+ defaultValue: i,
1329
+ minval: e == null ? void 0 : e.minval,
1330
+ maxval: e == null ? void 0 : e.maxval,
1331
+ step: (e == null ? void 0 : e.step) ?? 0.1
1332
+ },
1333
+ value: i
1334
+ };
1335
+ }
1336
+ function Ct(i, t) {
1337
+ return {
1338
+ meta: {
1339
+ id: `input_${A++}`,
1340
+ type: "bool",
1341
+ title: t ?? null,
1342
+ defaultValue: i
1343
+ },
1344
+ value: i
1345
+ };
1346
+ }
1347
+ function Ot(i, t, e) {
1348
+ return {
1349
+ meta: {
1350
+ id: `input_${A++}`,
1351
+ type: "string",
1352
+ title: t ?? null,
1353
+ defaultValue: i,
1354
+ options: e
1355
+ },
1356
+ value: i
1357
+ };
1358
+ }
1359
+ function Pt(i, t) {
1360
+ return {
1361
+ meta: {
1362
+ id: `input_${A++}`,
1363
+ type: "color",
1364
+ title: t ?? null,
1365
+ defaultValue: i
1366
+ },
1367
+ value: i
1368
+ };
1369
+ }
1370
+ function _t(i, t) {
1371
+ return {
1372
+ meta: {
1373
+ id: `input_${A++}`,
1374
+ type: "source",
1375
+ title: t ?? null,
1376
+ defaultValue: i
1377
+ },
1378
+ value: i
1379
+ };
1380
+ }
1381
+ function Mt(i, t) {
1382
+ const e = typeof i == "number" ? Number.isInteger(i) ? "int" : "float" : typeof i == "boolean" ? "bool" : "string";
1383
+ return {
1384
+ meta: {
1385
+ id: `input_${A++}`,
1386
+ type: e,
1387
+ title: t ?? null,
1388
+ defaultValue: i
1389
+ },
1390
+ value: i
1391
+ };
1392
+ }
1393
+ const Dt = {
1394
+ input: Mt,
1395
+ "input.int": Lt,
1396
+ "input.float": bt,
1397
+ "input.bool": Ct,
1398
+ "input.string": Ot,
1399
+ "input.color": Pt,
1400
+ "input.source": _t
1401
+ };
1402
+ /**
1403
+ * pine-to-kline — Builtins Master Index
1404
+ * Central registry of all built-in functions and constants
1405
+ * @license Apache-2.0
1406
+ */
1407
+ const g = {
1408
+ ...St,
1409
+ ...Rt,
1410
+ ...gt,
1411
+ ...Dt
1412
+ }, R = {
1413
+ ...yt,
1414
+ ...d,
1415
+ // Pine special constants
1416
+ na: NaN,
1417
+ true: !0,
1418
+ false: !1
1419
+ };
1420
+ /**
1421
+ * pine-to-kline — Pine Runtime
1422
+ * Walks the AST and executes PineScript logic against bar data.
1423
+ * Produces arrays of computed values for each plot.
1424
+ * @license Apache-2.0
1425
+ */
1426
+ class D {
1427
+ constructor() {
1428
+ p(this, "ctx");
1429
+ p(this, "vars", new W());
1430
+ p(this, "scope", /* @__PURE__ */ new Map());
1431
+ p(this, "functions", /* @__PURE__ */ new Map());
1432
+ p(this, "meta", { name: "Untitled", shortName: null, overlay: !1, format: null, precision: null, scale: null, max_bars_back: null });
1433
+ p(this, "inputs", []);
1434
+ p(this, "plots", []);
1435
+ p(this, "hlines", []);
1436
+ p(this, "plotResults", /* @__PURE__ */ new Map());
1437
+ p(this, "warnings", []);
1438
+ p(this, "inputIndex", 0);
1439
+ }
1440
+ execute(t, e, s) {
1441
+ kt(), this.inputs = [], this.plots = [], this.hlines = [], this.plotResults = /* @__PURE__ */ new Map(), this.warnings = [], this.functions = /* @__PURE__ */ new Map(), this.inputIndex = 0, this.ctx = new M(e);
1442
+ const r = [];
1443
+ this.scope = /* @__PURE__ */ new Map(), this.vars.reset(), this.firstPass(t, s);
1444
+ const n = (l, h) => this.runCalc(t, l, h);
1445
+ return {
1446
+ meta: this.meta,
1447
+ inputs: this.inputs,
1448
+ plots: this.plots,
1449
+ hlines: this.hlines,
1450
+ calcFn: n,
1451
+ warnings: this.warnings,
1452
+ errors: r
1453
+ };
1454
+ }
1455
+ firstPass(t, e) {
1456
+ for (const s of t.body)
1457
+ s.type === "Indicator" ? this.evalIndicator(s) : s.type === "FunctionDef" && this.functions.set(s.name, { params: s.params.map((r) => ({ name: r.name, defaultValue: r.defaultValue ? this.evalExpr(r.defaultValue) : null })), body: s.body });
1458
+ this.runOnce(t, this.ctx.dataList, e ?? []);
1459
+ }
1460
+ runCalc(t, e, s) {
1461
+ return this.runOnce(t, e, s);
1462
+ }
1463
+ runOnce(t, e, s) {
1464
+ this.ctx = new M(e), this.scope = /* @__PURE__ */ new Map(), this.vars.reset(), this.plotResults = /* @__PURE__ */ new Map(), this.inputIndex = 0;
1465
+ const r = [], n = [], l = [], h = {
1466
+ open: this.ctx.open,
1467
+ high: this.ctx.high,
1468
+ low: this.ctx.low,
1469
+ close: this.ctx.close,
1470
+ volume: this.ctx.volume,
1471
+ hl2: this.ctx.hl2,
1472
+ hlc3: this.ctx.hlc3,
1473
+ ohlc4: this.ctx.ohlc4
1474
+ };
1475
+ for (const u of t.body)
1476
+ u.type === "FunctionDef" && this.functions.set(u.name, { params: u.params.map((f) => ({ name: f.name, defaultValue: f.defaultValue ? this.evalExpr(f.defaultValue) : null })), body: u.body });
1477
+ for (const u of t.body)
1478
+ if (!(u.type === "Indicator" || u.type === "FunctionDef"))
1479
+ try {
1480
+ this.evalNode(u, h, s, r, n, l);
1481
+ } catch (f) {
1482
+ this.warnings.push(`Runtime warning at line ${u.line}: ${f.message}`);
1483
+ }
1484
+ r.length > 0 && (this.inputs = r), n.length > 0 && (this.plots = n), l.length > 0 && (this.hlines = l);
1485
+ const c = e.length, o = [];
1486
+ for (let u = 0; u < c; u++) {
1487
+ const f = {};
1488
+ for (const [E, v] of this.plotResults)
1489
+ f[E] = v[u] ?? NaN;
1490
+ o.push(f);
1491
+ }
1492
+ return o;
1493
+ }
1494
+ // ─── Node Evaluation ──────────────────────────────────────
1495
+ evalNode(t, e, s, r, n, l) {
1496
+ switch (t.type) {
1497
+ case "VarDecl":
1498
+ return this.evalVarDecl(t, e, s, r);
1499
+ case "Assign":
1500
+ return this.evalAssign(t, e, s, r);
1501
+ case "If":
1502
+ return this.evalIf(t, e, s, r, n, l);
1503
+ case "For":
1504
+ return this.evalFor(t, e, s, r, n, l);
1505
+ case "While":
1506
+ return this.evalWhile(t, e, s, r, n, l);
1507
+ case "PlotCall":
1508
+ return this.evalPlot(t, e, s, r, n);
1509
+ case "HlineCall":
1510
+ return this.evalHline(t, l);
1511
+ case "ExpressionStatement":
1512
+ return this.evalExpr(t.expression, e, s, r);
1513
+ case "Return":
1514
+ return t.value ? this.evalExpr(t.value, e, s, r) : void 0;
1515
+ default:
1516
+ return;
1517
+ }
1518
+ }
1519
+ evalIndicator(t) {
1520
+ var e, s, r, n, l;
1521
+ ((e = t.name) == null ? void 0 : e.type) === "StringLiteral" && (this.meta.name = t.name.value);
1522
+ for (const h of t.args)
1523
+ h.key === "overlay" && ((s = h.value) == null ? void 0 : s.type) === "BoolLiteral" && (this.meta.overlay = h.value.value), h.key === "shorttitle" && ((r = h.value) == null ? void 0 : r.type) === "StringLiteral" && (this.meta.shortName = h.value.value), h.key === "format" && ((n = h.value) == null ? void 0 : n.type) === "StringLiteral" && (this.meta.format = h.value.value), h.key === "precision" && ((l = h.value) == null ? void 0 : l.type) === "NumberLiteral" && (this.meta.precision = h.value.value);
1524
+ }
1525
+ evalVarDecl(t, e, s, r) {
1526
+ const n = this.evalExpr(t.value, e, s, r);
1527
+ if (Array.isArray(t.name)) {
1528
+ const l = t.name;
1529
+ if (n && typeof n == "object") {
1530
+ const h = Object.values(n);
1531
+ l.forEach((c, o) => this.scope.set(c, h[o]));
1532
+ }
1533
+ } else
1534
+ t.persistent ? (this.vars.initVar(t.name, n), this.scope.set(t.name, this.vars.getVar(t.name))) : t.persistentTick ? (this.vars.initVarip(t.name, n), this.scope.set(t.name, this.vars.getVarip(t.name))) : this.scope.set(t.name, n);
1535
+ }
1536
+ evalAssign(t, e, s, r) {
1537
+ const n = this.evalExpr(t.value, e, s, r), l = this.scope.get(t.target);
1538
+ switch (t.operator) {
1539
+ case ":=":
1540
+ case "=":
1541
+ this.scope.set(t.target, n);
1542
+ break;
1543
+ case "+=":
1544
+ this.scope.set(t.target, (l ?? 0) + n);
1545
+ break;
1546
+ case "-=":
1547
+ this.scope.set(t.target, (l ?? 0) - n);
1548
+ break;
1549
+ case "*=":
1550
+ this.scope.set(t.target, (l ?? 0) * n);
1551
+ break;
1552
+ case "/=":
1553
+ this.scope.set(t.target, (l ?? 0) / n);
1554
+ break;
1555
+ case "%=":
1556
+ this.scope.set(t.target, (l ?? 0) % n);
1557
+ break;
1558
+ }
1559
+ this.vars.hasVar(t.target) && this.vars.setVar(t.target, this.scope.get(t.target));
1560
+ }
1561
+ evalIf(t, e, s, r, n, l) {
1562
+ if (this.evalExpr(t.condition, e, s, r))
1563
+ for (const c of t.body) this.evalNode(c, e, s, r, n, l);
1564
+ else {
1565
+ let c = !1;
1566
+ for (const o of t.elseIf)
1567
+ if (this.evalExpr(o.condition, e, s, r)) {
1568
+ for (const u of o.body) this.evalNode(u, e, s, r, n, l);
1569
+ c = !0;
1570
+ break;
1571
+ }
1572
+ if (!c && t.elseBody)
1573
+ for (const o of t.elseBody) this.evalNode(o, e, s, r, n, l);
1574
+ }
1575
+ }
1576
+ evalFor(t, e, s, r, n, l) {
1577
+ const h = this.evalExpr(t.start, e, s, r), c = this.evalExpr(t.end, e, s, r), o = t.step ? this.evalExpr(t.step, e, s, r) : 1;
1578
+ for (let u = h; o > 0 ? u <= c : u >= c; u += o) {
1579
+ this.scope.set(t.variable, u);
1580
+ for (const f of t.body) this.evalNode(f, e, s, r, n, l);
1581
+ }
1582
+ }
1583
+ evalWhile(t, e, s, r, n, l) {
1584
+ let h = 0;
1585
+ for (; this.evalExpr(t.condition, e, s, r) && h++ < 1e4; )
1586
+ for (const c of t.body) this.evalNode(c, e, s, r, n, l);
1587
+ }
1588
+ evalPlot(t, e, s, r, n) {
1589
+ const l = this.evalExpr(t.args[0], e, s, r), h = Object.fromEntries(t.kwargs.map((u) => [u.key, this.evalExpr(u.value, e, s, r)])), o = (h.title ?? `plot_${n.length}`).toString().toLowerCase().replace(/\s+/g, "_");
1590
+ n.push({
1591
+ id: o,
1592
+ title: h.title ?? null,
1593
+ color: this.resolveColor(h.color),
1594
+ linewidth: h.linewidth ?? 1,
1595
+ style: h.style ?? null
1596
+ }), Array.isArray(l) ? this.plotResults.set(o, l) : typeof l == "number" && this.plotResults.set(o, new Array(this.ctx.barCount).fill(l));
1597
+ }
1598
+ evalHline(t, e) {
1599
+ const s = this.evalExpr(t.price), r = Object.fromEntries(t.kwargs.map((n) => [n.key, this.evalExpr(n.value)]));
1600
+ e.push({
1601
+ price: typeof s == "number" ? s : NaN,
1602
+ title: r.title ?? null,
1603
+ color: this.resolveColor(r.color),
1604
+ linestyle: r.linestyle ?? null,
1605
+ linewidth: r.linewidth ?? 1
1606
+ });
1607
+ }
1608
+ // ─── Expression Evaluation ────────────────────────────────
1609
+ evalExpr(t, e, s, r) {
1610
+ if (t)
1611
+ switch (t.type) {
1612
+ case "NumberLiteral":
1613
+ return t.value;
1614
+ case "StringLiteral":
1615
+ return t.value;
1616
+ case "BoolLiteral":
1617
+ return t.value;
1618
+ case "ColorLiteral":
1619
+ return t.value;
1620
+ case "NaLiteral":
1621
+ return NaN;
1622
+ case "Identifier": {
1623
+ const n = t.name;
1624
+ return this.scope.has(n) ? this.scope.get(n) : e && n in e ? e[n] : R[n] !== void 0 ? R[n] : d[n] ? d[n] : n === "bar_index" ? Array.from({ length: this.ctx.barCount }, (l, h) => h) : void 0;
1625
+ }
1626
+ case "BinaryExpr": {
1627
+ const n = this.evalExpr(t.left, e, s, r), l = this.evalExpr(t.right, e, s, r);
1628
+ return this.evalBinary(t.operator, n, l);
1629
+ }
1630
+ case "UnaryExpr": {
1631
+ const n = this.evalExpr(t.operand, e, s, r);
1632
+ return t.operator === "-" ? Array.isArray(n) ? n.map((l) => -l) : -n : t.operator === "not" ? Array.isArray(n) ? n.map((l) => !l) : !n : n;
1633
+ }
1634
+ case "TernaryExpr": {
1635
+ const n = this.evalExpr(t.condition, e, s, r);
1636
+ if (Array.isArray(n)) {
1637
+ const l = this.evalExpr(t.consequent, e, s, r), h = this.evalExpr(t.alternate, e, s, r);
1638
+ return n.map((c, o) => c ? Array.isArray(l) ? l[o] : l : Array.isArray(h) ? h[o] : h);
1639
+ }
1640
+ return n ? this.evalExpr(t.consequent, e, s, r) : this.evalExpr(t.alternate, e, s, r);
1641
+ }
1642
+ case "FunctionCall":
1643
+ return this.evalFunctionCall(t, e, s, r);
1644
+ case "SeriesAccess": {
1645
+ const n = this.evalExpr(t.series, e, s, r), l = this.evalExpr(t.offset, e, s, r);
1646
+ return Array.isArray(n) && typeof l == "number" ? n.map((h, c) => c - l >= 0 ? n[c - l] : NaN) : NaN;
1647
+ }
1648
+ case "MemberExpr": {
1649
+ const n = this.buildMemberName(t);
1650
+ return R[n] !== void 0 ? R[n] : d[n] ? d[n] : e && n in e ? e[n] : n;
1651
+ }
1652
+ default:
1653
+ return;
1654
+ }
1655
+ }
1656
+ evalFunctionCall(t, e, s, r) {
1657
+ const n = t.args.map((c) => this.evalExpr(c, e, s, r)), l = Object.fromEntries(t.kwargs.map((c) => [c.key, this.evalExpr(c.value, e, s, r)])), h = t.callee;
1658
+ if (h.startsWith("input")) {
1659
+ const c = g[h];
1660
+ if (c) {
1661
+ const o = c(n[0], l.title ?? n[1], l);
1662
+ r && r.push(o.meta);
1663
+ const u = this.inputIndex++, f = s && s[u] !== void 0 ? s[u] : o.value;
1664
+ return o.meta.type === "source" && e ? e[f] ?? e.close : f;
1665
+ }
1666
+ }
1667
+ if (g[h])
1668
+ return g[h](...n);
1669
+ if (this.functions.has(h))
1670
+ return this.callUserFunction(h, n, e, s, r);
1671
+ if (h === "nz") {
1672
+ const c = n[0], o = n[1] ?? 0;
1673
+ return Array.isArray(c) ? c.map((u) => u === void 0 || isNaN(u) ? o : u) : c === void 0 || typeof c == "number" && isNaN(c) ? o : c;
1674
+ }
1675
+ if (h === "na") {
1676
+ const c = n[0];
1677
+ return Array.isArray(c) ? c.map((o) => o === void 0 || typeof o == "number" && isNaN(o)) : c === void 0 || typeof c == "number" && isNaN(c);
1678
+ }
1679
+ if (h === "fixnan") {
1680
+ const c = n[0];
1681
+ if (Array.isArray(c)) {
1682
+ let o = NaN;
1683
+ return c.map((u) => (isNaN(u) || (o = u), o));
1684
+ }
1685
+ return c;
1686
+ }
1687
+ return h === "str.tostring" ? String(n[0]) : (this.warnings.push(`Unknown function: ${h}`), NaN);
1688
+ }
1689
+ callUserFunction(t, e, s, r, n) {
1690
+ const l = this.functions.get(t), h = new Map(this.scope);
1691
+ l.params.forEach((o, u) => {
1692
+ this.scope.set(o.name, e[u] ?? o.defaultValue);
1693
+ });
1694
+ let c;
1695
+ for (const o of l.body) {
1696
+ if (o.type === "Return") {
1697
+ c = o.value ? this.evalExpr(o.value, s, r, n) : void 0;
1698
+ break;
1699
+ }
1700
+ o.type === "ExpressionStatement" ? c = this.evalExpr(o.expression, s, r, n) : this.evalNode(o, s ?? {}, r ?? [], n ?? [], [], []);
1701
+ }
1702
+ return this.scope = h, c;
1703
+ }
1704
+ // ─── Binary Operations ────────────────────────────────────
1705
+ evalBinary(t, e, s) {
1706
+ const r = Array.isArray(e), n = Array.isArray(s);
1707
+ if (r || n) {
1708
+ const l = r ? e.length : s.length;
1709
+ return Array.from({ length: l }, (h, c) => {
1710
+ const o = r ? e[c] : e, u = n ? s[c] : s;
1711
+ return this.scalarBinary(t, o, u);
1712
+ });
1713
+ }
1714
+ return this.scalarBinary(t, e, s);
1715
+ }
1716
+ scalarBinary(t, e, s) {
1717
+ switch (t) {
1718
+ case "+":
1719
+ return e + s;
1720
+ case "-":
1721
+ return e - s;
1722
+ case "*":
1723
+ return e * s;
1724
+ case "/":
1725
+ return s === 0 ? NaN : e / s;
1726
+ case "%":
1727
+ return e % s;
1728
+ case "**":
1729
+ return Math.pow(e, s);
1730
+ case "==":
1731
+ return e === s;
1732
+ case "!=":
1733
+ return e !== s;
1734
+ case "<":
1735
+ return e < s;
1736
+ case ">":
1737
+ return e > s;
1738
+ case "<=":
1739
+ return e <= s;
1740
+ case ">=":
1741
+ return e >= s;
1742
+ case "and":
1743
+ return e && s;
1744
+ case "or":
1745
+ return e || s;
1746
+ default:
1747
+ return NaN;
1748
+ }
1749
+ }
1750
+ // ─── Helpers ──────────────────────────────────────────────
1751
+ resolveColor(t) {
1752
+ return t && typeof t == "string" ? t.startsWith("#") ? t : d[t] ? d[t] : t : null;
1753
+ }
1754
+ buildMemberName(t) {
1755
+ return t.type === "Identifier" ? t.name : t.type === "MemberExpr" ? this.buildMemberName(t.object) + "." + t.property : "";
1756
+ }
1757
+ }
1758
+ /**
1759
+ * pine-to-kline — Figure Mapper
1760
+ * Maps Pine plot styles to KlineChart figure types
1761
+ * @license Apache-2.0
1762
+ */
1763
+ const Ft = {
1764
+ "plot.style_line": "line",
1765
+ "plot.style_linebr": "line",
1766
+ "plot.style_stepline": "line",
1767
+ "plot.style_area": "line",
1768
+ "plot.style_areabr": "line",
1769
+ "plot.style_columns": "bar",
1770
+ "plot.style_histogram": "bar",
1771
+ "plot.style_circles": "circle",
1772
+ "plot.style_cross": "circle"
1773
+ };
1774
+ function Tt(i) {
1775
+ return i ? Ft[i] ?? "line" : "line";
1776
+ }
1777
+ /**
1778
+ * pine-to-kline — Style Mapper
1779
+ * Converts Pine style values to KlineChart-compatible CSS
1780
+ * @license Apache-2.0
1781
+ */
1782
+ function k(i) {
1783
+ if (!i) return "#2196F3";
1784
+ if (typeof i == "string") {
1785
+ if (i.startsWith("#")) return i;
1786
+ if (d[i]) return d[i];
1787
+ }
1788
+ return "#2196F3";
1789
+ }
1790
+ function Bt(i) {
1791
+ switch (i) {
1792
+ case "hline.style_dashed":
1793
+ return [6, 3];
1794
+ case "hline.style_dotted":
1795
+ return [2, 2];
1796
+ case "hline.style_solid":
1797
+ default:
1798
+ return [];
1799
+ }
1800
+ }
1801
+ /**
1802
+ * pine-to-kline — KlineChart Adapter
1803
+ * Converts PineRuntime IR → KlineChart IndicatorTemplate
1804
+ * @license Apache-2.0
1805
+ */
1806
+ class Ut {
1807
+ toIndicatorTemplate(t) {
1808
+ const { meta: e, inputs: s, plots: r, hlines: n, calcFn: l } = t;
1809
+ return {
1810
+ name: e.name.toUpperCase().replace(/[^A-Z0-9_]/g, "_"),
1811
+ shortName: e.shortName ?? e.name,
1812
+ series: e.overlay ? "price" : "normal",
1813
+ calcParams: s.map((c) => c.defaultValue),
1814
+ figures: this.mapFigures(r),
1815
+ regenerateFigures: s.length > 0 ? (c) => this.mapFigures(r) : void 0,
1816
+ calc: (c, o) => {
1817
+ const u = o.calcParams ?? s.map((f) => f.defaultValue);
1818
+ return l(c, u);
1819
+ },
1820
+ // hline() → custom draw callback
1821
+ ...n.length > 0 && {
1822
+ draw: (c) => {
1823
+ const { ctx: o, bounding: u, indicator: f, yAxis: E } = c;
1824
+ if (!o || !E) return !1;
1825
+ for (const v of n) {
1826
+ const I = E.convertToPixel(v.price);
1827
+ if (I < u.top || I > u.top + u.height) continue;
1828
+ o.save(), o.strokeStyle = k(v.color), o.lineWidth = v.linewidth ?? 1;
1829
+ const b = Bt(v.linestyle);
1830
+ b.length && o.setLineDash(b), o.beginPath(), o.moveTo(u.left, I), o.lineTo(u.left + u.width, I), o.stroke(), v.title && (o.fillStyle = k(v.color), o.font = "10px sans-serif", o.textAlign = "right", o.fillText(v.title, u.left + u.width - 4, I - 4)), o.restore();
1831
+ }
1832
+ return !1;
1833
+ }
1834
+ },
1835
+ createTooltipDataSource: (c) => {
1836
+ const { indicator: o } = c, u = (o == null ? void 0 : o.result) ?? [], f = u[u.length - 1];
1837
+ return {
1838
+ name: e.name,
1839
+ calcParamsText: s.length > 0 ? `(${((o == null ? void 0 : o.calcParams) ?? []).join(", ")})` : "",
1840
+ values: r.map((E) => ({
1841
+ title: `${E.title ?? E.id}: `,
1842
+ value: (f == null ? void 0 : f[E.id]) ?? "--"
1843
+ }))
1844
+ };
1845
+ }
1846
+ };
1847
+ }
1848
+ mapFigures(t) {
1849
+ return t.map((e) => ({
1850
+ key: e.id,
1851
+ title: `${e.title ?? e.id}: `,
1852
+ type: Tt(e.style),
1853
+ styles: (s, r, n) => ({
1854
+ color: k(e.color)
1855
+ })
1856
+ }));
1857
+ }
1858
+ }
1859
+ /**
1860
+ * pine-to-kline — PineInterpreter
1861
+ * Main entry point class for the library
1862
+ * @license Apache-2.0
1863
+ */
1864
+ const Gt = {
1865
+ version: "v5",
1866
+ strict: !1,
1867
+ sandbox: !0,
1868
+ onWarning: console.warn,
1869
+ onError: console.error
1870
+ };
1871
+ class Vt {
1872
+ constructor(t = {}) {
1873
+ p(this, "options");
1874
+ this.options = { ...Gt, ...t };
1875
+ }
1876
+ /** Full compile: PineScript source → IndicatorConfig (IndicatorTemplate) */
1877
+ compile(t) {
1878
+ try {
1879
+ const e = new O(t).tokenize(), s = new _(e).parse(), r = new D(), n = [{ timestamp: 0, open: 0, high: 0, low: 0, close: 0 }], l = r.execute(s, n), h = {
1880
+ ...l,
1881
+ calcFn: (u, f) => new D().execute(s, u, f).calcFn(u, f)
1882
+ }, o = new Ut().toIndicatorTemplate(h);
1883
+ return {
1884
+ success: !0,
1885
+ indicatorConfig: o,
1886
+ name: o.name,
1887
+ warnings: l.warnings,
1888
+ errors: []
1889
+ };
1890
+ } catch (e) {
1891
+ return this.options.onError(e), {
1892
+ success: !1,
1893
+ indicatorConfig: {},
1894
+ name: "",
1895
+ warnings: [],
1896
+ errors: [e]
1897
+ };
1898
+ }
1899
+ }
1900
+ /** Validate syntax only (no execution) */
1901
+ validate(t) {
1902
+ try {
1903
+ const e = new O(t).tokenize();
1904
+ return new _(e).parse(), { valid: !0, errors: [] };
1905
+ } catch (e) {
1906
+ return { valid: !1, errors: [e] };
1907
+ }
1908
+ }
1909
+ /** Compile + register to KlineChart (global or instance) */
1910
+ register(t, e) {
1911
+ const s = this.compile(t);
1912
+ if (!s.success) throw s.errors[0];
1913
+ return e && e(s.indicatorConfig), s.name;
1914
+ }
1915
+ /** Execute directly with data (for testing/preview) */
1916
+ execute(t, e, s) {
1917
+ const r = this.compile(t);
1918
+ if (!r.success) throw r.errors[0];
1919
+ return r.indicatorConfig.calc(e, { calcParams: s ?? r.indicatorConfig.calcParams });
1920
+ }
1921
+ }
1922
+ /**
1923
+ * pine-to-kline — KlineChartPro Plugin
1924
+ * Plugin adapter for @simahfud/klinecharts-pro integration
1925
+ * @license Apache-2.0
1926
+ */
1927
+ function $t(i = {}) {
1928
+ const t = new Vt(i);
1929
+ return {
1930
+ run: (e) => {
1931
+ const s = t.compile(e);
1932
+ if (!s.success) throw s.errors[0];
1933
+ return s.name;
1934
+ },
1935
+ validate: (e) => t.validate(e),
1936
+ compile: (e) => t.compile(e)
1937
+ };
1938
+ }
1939
+ /**
1940
+ * pine-to-kline — Series Emulator
1941
+ * Emulates Pine's bar-by-bar series model using cursor-indexed arrays
1942
+ * @license Apache-2.0
1943
+ */
1944
+ class Kt {
1945
+ constructor(t) {
1946
+ p(this, "_data");
1947
+ p(this, "_cursor", 0);
1948
+ this._data = t;
1949
+ }
1950
+ setCursor(t) {
1951
+ this._cursor = t;
1952
+ }
1953
+ /** Access value with lookback: series[0] = current, series[1] = previous */
1954
+ get(t = 0) {
1955
+ const e = this._cursor - t;
1956
+ return e < 0 ? NaN : this._data[e];
1957
+ }
1958
+ /** Set value at current cursor */
1959
+ set(t) {
1960
+ this._data[this._cursor] = t;
1961
+ }
1962
+ get length() {
1963
+ return this._data.length;
1964
+ }
1965
+ get current() {
1966
+ return this.get(0);
1967
+ }
1968
+ get all() {
1969
+ return this._data;
1970
+ }
1971
+ /** Get the full underlying array */
1972
+ toArray() {
1973
+ return [...this._data];
1974
+ }
1975
+ }
1976
+ export {
1977
+ g as ALL_BUILTINS,
1978
+ R as ALL_CONSTANTS,
1979
+ jt as AdapterError,
1980
+ M as BarContext,
1981
+ Ut as KlineAdapter,
1982
+ O as Lexer,
1983
+ S as LexerError,
1984
+ C as ParseError,
1985
+ _ as Parser,
1986
+ x as PineError,
1987
+ Vt as PineInterpreter,
1988
+ D as PineRuntime,
1989
+ Ht as RuntimeError,
1990
+ Kt as SeriesEmulator,
1991
+ St as TA_REGISTRY,
1992
+ N as Token,
1993
+ a as TokenType,
1994
+ $t as createPinePlugin
1995
+ };
1996
+ //# sourceMappingURL=pine-to-kline.js.map