oakscriptjs 0.15.3 → 0.16.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.
Files changed (144) hide show
  1. package/dist/cjs/check/format.d.ts.map +1 -1
  2. package/dist/cjs/check/format.js +5 -0
  3. package/dist/cjs/check/format.js.map +2 -2
  4. package/dist/cjs/check/harness.d.ts +24 -0
  5. package/dist/cjs/check/harness.d.ts.map +1 -1
  6. package/dist/cjs/check/harness.js +33 -0
  7. package/dist/cjs/check/harness.js.map +2 -2
  8. package/dist/cjs/check/index.d.ts +9 -0
  9. package/dist/cjs/check/index.d.ts.map +1 -1
  10. package/dist/cjs/check/index.js +7 -0
  11. package/dist/cjs/check/index.js.map +2 -2
  12. package/dist/cjs/color/index.d.ts.map +1 -1
  13. package/dist/cjs/color/index.js +19 -2
  14. package/dist/cjs/color/index.js.map +2 -2
  15. package/dist/cjs/color/parse.d.ts +8 -6
  16. package/dist/cjs/color/parse.d.ts.map +1 -1
  17. package/dist/cjs/color/parse.js +15 -2
  18. package/dist/cjs/color/parse.js.map +2 -2
  19. package/dist/cjs/drawing/registry.d.ts +68 -0
  20. package/dist/cjs/drawing/registry.d.ts.map +1 -1
  21. package/dist/cjs/drawing/registry.js +99 -9
  22. package/dist/cjs/drawing/registry.js.map +2 -2
  23. package/dist/cjs/index.d.ts +3 -2
  24. package/dist/cjs/index.d.ts.map +1 -1
  25. package/dist/cjs/index.js +5 -1
  26. package/dist/cjs/index.js.map +2 -2
  27. package/dist/cjs/runtime/series.d.ts +16 -0
  28. package/dist/cjs/runtime/series.d.ts.map +1 -1
  29. package/dist/cjs/runtime/series.js +19 -2
  30. package/dist/cjs/runtime/series.js.map +2 -2
  31. package/dist/cjs/script/closure-writes.d.ts +16 -0
  32. package/dist/cjs/script/closure-writes.d.ts.map +1 -0
  33. package/dist/cjs/script/closure-writes.js +435 -0
  34. package/dist/cjs/script/closure-writes.js.map +7 -0
  35. package/dist/cjs/script/globals.d.ts +2 -0
  36. package/dist/cjs/script/globals.d.ts.map +1 -1
  37. package/dist/cjs/script/globals.js.map +1 -1
  38. package/dist/cjs/script/incremental.d.ts +140 -0
  39. package/dist/cjs/script/incremental.d.ts.map +1 -0
  40. package/dist/cjs/script/incremental.js +142 -0
  41. package/dist/cjs/script/incremental.js.map +7 -0
  42. package/dist/cjs/script/index.d.ts +116 -31
  43. package/dist/cjs/script/index.d.ts.map +1 -1
  44. package/dist/cjs/script/index.js +471 -25
  45. package/dist/cjs/script/index.js.map +3 -3
  46. package/dist/cjs/str/numberformat.d.ts.map +1 -1
  47. package/dist/cjs/str/numberformat.js +23 -0
  48. package/dist/cjs/str/numberformat.js.map +2 -2
  49. package/dist/cjs/strategy/index.d.ts +8 -0
  50. package/dist/cjs/strategy/index.d.ts.map +1 -1
  51. package/dist/cjs/strategy/index.js.map +1 -1
  52. package/dist/cjs/ta/running-sum.d.ts.map +1 -1
  53. package/dist/cjs/ta/running-sum.js +72 -3
  54. package/dist/cjs/ta/running-sum.js.map +2 -2
  55. package/dist/cjs/ta/step.d.ts +476 -0
  56. package/dist/cjs/ta/step.d.ts.map +1 -0
  57. package/dist/cjs/ta/step.js +1000 -0
  58. package/dist/cjs/ta/step.js.map +7 -0
  59. package/dist/cjs/ta-series.d.ts +1 -1
  60. package/dist/cjs/ta-series.js +3 -3
  61. package/dist/cjs/ta-series.js.map +1 -1
  62. package/dist/esm/check/format.d.ts.map +1 -1
  63. package/dist/esm/check/format.js +5 -0
  64. package/dist/esm/check/format.js.map +1 -1
  65. package/dist/esm/check/harness.d.ts +24 -0
  66. package/dist/esm/check/harness.d.ts.map +1 -1
  67. package/dist/esm/check/harness.js +40 -6
  68. package/dist/esm/check/harness.js.map +1 -1
  69. package/dist/esm/check/index.d.ts +9 -0
  70. package/dist/esm/check/index.d.ts.map +1 -1
  71. package/dist/esm/check/index.js +11 -1
  72. package/dist/esm/check/index.js.map +1 -1
  73. package/dist/esm/color/index.d.ts.map +1 -1
  74. package/dist/esm/color/index.js +23 -3
  75. package/dist/esm/color/index.js.map +1 -1
  76. package/dist/esm/color/parse.d.ts +8 -6
  77. package/dist/esm/color/parse.d.ts.map +1 -1
  78. package/dist/esm/color/parse.js +19 -2
  79. package/dist/esm/color/parse.js.map +1 -1
  80. package/dist/esm/drawing/registry.d.ts +68 -0
  81. package/dist/esm/drawing/registry.d.ts.map +1 -1
  82. package/dist/esm/drawing/registry.js +156 -10
  83. package/dist/esm/drawing/registry.js.map +1 -1
  84. package/dist/esm/index.d.ts +3 -2
  85. package/dist/esm/index.d.ts.map +1 -1
  86. package/dist/esm/index.js +6 -3
  87. package/dist/esm/index.js.map +1 -1
  88. package/dist/esm/runtime/series.d.ts +16 -0
  89. package/dist/esm/runtime/series.d.ts.map +1 -1
  90. package/dist/esm/runtime/series.js +21 -1
  91. package/dist/esm/runtime/series.js.map +1 -1
  92. package/dist/esm/script/closure-writes.d.ts +16 -0
  93. package/dist/esm/script/closure-writes.d.ts.map +1 -0
  94. package/dist/esm/script/closure-writes.js +323 -0
  95. package/dist/esm/script/closure-writes.js.map +1 -0
  96. package/dist/esm/script/globals.d.ts +2 -0
  97. package/dist/esm/script/globals.d.ts.map +1 -1
  98. package/dist/esm/script/globals.js.map +1 -1
  99. package/dist/esm/script/incremental.d.ts +140 -0
  100. package/dist/esm/script/incremental.d.ts.map +1 -0
  101. package/dist/esm/script/incremental.js +173 -0
  102. package/dist/esm/script/incremental.js.map +1 -0
  103. package/dist/esm/script/index.d.ts +116 -31
  104. package/dist/esm/script/index.d.ts.map +1 -1
  105. package/dist/esm/script/index.js +561 -24
  106. package/dist/esm/script/index.js.map +1 -1
  107. package/dist/esm/str/numberformat.d.ts.map +1 -1
  108. package/dist/esm/str/numberformat.js +30 -0
  109. package/dist/esm/str/numberformat.js.map +1 -1
  110. package/dist/esm/strategy/index.d.ts +8 -0
  111. package/dist/esm/strategy/index.d.ts.map +1 -1
  112. package/dist/esm/ta/running-sum.d.ts.map +1 -1
  113. package/dist/esm/ta/running-sum.js +79 -4
  114. package/dist/esm/ta/running-sum.js.map +1 -1
  115. package/dist/esm/ta/step.d.ts +476 -0
  116. package/dist/esm/ta/step.d.ts.map +1 -0
  117. package/dist/esm/ta/step.js +1089 -0
  118. package/dist/esm/ta/step.js.map +1 -0
  119. package/dist/esm/ta-series.d.ts +1 -1
  120. package/dist/esm/ta-series.js +4 -4
  121. package/package.json +1 -1
  122. package/skills/oakscript/SKILL.md +2 -2
  123. package/skills/oakscript/reference/check.md +5 -0
  124. package/skills/oakscript/reference/errors.md +0 -1
  125. package/skills/oakscript/reference/pine-differences.md +1 -2
  126. package/skills/oakscript/reference/plotting.md +5 -7
  127. package/skills/oakscript/reference/script-structure.md +6 -0
  128. package/src/check/format.ts +7 -0
  129. package/src/check/harness.ts +57 -0
  130. package/src/check/index.ts +16 -0
  131. package/src/color/index.ts +22 -3
  132. package/src/color/parse.ts +28 -3
  133. package/src/drawing/registry.ts +172 -10
  134. package/src/index.ts +9 -2
  135. package/src/runtime/series.ts +33 -1
  136. package/src/script/closure-writes.ts +279 -0
  137. package/src/script/globals.ts +2 -0
  138. package/src/script/incremental.ts +246 -0
  139. package/src/script/index.ts +695 -26
  140. package/src/str/numberformat.ts +29 -0
  141. package/src/strategy/index.ts +8 -0
  142. package/src/ta/running-sum.ts +78 -3
  143. package/src/ta/step.ts +1145 -0
  144. package/src/ta-series.ts +4 -4
@@ -48,6 +48,9 @@
48
48
  * The script API (`executeScript`) resets the registry at the start of every run and applies the
49
49
  * `max_*_count` values of `indicator()`. Outside a script run the registry is global to the module.
50
50
  *
51
+ * A port with its own bar loop resumes a live update with {@link saveDrawingCheckpoint} (at the end of the last
52
+ * confirmed bar) and {@link restoreDrawingCheckpoint} (before the forming bar is calculated again).
53
+ *
51
54
  * @module drawing/registry
52
55
  */
53
56
 
@@ -171,17 +174,44 @@ export class Stamped {
171
174
  }
172
175
  }
173
176
 
174
- /** The deleted objects. */
177
+ /** The deleted objects (an incremental run can bring one back when it puts the registry back, #196). */
175
178
  class Deleted extends Stamped {
176
179
  #deleted = true;
177
180
  static mark(obj: object): void {
178
- if (!Deleted.has(obj)) new Deleted(obj);
181
+ if (#deleted in obj) (obj as Deleted).#deleted = true;
182
+ else new Deleted(obj);
183
+ }
184
+ static unmark(obj: object): void {
185
+ if (#deleted in obj) (obj as Deleted).#deleted = false;
179
186
  }
180
187
  static has(obj: object): boolean {
181
- return #deleted in obj;
188
+ return #deleted in obj && (obj as Deleted).#deleted;
182
189
  }
183
190
  }
184
191
 
192
+ /** The objects the registry recorded (drawing objects, kept as references by the copies of an incremental run). */
193
+ const registered = new WeakSet<object>();
194
+
195
+ /** True for a drawing object of the registry (a line, a label, a box, a polyline, a linefill or a table). */
196
+ export function isDrawingObject(value: unknown): boolean {
197
+ return typeof value === 'object' && value !== null && registered.has(value);
198
+ }
199
+
200
+ /** Hooks of an incremental script run (#196, set by the script runtime during a run only). @internal */
201
+ export interface DrawingRunHooks {
202
+ /** A drawing function read or changed the registry or an object */
203
+ access(): void;
204
+ /** A creation: the object of the previous run to use instead of `obj` (its fields are set to those of `obj`) */
205
+ reuse(kind: DrawingKind, obj: object): object | null;
206
+ }
207
+
208
+ let runHooks: DrawingRunHooks | null = null;
209
+
210
+ /** @internal */
211
+ export function setDrawingRunHooks(hooks: DrawingRunHooks | null): void {
212
+ runHooks = hooks;
213
+ }
214
+
185
215
  /** The `var` records of a run: a reset starts new ones, a nested run saves and puts back those of its run. */
186
216
  interface Holds {
187
217
  /** The records of the objects whose private record belongs to another run */
@@ -189,6 +219,8 @@ interface Holds {
189
219
  /** Records made in the run. None: no object has one, nothing to look up for each object the maximum count may
190
220
  * delete */
191
221
  records: number;
222
+ /** The {@link varDrawing} variables made in the run: a checkpoint puts their objects back with the records */
223
+ readonly variables: Array<{ current: object | undefined }>;
192
224
  }
193
225
 
194
226
  /** What the `var` variables of a run did with an object. */
@@ -202,7 +234,7 @@ interface HoldRecord {
202
234
  /** Bar on which the last `var` variable released the object (linefill rule) */
203
235
  releasedAt: number | undefined;
204
236
  }
205
- let holds: Holds = { others: new WeakMap(), records: 0 };
237
+ let holds: Holds = { others: new WeakMap(), records: 0, variables: [] };
206
238
 
207
239
  /**
208
240
  * The record of the first run that holds an object, on the object itself (a study holding a new object on every bar
@@ -308,15 +340,17 @@ export interface DrawingVariable<T extends object> {
308
340
  * ```
309
341
  */
310
342
  export function varDrawing<T extends object>(initial?: T): DrawingVariable<T> {
311
- let current: T | undefined = initial ? holdDrawing(initial) : undefined;
343
+ const slot: { current: T | undefined } = { current: initial ? holdDrawing(initial) : undefined };
344
+ // kept by the run: a drawing checkpoint puts the variable back without holding or releasing again
345
+ holds.variables.push(slot);
312
346
  return {
313
347
  get value() {
314
- return current;
348
+ return slot.current;
315
349
  },
316
350
  set value(next: T | undefined) {
317
- if (next === current) return;
318
- releaseDrawing(current);
319
- current = next ? holdDrawing(next) : undefined;
351
+ if (next === slot.current) return;
352
+ releaseDrawing(slot.current);
353
+ slot.current = next ? holdDrawing(next) : undefined;
320
354
  },
321
355
  };
322
356
  }
@@ -499,6 +533,18 @@ export function createdDrawingKinds(): DrawingKind[] {
499
533
 
500
534
  /** Records a new object and deletes the oldest objects of its kind when the count is too high. */
501
535
  export function register<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): DrawingTypes[K] {
536
+ if (runHooks) {
537
+ runHooks.access();
538
+ const old = runHooks.reuse(kind, obj);
539
+ if (old && old !== obj) {
540
+ // the same object as in the previous run, with the fields of the new one
541
+ for (const key of Object.keys(old)) if (!(key in obj)) delete (old as Record<string, unknown>)[key];
542
+ Object.assign(old, obj);
543
+ Deleted.unmark(old);
544
+ obj = old as DrawingTypes[K];
545
+ }
546
+ }
547
+ registered.add(obj);
502
548
  const list = live[kind];
503
549
  created.add(kind);
504
550
  if (lastBar && isCounted(kind)) return registerLast(lastBar, kind, obj);
@@ -549,6 +595,7 @@ function registerLast<K extends DrawingKind>(bar: LastBar, kind: K, obj: Drawing
549
595
 
550
596
  /** Deletes an object (no effect when it is already deleted). */
551
597
  export function remove<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): void {
598
+ runHooks?.access();
552
599
  const list = live[kind];
553
600
  // from the end: an object is in the list once, and scripts mostly delete their newest objects
554
601
  const index = list.lastIndexOf(obj);
@@ -563,11 +610,14 @@ export function remove<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): vo
563
610
 
564
611
  /** True when the object was deleted (by `delete` or by the maximum count). */
565
612
  export function isDeleted(obj: unknown): boolean {
613
+ // the setters and getters of the drawing objects start here
614
+ runHooks?.access();
566
615
  return typeof obj === 'object' && obj !== null && Deleted.has(obj);
567
616
  }
568
617
 
569
618
  /** The live objects of a kind, in creation order (a new array). */
570
619
  export function all<K extends DrawingKind>(kind: K): Array<DrawingTypes[K]> {
620
+ runHooks?.access();
571
621
  return live[kind].toArray() as Array<DrawingTypes[K]>;
572
622
  }
573
623
 
@@ -576,7 +626,7 @@ export function resetDrawings(newLimits: DrawingLimits = {}): void {
576
626
  for (const kind of Object.keys(live) as DrawingKind[]) live[kind].replace([]);
577
627
  fillsOfLine = new Map();
578
628
  created.clear();
579
- holds = { others: new WeakMap(), records: 0 };
629
+ holds = { others: new WeakMap(), records: 0, variables: [] };
580
630
  pending = { line: 0, label: 0, box: 0, polyline: 0 };
581
631
  currentBar = null;
582
632
  lastBarIndex = null;
@@ -627,6 +677,118 @@ export function saveDrawingState(): DrawingState {
627
677
  };
628
678
  }
629
679
 
680
+ /**
681
+ * The registry and the state of its objects at the end of a bar (see {@link saveDrawingCheckpoint}): the live objects,
682
+ * the fields of each one (arrays, maps and plain objects copied; other drawing objects kept as references), their `var`
683
+ * records, the objects of the {@link varDrawing} variables, and the counters. Its fields are internal.
684
+ */
685
+ export interface DrawingCheckpoint {
686
+ state: DrawingState;
687
+ fields: Map<object, Record<string, unknown>>;
688
+ records: Map<object, { count: number; heldAt: number | undefined; releasedAt: number | undefined } | null>;
689
+ /** The object of each variable of the run, in the order they were made */
690
+ variables: Array<object | undefined>;
691
+ }
692
+
693
+ /** A copy of a field value of a drawing object: plain data copied, drawing objects (and other instances) shared. */
694
+ function copyField(v: unknown): unknown {
695
+ if (v === null || typeof v !== 'object' || registered.has(v)) return v;
696
+ if (Array.isArray(v)) return v.map(copyField);
697
+ if (v instanceof Map) return new Map([...v].map(([k, x]) => [k, copyField(x)]));
698
+ if (v instanceof Set) return new Set([...v].map(copyField));
699
+ const proto = Object.getPrototypeOf(v);
700
+ if (proto !== Object.prototype && proto !== null) return v;
701
+ const out: Record<string, unknown> = {};
702
+ for (const [k, x] of Object.entries(v)) out[k] = copyField(x);
703
+ return out;
704
+ }
705
+
706
+ function copyFields(obj: object): Record<string, unknown> {
707
+ const out: Record<string, unknown> = {};
708
+ for (const [k, v] of Object.entries(obj)) out[k] = copyField(v);
709
+ return out;
710
+ }
711
+
712
+ /**
713
+ * The drawings at the end of a bar, for a live update of a study with its own bar loop: save it at the end of the last
714
+ * confirmed bar, and put it back with {@link restoreDrawingCheckpoint} before the forming bar is calculated again. The
715
+ * drawings then are those of a full run on the same bars: the objects created, changed or deleted on the forming bar
716
+ * are undone, the objects keep their identity and creation order, and the maximum counts, the `var` holds (also of
717
+ * {@link varDrawing} variables), the linefills and the rules of the last bar ({@link setDrawingBar}) go on as in a full
718
+ * run. The incremental script runs use it too (#196, #203).
719
+ *
720
+ * The checkpoint holds the whole registry of the study: other studies on the same chart may reset and use the registry
721
+ * between two updates, putting it back makes it the study's again (call it where a full run calls
722
+ * {@link resetDrawings}). The study keeps its own variables (the objects it refers to, its arrays of objects) with the
723
+ * checkpoint and puts them back as plain values.
724
+ *
725
+ * @example
726
+ * ```typescript
727
+ * // full run: resetDrawings({ line: 500 }) ... for each bar i: setDrawingBar(i, i === n - 1); draw(i);
728
+ * // and after the bar n - 2: checkpoint = saveDrawingCheckpoint()
729
+ * // live update of the forming bar n - 1 (or new bars after it):
730
+ * restoreDrawingCheckpoint(checkpoint);
731
+ * for (let i = n - 1; i < bars.length; i++) {
732
+ * setDrawingBar(i, i === bars.length - 1);
733
+ * draw(i);
734
+ * if (i === bars.length - 2) checkpoint = saveDrawingCheckpoint();
735
+ * }
736
+ * setDrawingBar(null);
737
+ * ```
738
+ */
739
+ export function saveDrawingCheckpoint(): DrawingCheckpoint {
740
+ const state = saveDrawingState();
741
+ // the state of the last bar changes during the bar: a checkpoint taken on it keeps a copy
742
+ if (state.lastBar) state.lastBar = copyLastBar(state.lastBar);
743
+ const fields = new Map<object, Record<string, unknown>>();
744
+ const records: DrawingCheckpoint['records'] = new Map();
745
+ for (const kind of Object.keys(state.live) as DrawingKind[]) {
746
+ for (const obj of state.live[kind] as object[]) {
747
+ fields.set(obj, copyFields(obj));
748
+ const r = Held.get(obj);
749
+ records.set(obj, r ? { count: r.count, heldAt: r.heldAt, releasedAt: r.releasedAt } : null);
750
+ }
751
+ }
752
+ return { state, fields, records, variables: holds.variables.map((v) => v.current) };
753
+ }
754
+
755
+ function copyLastBar(bar: LastBar): LastBar {
756
+ return { ...bar, old: new Set(bar.old), allowance: { ...bar.allowance } };
757
+ }
758
+
759
+ /**
760
+ * Puts back a {@link saveDrawingCheckpoint}: the registry becomes the one of the checkpoint, the objects alive then get
761
+ * their fields and `var` records back, the variables their objects. It can be put back again later (on each update of
762
+ * the forming bar).
763
+ */
764
+ export function restoreDrawingCheckpoint(cp: DrawingCheckpoint): void {
765
+ restoreDrawingState(cp.state);
766
+ if (cp.state.lastBar) lastBar = copyLastBar(cp.state.lastBar);
767
+ for (const [obj, saved] of cp.fields) {
768
+ for (const key of Object.keys(obj)) if (!(key in saved)) delete (obj as Record<string, unknown>)[key];
769
+ Object.assign(obj, copyFields(saved));
770
+ Deleted.unmark(obj);
771
+ }
772
+ for (const [obj, saved] of cp.records) {
773
+ const r = Held.get(obj);
774
+ if (saved) {
775
+ const record = r ?? Held.create(obj);
776
+ record.count = saved.count;
777
+ record.heldAt = saved.heldAt;
778
+ record.releasedAt = saved.releasedAt;
779
+ } else if (r) {
780
+ r.count = 0;
781
+ r.heldAt = undefined;
782
+ r.releasedAt = undefined;
783
+ }
784
+ }
785
+ // the variables made after the checkpoint belong to the calculation being undone
786
+ holds.variables.length = cp.variables.length;
787
+ cp.variables.forEach((obj, k) => {
788
+ holds.variables[k]!.current = obj;
789
+ });
790
+ }
791
+
630
792
  /** Puts back the registry saved by {@link saveDrawingState} after the nested run. */
631
793
  export function restoreDrawingState(s: DrawingState): void {
632
794
  for (const kind of Object.keys(live) as DrawingKind[]) (live[kind] as LiveList<object>).replace(s.live[kind]);
package/src/index.ts CHANGED
@@ -39,11 +39,15 @@ import * as callsite from './callsite/index.js';
39
39
 
40
40
  export { taCore, math, array, map, str, color, time, timeframe, matrix, line, box, label, linefill, chartPoint, polyline, table, text, compare, callsite };
41
41
 
42
+ // ta.* one bar at a time (step / commit), for incremental calculations (#196)
43
+ export { taStep, type BarStep } from './ta/step.js';
44
+
42
45
  // Renderable drawings (IndicatorResult labels, lines, boxes, linefills, polylines, tables) and future bar times
43
46
  export { drawingOutputs, type DrawingOutputs } from './drawing/output.js';
44
47
  export { barInterval, barTime } from './drawing/bar-time.js';
45
48
 
46
- // Drawing registry limits (PineScript indicator(max_lines_count / max_labels_count / max_boxes_count / max_polylines_count))
49
+ // Drawing registry limits (PineScript indicator(max_lines_count / max_labels_count / max_boxes_count / max_polylines_count)),
50
+ // and the drawing checkpoint of a port with its own bar loop (live updates of the forming bar, #203)
47
51
  export {
48
52
  resetDrawings,
49
53
  setDrawingLimits,
@@ -52,6 +56,9 @@ export {
52
56
  releaseDrawing,
53
57
  varDrawing,
54
58
  createdDrawingKinds,
59
+ saveDrawingCheckpoint,
60
+ restoreDrawingCheckpoint,
61
+ type DrawingCheckpoint,
55
62
  type DrawingKind,
56
63
  type DrawingLimits,
57
64
  type DrawingVariable,
@@ -225,7 +232,7 @@ export type { LightweightSeriesDefinitions } from './runtime/adapters/Lightweigh
225
232
  export { SimpleInputAdapter } from './runtime/adapters/SimpleInputAdapter.js';
226
233
 
227
234
  // Version
228
- export const VERSION = '0.15.3';
235
+ export const VERSION = '0.16.0';
229
236
 
230
237
  /**
231
238
  * Library information
@@ -185,6 +185,25 @@ export function historyError(bar: number, barsBack: number): string {
185
185
  );
186
186
  }
187
187
 
188
+ /**
189
+ * Hooks of an incremental script run (#196, set by the script runtime during a run only): a Series created by the
190
+ * script gets a slot, and toArray() reuses the values of the previous run up to the first bar that changed.
191
+ * @internal
192
+ */
193
+ export interface SeriesRunHooks {
194
+ created(series: Series): void;
195
+ /** The values of the previous run (indexes below `from` are kept; the array is reused), or null to compute every bar */
196
+ prefix(series: Series, bars: readonly Bar[]): { values: number[]; from: number } | null;
197
+ computed(series: Series, values: number[]): void;
198
+ }
199
+
200
+ let runHooks: SeriesRunHooks | null = null;
201
+
202
+ /** @internal */
203
+ export function setSeriesRunHooks(hooks: SeriesRunHooks | null): void {
204
+ runHooks = hooks;
205
+ }
206
+
188
207
  export class Series {
189
208
  private extractor: SeriesExtractor;
190
209
  private dataSource: BarData;
@@ -207,6 +226,7 @@ export class Series {
207
226
  // Support both Bar[] and BarData for backward compatibility
208
227
  this.dataSource = data instanceof BarData ? data : new BarData(data);
209
228
  this.extractor = extractor;
229
+ runHooks?.created(this);
210
230
  }
211
231
 
212
232
  /**
@@ -568,8 +588,20 @@ export class Series {
568
588
 
569
589
  // Recompute and update cache
570
590
  const bars = this.dataSource.bars;
571
- this.cached = bars.map((bar, i) => this.extractor(bar, i, bars));
591
+ const prefix = runHooks?.prefix(this, bars) ?? null;
592
+ if (prefix) {
593
+ // the run's own array of the previous run: its first values are kept, the newest computed in place
594
+ const n = bars.length;
595
+ const values = prefix.values;
596
+ const from = Math.min(prefix.from, n);
597
+ values.length = n;
598
+ for (let i = from; i < n; i++) values[i] = this.extractor(bars[i]!, i, bars);
599
+ this.cached = values;
600
+ } else {
601
+ this.cached = bars.map((bar, i) => this.extractor(bar, i, bars));
602
+ }
572
603
  this.cachedVersion = this.dataSource.version;
604
+ runHooks?.computed(this, this.cached);
573
605
  return this.cached;
574
606
  }
575
607
 
@@ -0,0 +1,279 @@
1
+ /**
2
+ * The variables of the script that an eachBar() callback changes outside itself (#196): an incremental run cannot put
3
+ * them back to their value at the last confirmed bar, so a script with such a write is calculated in full.
4
+ *
5
+ * Read from the callback's source text (`fn.toString()`), with a tokenizer (strings, template literals, comments and
6
+ * regular expressions skipped). A write is an assignment (`x = `, `x += `, `x++`...) or a change of a member
7
+ * (`x.y = `, `x[i] = `, `x.push(...)` and the other mutating methods) whose root name is not declared inside the
8
+ * callback. The `.value` of a persist() box (`dir.value = 1`) is not a write. Conservative: a name declared anywhere
9
+ * inside the callback counts as its own (a shadowed outer write is missed); functions called by the callback are not
10
+ * read.
11
+ *
12
+ * @internal
13
+ */
14
+
15
+ const MUTATORS = new Set([
16
+ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin',
17
+ 'set', 'delete', 'clear', 'add',
18
+ ]);
19
+
20
+ const KEYWORDS = new Set([
21
+ 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'export',
22
+ 'extends', 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'let', 'new', 'return', 'super',
23
+ 'switch', 'this', 'throw', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', 'await', 'of', 'true', 'false',
24
+ 'null', 'undefined', 'async', 'static', 'get',
25
+ ]);
26
+
27
+ type Token = { kind: 'id' | 'punct' | 'num' | 'str'; text: string };
28
+
29
+ /** Tokens of a JavaScript source: names, numbers, punctuators; strings, template literals, comments and regexes skipped. */
30
+ function tokenize(src: string): Token[] {
31
+ const out: Token[] = [];
32
+ let i = 0;
33
+ const n = src.length;
34
+ const regexAllowed = (): boolean => {
35
+ const last = out[out.length - 1];
36
+ if (!last) return true;
37
+ if (last.kind === 'num' || last.kind === 'str') return false;
38
+ if (last.kind === 'id') return KEYWORDS.has(last.text) && !['this', 'super', 'true', 'false', 'null', 'undefined'].includes(last.text);
39
+ return ![')', ']', '}'].includes(last.text);
40
+ };
41
+ while (i < n) {
42
+ const ch = src[i]!;
43
+ if (/\s/.test(ch)) {
44
+ i++;
45
+ } else if (ch === '/' && src[i + 1] === '/') {
46
+ while (i < n && src[i] !== '\n') i++;
47
+ } else if (ch === '/' && src[i + 1] === '*') {
48
+ i = src.indexOf('*/', i + 2);
49
+ i = i < 0 ? n : i + 2;
50
+ } else if (ch === '"' || ch === "'") {
51
+ i++;
52
+ while (i < n && src[i] !== ch) i += src[i] === '\\' ? 2 : 1;
53
+ i++;
54
+ out.push({ kind: 'str', text: '' });
55
+ } else if (ch === '`') {
56
+ // a template literal: its ${...} parts are tokenized as code
57
+ i++;
58
+ let depth = 0;
59
+ const inner: string[] = [];
60
+ let part = '';
61
+ while (i < n) {
62
+ if (depth === 0 && src[i] === '\\') {
63
+ i += 2;
64
+ continue;
65
+ }
66
+ if (depth === 0 && src[i] === '`') break;
67
+ if (depth === 0 && src[i] === '$' && src[i + 1] === '{') {
68
+ depth = 1;
69
+ i += 2;
70
+ continue;
71
+ }
72
+ if (depth > 0) {
73
+ if (src[i] === '{') depth++;
74
+ if (src[i] === '}' && --depth === 0) {
75
+ inner.push(part);
76
+ part = '';
77
+ i++;
78
+ continue;
79
+ }
80
+ part += src[i];
81
+ }
82
+ i++;
83
+ }
84
+ i++;
85
+ out.push({ kind: 'str', text: '' });
86
+ for (const code of inner) {
87
+ out.push({ kind: 'punct', text: '(' });
88
+ out.push(...tokenize(code));
89
+ out.push({ kind: 'punct', text: ')' });
90
+ }
91
+ } else if (ch === '/' && regexAllowed()) {
92
+ i++;
93
+ let inClass = false;
94
+ while (i < n && (src[i] !== '/' || inClass)) {
95
+ if (src[i] === '\\') i++;
96
+ else if (src[i] === '[') inClass = true;
97
+ else if (src[i] === ']') inClass = false;
98
+ i++;
99
+ }
100
+ i++;
101
+ while (i < n && /[a-z]/i.test(src[i]!)) i++;
102
+ out.push({ kind: 'str', text: '' });
103
+ } else if (/[A-Za-z_$]/.test(ch)) {
104
+ let j = i + 1;
105
+ while (j < n && /[\w$]/.test(src[j]!)) j++;
106
+ out.push({ kind: 'id', text: src.slice(i, j) });
107
+ i = j;
108
+ } else if (/[0-9]/.test(ch) || (ch === '.' && /[0-9]/.test(src[i + 1] ?? ''))) {
109
+ let j = i + 1;
110
+ while (j < n && /[\w.]/.test(src[j]!)) j++;
111
+ out.push({ kind: 'num', text: src.slice(i, j) });
112
+ i = j;
113
+ } else {
114
+ const three = src.slice(i, i + 4);
115
+ const op = ['>>>=', '...', '===', '!==', '**=', '<<=', '>>=', '&&=', '||=', '??=', '>>>', '=>', '==', '!=', '<=', '>=',
116
+ '&&', '||', '??', '?.', '++', '--', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '**', '<<', '>>']
117
+ .find((o) => three.startsWith(o));
118
+ const text = op ?? ch;
119
+ out.push({ kind: 'punct', text });
120
+ i += text.length;
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+
126
+ const ASSIGN = new Set(['=', '+=', '-=', '*=', '/=', '%=', '**=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', '&&=', '||=', '??=']);
127
+
128
+ /** Names declared inside the tokens: let / const / var / function / class / catch, and parameters of functions. */
129
+ function declaredNames(t: Token[]): Set<string> {
130
+ const names = new Set<string>();
131
+ const addUntil = (start: number, stop: (tok: Token, depth: number) => boolean): void => {
132
+ let depth = 0;
133
+ for (let k = start; k < t.length; k++) {
134
+ const tok = t[k]!;
135
+ if (tok.kind === 'punct' && ['(', '[', '{'].includes(tok.text)) depth++;
136
+ if (tok.kind === 'punct' && [')', ']', '}'].includes(tok.text)) {
137
+ if (depth === 0) return;
138
+ depth--;
139
+ }
140
+ if (stop(tok, depth)) return;
141
+ // a default value or a computed key is not a name: skip to the next , at this depth
142
+ if (tok.kind === 'id' && !KEYWORDS.has(tok.text) && t[k - 1]?.text !== '.' && t[k + 1]?.text !== ':') names.add(tok.text);
143
+ }
144
+ };
145
+ for (let k = 0; k < t.length; k++) {
146
+ const tok = t[k]!;
147
+ if (tok.kind !== 'id') continue;
148
+ if (tok.text === 'let' || tok.text === 'const' || tok.text === 'var') {
149
+ // up to the end of the declaration: an = at depth 0 ends a name, a , starts the next one
150
+ let depth = 0;
151
+ let naming = true;
152
+ for (let j = k + 1; j < t.length; j++) {
153
+ const x = t[j]!;
154
+ if (x.kind === 'punct' && ['(', '[', '{'].includes(x.text)) depth++;
155
+ else if (x.kind === 'punct' && [')', ']', '}'].includes(x.text)) {
156
+ if (depth === 0) break;
157
+ depth--;
158
+ } else if (depth === 0 && x.text === ';') break;
159
+ else if (depth === 0 && x.text === '=') naming = false;
160
+ else if (depth === 0 && x.text === ',') naming = true;
161
+ else if (depth === 0 && (x.text === 'of' || x.text === 'in')) break;
162
+ if (naming && x.kind === 'id' && !KEYWORDS.has(x.text) && t[j + 1]?.text !== ':') names.add(x.text);
163
+ if (!naming && depth === 0 && x.kind === 'punct' && x.text === '=>' ) break;
164
+ }
165
+ } else if ((tok.text === 'function' || tok.text === 'class') && t[k + 1]?.kind === 'id') {
166
+ names.add(t[k + 1]!.text);
167
+ } else if (tok.text === 'catch' && t[k + 1]?.text === '(') {
168
+ addUntil(k + 2, () => false);
169
+ }
170
+ }
171
+ // parameters: ( ... ) => or function name ( ... ), and a single name before =>
172
+ for (let k = 0; k < t.length; k++) {
173
+ const tok = t[k]!;
174
+ if (tok.text === '=>' && t[k - 1]?.kind === 'id') names.add(t[k - 1]!.text);
175
+ if (tok.text === '=>' && t[k - 1]?.text === ')') {
176
+ let depth = 0;
177
+ let j = k - 1;
178
+ for (; j >= 0; j--) {
179
+ if (t[j]!.text === ')') depth++;
180
+ else if (t[j]!.text === '(' && --depth === 0) break;
181
+ }
182
+ addUntil(j + 1, () => false);
183
+ }
184
+ if (tok.text === 'function') {
185
+ let j = k + 1;
186
+ if (t[j]?.kind === 'id') j++;
187
+ if (t[j]?.text === '(') addUntil(j + 1, () => false);
188
+ }
189
+ }
190
+ return names;
191
+ }
192
+
193
+ /** The names outside the function source `src` that it assigns or changes (empty: none found). */
194
+ export function outerWrites(src: string): string[] {
195
+ const t = tokenize(src);
196
+ const inside = declaredNames(t);
197
+ const found = new Set<string>();
198
+ for (let k = 0; k < t.length; k++) {
199
+ const tok = t[k]!;
200
+ if (tok.kind !== 'id' || KEYWORDS.has(tok.text) || inside.has(tok.text)) continue;
201
+ const before = t[k - 1];
202
+ if (before && (before.text === '.' || before.text === '?.')) continue; // a member, not a root name
203
+ if (t[k + 1]?.text === ':' && (before?.text === '{' || before?.text === ',')) continue; // an object key
204
+ // the member chain after the name: .a.b / [x] / ?.a
205
+ let j = k + 1;
206
+ let members = 0;
207
+ let firstMember = '';
208
+ let lastMember = '';
209
+ const memberList: string[] = [];
210
+ while (j < t.length) {
211
+ if ((t[j]!.text === '.' || t[j]!.text === '?.') && t[j + 1]?.kind === 'id') {
212
+ lastMember = t[j + 1]!.text;
213
+ memberList.push(lastMember);
214
+ if (members === 0) firstMember = lastMember;
215
+ j += 2;
216
+ members++;
217
+ } else if (t[j]!.text === '[') {
218
+ if (members === 0) firstMember = '[]';
219
+ let depth = 0;
220
+ for (; j < t.length; j++) {
221
+ if (t[j]!.text === '[') depth++;
222
+ else if (t[j]!.text === ']' && --depth === 0) break;
223
+ }
224
+ j++;
225
+ members++;
226
+ lastMember = '[]';
227
+ memberList.push('[]');
228
+ } else break;
229
+ }
230
+ const next = t[j];
231
+ // a call of a PineScript namespace (label.delete(l), array.push(zones, x); also through a module object of compiled
232
+ // code, script_1.label.delete(l)): not a change of the namespace; array / map / matrix functions change their first
233
+ // argument
234
+ const ns = members === 1 ? tok.text : members >= 2 ? memberList[members - 2]! : '';
235
+ if (next?.text === '(' && PINE_NAMESPACES.has(ns) && (members === 1 || members >= 2)) {
236
+ if (NAMESPACES.has(ns) && !READS.has(lastMember)) {
237
+ const arg = t[j + 1];
238
+ if (arg?.kind === 'id' && !inside.has(arg.text) && !KEYWORDS.has(arg.text)) {
239
+ const box = t[j + 2]?.text === '.' && t[j + 3]?.text === 'value';
240
+ if (!box) found.add(arg.text);
241
+ }
242
+ }
243
+ continue;
244
+ }
245
+ // the content of a persist() box (dir.value = 1, zones.value.push(x)) is put back by the runtime
246
+ if (firstMember === 'value') continue;
247
+ const written =
248
+ (next && ASSIGN.has(next.text)) ||
249
+ (next && (next.text === '++' || next.text === '--')) ||
250
+ before?.text === '++' ||
251
+ before?.text === '--' ||
252
+ (members > 0 && MUTATORS.has(lastMember) && next?.text === '(');
253
+ if (written) found.add(tok.text);
254
+ }
255
+ return [...found];
256
+ }
257
+
258
+ /** Namespaces of the PineScript API (their functions do not change the namespace object) */
259
+ const PINE_NAMESPACES = new Set([
260
+ 'array', 'matrix', 'map', 'label', 'line', 'box', 'table', 'polyline', 'linefill', 'chart', 'str', 'math', 'ta', 'color',
261
+ 'request', 'strategy', 'input', 'timeframe', 'syminfo', 'barstate', 'session', 'callsite', 'taCore', 'taStep',
262
+ 'compare', 'plot', 'time', 'text', 'ticker', 'runtime', 'log', 'alert', 'chartPoint',
263
+ ]);
264
+
265
+ /** PineScript namespaces whose functions change their first argument */
266
+ const NAMESPACES = new Set(['array', 'matrix', 'map']);
267
+
268
+ /** Functions of those namespaces that only read their first argument */
269
+ const READS = new Set([
270
+ 'get', 'size', 'includes', 'indexof', 'lastindexof', 'sum', 'avg', 'max', 'min', 'median', 'mode', 'stdev',
271
+ 'variance', 'range', 'first', 'last', 'slice', 'copy', 'join', 'every', 'some', 'abs', 'binary_search',
272
+ 'binary_search_leftmost', 'binary_search_rightmost', 'covariance', 'percentile_linear_interpolation',
273
+ 'percentile_nearest_rank', 'percentrank', 'standardize', 'sort_indices', 'from', 'new', 'new_float', 'new_int',
274
+ 'new_bool', 'new_string', 'new_color', 'new_line', 'new_label', 'new_box', 'new_table', 'new_linefill',
275
+ 'contains', 'keys', 'values', 'rows', 'columns', 'elements_count', 'row', 'col', 'det', 'inv', 'pinv', 'rank',
276
+ 'trace', 'transpose', 'mult', 'diff', 'pow', 'eigenvalues', 'eigenvectors', 'kron', 'is_square', 'is_zero',
277
+ 'is_binary', 'is_symmetric', 'is_antisymmetric', 'is_diagonal', 'is_antidiagonal', 'is_identity', 'is_triangular',
278
+ 'is_stochastic',
279
+ ]);
@@ -29,7 +29,9 @@ import type * as S from './index.js';
29
29
 
30
30
  declare global {
31
31
  const executeIntrabar: typeof S.executeIntrabar;
32
+ const createScriptRun: typeof S.createScriptRun;
32
33
  const varip: typeof S.varip;
34
+ const persist: typeof S.persist;
33
35
  const indicator: typeof S.indicator;
34
36
  const fixnan: typeof S.fixnan;
35
37
  const fill: typeof S.fill;