barefoot_js 0.40.2 → 0.41.1

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.
data/lib/barefoot_js.rb CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'set'
4
4
  require 'time'
5
+ require 'barefoot_js/undefined'
5
6
  require 'barefoot_js/evaluator'
6
7
  require 'barefoot_js/search_params'
7
8
 
@@ -24,7 +25,10 @@ require 'barefoot_js/search_params'
24
25
  # directly than Perl's blurred numeric-string scalars, so this port needs
25
26
  # none of the `JSON::PP::Boolean` sentinel-detection machinery the Perl
26
27
  # runtime carries -- a Ruby `true`/`false` IS a boolean, distinguishable
27
- # from `0`/`1` for free.
28
+ # from `0`/`1` for free. Host `nil` is JS `null`; JS `undefined` is
29
+ # `BarefootJS::UNDEF` (barefoot_js/undefined.rb), so a props Hash has JS's
30
+ # four states: a key left out (absent), `UNDEF` (present `undefined`), `nil`
31
+ # (`null`) and a value.
28
32
  module BarefootJS
29
33
  # Marker wrapper for a string that is ALREADY finished HTML and must not
30
34
  # be re-escaped by `Context#h` -- e.g. a named-slot / children capture
@@ -43,6 +47,13 @@ module BarefootJS
43
47
  # `register_components_from_manifest` construct a fresh child instance
44
48
  # per nested render, chaining scope/slot identity off the caller.
45
49
  class Context
50
+ # The default of a helper's optional argument: the call passed none. JS
51
+ # reads an omitted argument as `undefined`, so `omitted?` accepts `UNDEF`
52
+ # too; an explicit `nil` is JS `null`, which each helper coerces like any
53
+ # other value.
54
+ OMITTED = Object.new.freeze
55
+ private_constant :OMITTED
56
+
46
57
  # ---------------------------------------------------------------------
47
58
  # Minimal get/set accessors (Perl-style: no-arg reads, one-arg writes,
48
59
  # matching BarefootJS.pm's hand-rolled accessor base so the exact same
@@ -116,7 +127,7 @@ module BarefootJS
116
127
  # BarefootJS.pm's docstring on the client reconciliation contract.
117
128
  def data_key_attr
118
129
  k = _data_key
119
- return '' if k.nil?
130
+ return '' if BarefootJS.nullish?(k)
120
131
 
121
132
  escaped = k.to_s.gsub('&', '&').gsub('"', '"')
122
133
  %( data-key="#{escaped}")
@@ -142,7 +153,7 @@ module BarefootJS
142
153
  # (e.g. a blog paragraph) terminates the single-quoted attribute and
143
154
  # truncates the hydration payload. The browser entity-decodes the
144
155
  # attribute value, so the client's JSON.parse sees the original text.
145
- json = html_escape(backend.encode_json(client_props))
156
+ json = html_escape(backend.encode_json(json_ready(client_props)))
146
157
  %( bf-p='#{json}')
147
158
  end
148
159
 
@@ -172,7 +183,7 @@ module BarefootJS
172
183
  ''
173
184
  end
174
185
 
175
- def use_context(name, default = nil)
186
+ def use_context(name, default = UNDEF)
176
187
  stack = CONTEXT_STACKS[name]
177
188
  stack.empty? ? default : stack.last
178
189
  end
@@ -206,7 +217,7 @@ module BarefootJS
206
217
  # callers must have already classified the expression as boolean-
207
218
  # result; non-boolean attribute bindings never reach this helper.
208
219
  def bool_str(value)
209
- value ? 'true' : 'false'
220
+ value && !BarefootJS.undefined?(value) ? 'true' : 'false'
210
221
  end
211
222
 
212
223
  # A JSX text child's value: JSX renders nothing for a boolean (#3824
@@ -231,7 +242,7 @@ module BarefootJS
231
242
  mount = _bf_mount
232
243
  host_segment = "|h=#{host}|m=#{mount || ''}" if host && !host.empty?
233
244
  props_json = ''
234
- props_json = "|#{backend.encode_json(_props)}" if _props && !_props.empty?
245
+ props_json = "|#{backend.encode_json(json_ready(_props))}" if _props && !_props.empty?
235
246
  "<!--bf-scope:#{scope_id}#{host_segment}#{props_json}-->"
236
247
  end
237
248
 
@@ -350,14 +361,14 @@ module BarefootJS
350
361
  end
351
362
  end
352
363
 
353
- # Whether this component's caller passed the prop `name`, even as `nil`:
354
- # JS's `name in props`, which a template can't ask of its vars (every
355
- # declared prop is seeded, so an omitted one and a `nil` one read the
356
- # same). A `{...props}` spread onto a child carries a param only when
357
- # this is true. The keys are those `render_child` recorded for a child
358
- # and `_props` for the root; with neither recorded (a root rendered
359
- # without `_props`), `fallback`, the template's own "not nil" test,
360
- # decides.
364
+ # Whether this component's caller passed the prop `name`, even as `nil`
365
+ # (`null`) or `UNDEF`: JS's `name in props`, which a template can't ask of
366
+ # its vars (every declared prop is seeded, so an omitted one reads as its
367
+ # default or `UNDEF`, as a present `undefined` one does). A `{...props}`
368
+ # spread onto a child carries a param only when this is true. The keys
369
+ # are those `render_child` recorded for a child and `_props` for the
370
+ # root; with neither recorded (a root rendered without `_props`),
371
+ # `fallback`, the template's own "not undefined" test, decides.
361
372
  def passed?(name, fallback)
362
373
  stack = Thread.current[:barefoot_js_caller_keys]
363
374
  keys = stack && !stack.empty? ? stack.last : _props&.keys&.map(&:to_s)
@@ -400,7 +411,7 @@ module BarefootJS
400
411
  child_bf = self.class.new(parent.backend)
401
412
  slot_id = props.delete(:_bf_slot)
402
413
  data_key = props.delete(:key)
403
- child_bf._data_key(data_key) unless data_key.nil?
414
+ child_bf._data_key(data_key) unless BarefootJS.nullish?(data_key)
404
415
  child_bf._scope_id(
405
416
  slot_id ? "#{host_scope}_#{slot_id}" : "#{template_name}_#{rand.to_s[2, 6]}",
406
417
  )
@@ -444,9 +455,12 @@ module BarefootJS
444
455
  # Each entry shape: `{ value:, propName:, isRestProps: }`. For
445
456
  # `isRestProps`, the rest bag passes through unchanged (or the static
446
457
  # `{}` if the caller didn't supply one). For ordinary entries the
447
- # caller's `props[propName]` wins when present, otherwise the static
448
- # `value` does. `propName`-less entries (signal / memo locals) always
449
- # use the static value.
458
+ # caller's `props[propName]` wins when present -- `nil` (JS `null`)
459
+ # included -- and an absent or `UNDEF` prop takes the static `value`, or
460
+ # `UNDEF` when the entry has none (the manifest writes `value` only for a
461
+ # prop with a default; spec/js-undefined-value.md, decision 6).
462
+ # `propName`-less entries (signal / memo locals) always use the static
463
+ # value.
450
464
  #
451
465
  # Public (not `private_class_method`): `register_components_from_manifest`
452
466
  # above uses it for the `ui/*` registry path, but a page that composes
@@ -462,11 +476,11 @@ module BarefootJS
462
476
  extra = {}
463
477
  defaults.each do |name, d|
464
478
  unless d.is_a?(Hash)
465
- extra[name] = d
479
+ extra[name] = BarefootJS.decode_undefined(d)
466
480
  next
467
481
  end
468
482
  if d[:isRestProps]
469
- extra[name] = props.key?(name) ? props[name] : d[:value]
483
+ extra[name] = props.key?(name) ? props[name] : static_fallback(d)
470
484
  next
471
485
  end
472
486
  # `propName` rides in from the JSON manifest as a String -- JSON has
@@ -479,15 +493,23 @@ module BarefootJS
479
493
  # rendering empty) (#2157).
480
494
  prop_name = d[:propName]&.to_sym
481
495
  extra[name] =
482
- if !prop_name.nil? && props.key?(prop_name) && !props[prop_name].nil?
496
+ if !prop_name.nil? && props.key?(prop_name) && !BarefootJS.undefined?(props[prop_name])
483
497
  props[prop_name]
484
498
  else
485
- d[:value]
499
+ static_fallback(d)
486
500
  end
487
501
  end
488
502
  extra
489
503
  end
490
504
 
505
+ # An `ssrDefaults` entry's seed when the caller's prop is absent or
506
+ # `UNDEF`: its `value` (a `{"$undef": true}` sentinel in it is `UNDEF`),
507
+ # or `UNDEF` when it has none.
508
+ def self.static_fallback(entry)
509
+ entry.key?(:value) ? BarefootJS.decode_undefined(entry[:value]) : UNDEF
510
+ end
511
+ private_class_method :static_fallback
512
+
491
513
  # -----------------------------------------------------------------
492
514
  # Streaming SSR (Out-of-Order)
493
515
  # -----------------------------------------------------------------
@@ -521,27 +543,54 @@ module BarefootJS
521
543
  # are `null`, at any depth (#3787). Ruby's encoder would write `-2.0` /
522
544
  # `-4.0e-08` and raise on a non-finite Float. Arrays and Hashes are
523
545
  # walked here in insertion order, as `JSON.generate` does; strings and
524
- # other leaves go through the backend's encoder.
546
+ # other leaves go through the backend's encoder. `undefined` follows
547
+ # `JSON.stringify` too: a member holding it is skipped, an element is
548
+ # written as `null`, and at the top level the result is `UNDEF` itself
549
+ # (no string), which prints nothing and omits an attribute.
525
550
  def json(value)
526
551
  case value
552
+ when Undefined then value
527
553
  when Integer, Float
528
554
  value.to_f.finite? ? Evaluator.number_to_string(value) : 'null'
529
- when Array then "[#{value.map { |el| json(el) }.join(',')}]"
555
+ when Array then "[#{value.map { |el| BarefootJS.undefined?(el) ? 'null' : json(el) }.join(',')}]"
530
556
  when Hash
531
- members = value.map { |k, v| "#{backend.encode_json(k.to_s)}:#{json(v)}" }
557
+ members = value.reject { |_, v| BarefootJS.undefined?(v) }.map { |k, v| "#{backend.encode_json(k.to_s)}:#{json(v)}" }
532
558
  "{#{members.join(',')}}"
533
559
  else backend.encode_json(value)
534
560
  end
535
561
  end
536
562
 
563
+ # JS `undefined` as a template spells it (`bf.undefined`): the
564
+ # `undefined` identifier, an omitted method argument's default, the
565
+ # result of a `?.` over a nullish receiver.
566
+ def undefined
567
+ UNDEF
568
+ end
569
+
570
+ # The nil tests (spec/js-undefined-value.md, decisions 3 and 7): JS
571
+ # `x === undefined`, `x === null` and the loose `x == null`. A template
572
+ # spells a nil-test plan through them.
573
+ def is_undefined(value)
574
+ BarefootJS.undefined?(value)
575
+ end
576
+
577
+ def is_null(value)
578
+ BarefootJS.null?(value)
579
+ end
580
+
581
+ def is_nullish(value)
582
+ BarefootJS.nullish?(value)
583
+ end
584
+
537
585
  # JS `String(v)` mirror, EXCEPT `nil` renders as '' (not the literal
538
586
  # "null") so an unset prop doesn't surface as literal text in
539
587
  # user-facing HTML -- the same divergence the Go/Perl adapters document
540
- # for their `string` helper. This is the canonical JS-ish stringifier
541
- # used throughout this file (join, spread_attrs, `h`, reduce's string
542
- # fold, ...).
588
+ # for their `string` helper; `undefined` renders as '' too, as a JSX
589
+ # text child does. This is the canonical display stringifier used
590
+ # throughout this file (join, spread_attrs, `h`, reduce's string fold,
591
+ # ...); JS ToString itself is `to_string`.
543
592
  def string(value)
544
- return '' if value.nil?
593
+ return '' if BarefootJS.nullish?(value)
545
594
  return value ? 'true' : 'false' if value.is_a?(TrueClass) || value.is_a?(FalseClass)
546
595
  return Evaluator.number_to_string(value) if value.is_a?(Numeric)
547
596
  # JS `Array.prototype.toString` is `this.join(',')`, applied
@@ -554,6 +603,23 @@ module BarefootJS
554
603
  value.to_s
555
604
  end
556
605
 
606
+ # JS `l - r` / `l * r` over operands the compiler could not prove numbers:
607
+ # ToNumber of both (`undefined` is NaN, `null` 0).
608
+ def sub(left, right)
609
+ Evaluator.binary('-', left, right)
610
+ end
611
+
612
+ def mul(left, right)
613
+ Evaluator.binary('*', left, right)
614
+ end
615
+
616
+ # JS `o?.k`: `undefined` over a nullish receiver, the read of `k`
617
+ # (`get`) otherwise. Ruby's `nil&.[](:k)` gives `nil`, JS's `null?.k`
618
+ # `undefined`; and `&.` calls through on `UNDEF`.
619
+ def get_opt(collection, key)
620
+ BarefootJS.nullish?(collection) ? UNDEF : get(collection, key)
621
+ end
622
+
557
623
  # HTML-escaping helper for text interpolation (`<%= bf.h(expr) %>` --
558
624
  # stdlib ERB does not auto-escape). JS-style stringification via
559
625
  # `string` (numbers per JS Number#toString, nil -> "", booleans ->
@@ -608,12 +674,22 @@ module BarefootJS
608
674
  Evaluator.truthy?(value) ? nil : [value]
609
675
  end
610
676
 
677
+ # The box for a value-position JS `l ?? r` (#3839): the adapter spells it
678
+ # as `(bf.keep_nonnil(l) || [r])[0]`, so each operand appears once and a
679
+ # chain grows linearly (`l.nil? ? r : l` rendered `l` twice). Only the
680
+ # two nils (`null`, `undefined`) are absent; `0`, `''` and `false` are
681
+ # kept, as in JS.
682
+ def keep_nonnil(value)
683
+ BarefootJS.nullish?(value) ? nil : [value]
684
+ end
685
+
611
686
  # JS primitive helpers (spec/js-primitive-semantics.md, "Operation
612
687
  # table"): ToNumber, ToString, `===`, the relational operators, binary
613
688
  # `+` and unary `-`. Each delegates to the shared evaluator's primitive
614
689
  # of the same operation, so a template helper call and a callback body
615
690
  # share one implementation. Unlike `number` and `string` (display
616
- # helpers: nil -> NaN / ""), nil reads as JS null here (0 / "null").
691
+ # helpers: nil -> NaN / ""), nil reads as JS null here (0 / "null") and
692
+ # `UNDEF` as JS undefined (NaN / "undefined").
617
693
  def to_number(value)
618
694
  Evaluator.to_number(value)
619
695
  end
@@ -661,7 +737,7 @@ module BarefootJS
661
737
  # non-numeric / nil yield real numeric NaN so downstream arithmetic
662
738
  # propagates correctly (`Math.floor(NaN) === NaN`).
663
739
  def number(value)
664
- return Float::NAN if value.nil?
740
+ return Float::NAN if BarefootJS.nullish?(value)
665
741
  return value ? 1 : 0 if value.is_a?(TrueClass) || value.is_a?(FalseClass)
666
742
  return value if value.is_a?(Numeric)
667
743
  return Float(value.strip) if value.is_a?(String) && value.strip =~ NUMERIC_STRING_RE
@@ -669,18 +745,20 @@ module BarefootJS
669
745
  Float::NAN
670
746
  end
671
747
 
748
+ # The `Math` helpers coerce through JS ToNumber (`null` is 0, `undefined`
749
+ # NaN), as `Math.floor(null)` is 0.
672
750
  def floor(value)
673
- n = number(value)
751
+ n = js_number(value)
674
752
  finite_number?(n) ? n.floor : n
675
753
  end
676
754
 
677
755
  def ceil(value)
678
- n = number(value)
756
+ n = js_number(value)
679
757
  finite_number?(n) ? n.ceil : n
680
758
  end
681
759
 
682
760
  def round(value)
683
- n = number(value)
761
+ n = js_number(value)
684
762
  finite_number?(n) ? (n + 0.5).floor : n
685
763
  end
686
764
 
@@ -689,8 +767,8 @@ module BarefootJS
689
767
  # may return a plain Integer (no `#nan?`), so guard like
690
768
  # `finite_number?` above rather than calling `#nan?` unconditionally.
691
769
  def min(a, b)
692
- x = number(a)
693
- y = number(b)
770
+ x = js_number(a)
771
+ y = js_number(b)
694
772
  return x if nan_number?(x)
695
773
  return y if nan_number?(y)
696
774
 
@@ -698,8 +776,8 @@ module BarefootJS
698
776
  end
699
777
 
700
778
  def max(a, b)
701
- x = number(a)
702
- y = number(b)
779
+ x = js_number(a)
780
+ y = js_number(b)
703
781
  return x if nan_number?(x)
704
782
  return y if nan_number?(y)
705
783
 
@@ -708,7 +786,7 @@ module BarefootJS
708
786
 
709
787
  # `Math.abs()` (#2168 math-methods).
710
788
  def abs(value)
711
- n = number(value)
789
+ n = js_number(value)
712
790
  nan_number?(n) ? n : n.abs
713
791
  end
714
792
 
@@ -907,9 +985,8 @@ module BarefootJS
907
985
  return recv.any? { |item| Evaluator.same_value_zero?(item, elem) } if recv.is_a?(Array)
908
986
  return false if recv.is_a?(Hash)
909
987
 
910
- s = recv.nil? ? '' : string(recv)
911
- needle = elem.nil? ? '' : string(elem)
912
- s.include?(needle)
988
+ # The needle is JS ToString'd (`"anullb".includes(null)` is true).
989
+ string(recv).include?(js_string(elem))
913
990
  end
914
991
 
915
992
  # `.filter(fn)` / `.every(fn)` / `.some(fn)` / `.find(fn)` /
@@ -936,10 +1013,12 @@ module BarefootJS
936
1013
  recv.any? { |item| pred.call(item) }
937
1014
  end
938
1015
 
1016
+ # A miss is `undefined`, as JS `.find()` gives.
939
1017
  def find(recv, pred)
940
- return nil unless recv.is_a?(Array)
1018
+ return UNDEF unless recv.is_a?(Array)
941
1019
 
942
- recv.find { |item| pred.call(item) }
1020
+ recv.each { |item| return item if pred.call(item) }
1021
+ UNDEF
943
1022
  end
944
1023
 
945
1024
  def find_index(recv, pred)
@@ -950,10 +1029,10 @@ module BarefootJS
950
1029
  end
951
1030
 
952
1031
  def find_last(recv, pred)
953
- return nil unless recv.is_a?(Array)
1032
+ return UNDEF unless recv.is_a?(Array)
954
1033
 
955
1034
  recv.reverse_each { |item| return item if pred.call(item) }
956
- nil
1035
+ UNDEF
957
1036
  end
958
1037
 
959
1038
  def find_last_index(recv, pred)
@@ -965,20 +1044,21 @@ module BarefootJS
965
1044
 
966
1045
  # `String.prototype.toLowerCase()` / `.toUpperCase()`.
967
1046
  def lc(s)
968
- s.nil? ? '' : string(s).downcase
1047
+ string(s).downcase
969
1048
  end
970
1049
 
971
1050
  def uc(s)
972
- s.nil? ? '' : string(s).upcase
1051
+ string(s).upcase
973
1052
  end
974
1053
 
975
- # `Array.prototype.join(sep)` with JS semantics: separator defaults to
976
- # ",", undefined/null elements render as empty.
977
- def join(recv, sep = nil)
1054
+ # `Array.prototype.join(sep)` with JS semantics: an omitted or
1055
+ # `undefined` separator is ",", any other one is ToString'd (`null` joins
1056
+ # with "null"); undefined/null elements render as empty.
1057
+ def join(recv, sep = OMITTED)
978
1058
  return '' unless recv.is_a?(Array)
979
1059
 
980
- sep = ',' if sep.nil?
981
- recv.map { |el| string(el) }.join(sep)
1060
+ sep_s = omitted?(sep) ? ',' : js_string(sep)
1061
+ recv.map { |el| string(el) }.join(sep_s)
982
1062
  end
983
1063
 
984
1064
  # `.length` works on both arrays (element count) and strings. The
@@ -988,11 +1068,11 @@ module BarefootJS
988
1068
  # Plane (astral, U+10000-U+10FFFF -- e.g. '👍') is a surrogate PAIR in
989
1069
  # UTF-16, so it counts as 2, not 1; '日本語' is 3 either way (BMP-only).
990
1070
  # An object's `.length` is its own `length` property (`{ length: 3 }`),
991
- # nil when it has none (#3449).
1071
+ # `undefined` when it has none (#3449).
992
1072
  def length(recv)
993
1073
  return recv.length if recv.is_a?(Array)
994
- return recv.key?(:length) ? recv[:length] : recv['length'] if recv.is_a?(Hash)
995
- return 0 if recv.nil?
1074
+ return Evaluator.index_value(recv, :length) if recv.is_a?(Hash)
1075
+ return 0 if BarefootJS.nullish?(recv)
996
1076
 
997
1077
  string(recv).each_char.sum { |c| c.ord > 0xFFFF ? 2 : 1 }
998
1078
  end
@@ -1119,25 +1199,19 @@ module BarefootJS
1119
1199
  array_index_of(recv, elem, true)
1120
1200
  end
1121
1201
 
1122
- # `Array.prototype.at(i)` -- negative indices count from the end;
1123
- # out-of-bounds -> nil (renders as '' via `h`, matching JS `undefined`).
1124
- # A String receiver is indexed in UTF-16 code units (#3613). Half of a
1125
- # surrogate pair, a lone surrogate in JS, comes back as U+FFFD: a
1126
- # UTF-8 Ruby String can't hold one, so the halves compare equal and
1127
- # don't rejoin (limitation `string-at-lone-surrogate`).
1128
- def at(recv, i)
1202
+ # `Array.prototype.at(i)` -- negative indices count from the end; the
1203
+ # index is ToIntegerOrInfinity'd, so an omitted, `undefined` or `null`
1204
+ # one reads element 0; out-of-bounds -> `undefined`. A String receiver
1205
+ # is indexed in UTF-16 code units (#3613). Half of a surrogate pair, a
1206
+ # lone surrogate in JS, comes back as U+FFFD: a UTF-8 Ruby String can't
1207
+ # hold one, so the halves compare equal and don't rejoin (limitation
1208
+ # `string-at-lone-surrogate`).
1209
+ def at(recv, i = OMITTED)
1129
1210
  return utf16_at(recv, i) if recv.is_a?(String)
1130
- return nil unless recv.is_a?(Array)
1131
- return nil if i.nil?
1132
-
1133
- idx = i.to_i
1134
- len = recv.length
1135
- return nil if len.zero?
1136
-
1137
- idx = len + idx if idx.negative?
1138
- return nil if idx.negative? || idx >= len
1211
+ return UNDEF unless recv.is_a?(Array)
1139
1212
 
1140
- recv[idx]
1213
+ idx = relative_index(i, recv.length)
1214
+ idx.nil? ? UNDEF : recv[idx]
1141
1215
  end
1142
1216
 
1143
1217
  # `Array.prototype.concat(other)` -- merges two arrays in order into a
@@ -1159,22 +1233,17 @@ module BarefootJS
1159
1233
  # a UTF-8-encoded string, matching JS except for astral-plane input
1160
1234
  # (the same divergence boundary every other adapter's pad/trim
1161
1235
  # helpers already accept).
1162
- def slice(recv, start, end_ = nil)
1236
+ # Both bounds are ToIntegerOrInfinity'd (`null` is 0); an omitted or
1237
+ # `undefined` end is the length.
1238
+ def slice(recv, start = OMITTED, end_ = OMITTED)
1163
1239
  return [] unless recv.is_a?(Array) || recv.is_a?(String)
1164
1240
 
1165
1241
  empty = recv.is_a?(String) ? '' : []
1166
1242
  len = recv.length
1167
1243
  return empty if len.zero?
1168
1244
 
1169
- s = start.nil? ? 0 : start.to_i
1170
- s = len + s if s.negative?
1171
- s = 0 if s.negative?
1172
- s = len if s > len
1173
-
1174
- e = end_.nil? ? len : end_.to_i
1175
- e = len + e if e.negative?
1176
- e = 0 if e.negative?
1177
- e = len if e > len
1245
+ s = clamp_relative(to_integer_or_infinity(start), len)
1246
+ e = omitted?(end_) ? len : clamp_relative(to_integer_or_infinity(end_), len)
1178
1247
 
1179
1248
  return empty if s >= e
1180
1249
 
@@ -1224,6 +1293,9 @@ module BarefootJS
1224
1293
  # value to `0` -- and only then delegates to `flat`'s recursion. Mirrors
1225
1294
  # Go's `FlatDynamicDepth`/`coerceFlatDepth` (adapter-go-template/runtime/bf.go).
1226
1295
  def flat_dynamic(recv, depth)
1296
+ # An `undefined` depth is the default, 1; `null` coerces to 0.
1297
+ return flat(recv, 1) if omitted?(depth)
1298
+
1227
1299
  flat(recv, coerce_flat_depth(depth))
1228
1300
  end
1229
1301
 
@@ -1253,7 +1325,7 @@ module BarefootJS
1253
1325
 
1254
1326
  # `String.prototype.trim()`.
1255
1327
  def trim(recv)
1256
- return '' if recv.nil? || recv.is_a?(Array) || recv.is_a?(Hash)
1328
+ return '' if BarefootJS.nullish?(recv) || recv.is_a?(Array) || recv.is_a?(Hash)
1257
1329
 
1258
1330
  string(recv).gsub(/\A\p{Space}+|\p{Space}+\z/, '')
1259
1331
  end
@@ -1262,25 +1334,27 @@ module BarefootJS
1262
1334
  # siblings of `trim` above (#2183 follow-up), same `\p{Space}` regex
1263
1335
  # restricted to one side.
1264
1336
  def trim_start(recv)
1265
- return '' if recv.nil? || recv.is_a?(Array) || recv.is_a?(Hash)
1337
+ return '' if BarefootJS.nullish?(recv) || recv.is_a?(Array) || recv.is_a?(Hash)
1266
1338
 
1267
1339
  string(recv).sub(/\A\p{Space}+/, '')
1268
1340
  end
1269
1341
 
1270
1342
  def trim_end(recv)
1271
- return '' if recv.nil? || recv.is_a?(Array) || recv.is_a?(Hash)
1343
+ return '' if BarefootJS.nullish?(recv) || recv.is_a?(Array) || recv.is_a?(Hash)
1272
1344
 
1273
1345
  string(recv).sub(/\p{Space}+\z/, '')
1274
1346
  end
1275
1347
 
1276
1348
  # `Number.prototype.toFixed(digits)` -- fixed-decimal string with
1277
1349
  # zero-padding, rounding half toward +Infinity (matching `round`).
1278
- def to_fixed(value, digits = 0)
1350
+ # An omitted or `undefined` digit count is 0, as ToIntegerOrInfinity
1351
+ # makes `null` too.
1352
+ def to_fixed(value, digits = OMITTED)
1279
1353
  n = number(value)
1280
1354
  return 'NaN' if n.respond_to?(:nan?) && n.nan?
1281
1355
  return n.negative? ? '-Infinity' : 'Infinity' if n.respond_to?(:infinite?) && n.infinite?
1282
1356
 
1283
- digits = 0 if digits.nil? || digits.negative?
1357
+ digits = [to_integer_or_infinity(digits), 0].max
1284
1358
  factor = 10.0**digits
1285
1359
  rounded = (n * factor + 0.5).floor
1286
1360
  format("%.#{digits}f", rounded / factor)
@@ -1291,35 +1365,35 @@ module BarefootJS
1291
1365
  # string in a single-element Array; trailing empty fields are kept
1292
1366
  # (JS parity -- Ruby's `String#split(str, -1)` already matches this,
1293
1367
  # and (unlike a Regexp) a String separator is matched literally).
1294
- def split(recv, sep = nil, limit = nil)
1295
- s = (recv.nil? || recv.is_a?(Array) || recv.is_a?(Hash)) ? '' : string(recv)
1368
+ # An omitted or `undefined` separator yields `[s]`; any other one is
1369
+ # ToString'd (`null` splits on "null"). An omitted or `undefined` limit
1370
+ # is unbounded; any other one is ToUint32'd (`null` is 0).
1371
+ def split(recv, sep = OMITTED, limit = OMITTED)
1372
+ s = (recv.is_a?(Array) || recv.is_a?(Hash)) ? '' : string(recv)
1296
1373
  parts =
1297
- if sep.nil?
1374
+ if omitted?(sep)
1298
1375
  [s]
1299
- elsif string(sep).empty?
1300
- s.chars
1301
- elsif s.empty?
1302
- ['']
1303
1376
  else
1304
- s.split(string(sep), -1)
1305
- end
1306
- unless limit.nil?
1307
- n = limit.to_i
1308
- if n.zero?
1309
- parts = []
1310
- elsif n.positive? && n < parts.length
1311
- parts = parts[0...n]
1377
+ sep_s = js_string(sep)
1378
+ if sep_s.empty?
1379
+ s.chars
1380
+ elsif s.empty?
1381
+ ['']
1382
+ else
1383
+ s.split(sep_s, -1)
1384
+ end
1312
1385
  end
1313
- end
1386
+ parts = parts[0, to_uint32(limit)] unless omitted?(limit)
1314
1387
  parts
1315
1388
  end
1316
1389
 
1317
1390
  # `String.prototype.startsWith(prefix, position?)`.
1318
- def starts_with(recv, prefix, position = nil)
1319
- s = recv.nil? ? '' : string(recv)
1320
- p = prefix.nil? ? '' : string(prefix)
1391
+ # An omitted or `undefined` position is 0; `null` is 0 too.
1392
+ def starts_with(recv, prefix, position = OMITTED)
1393
+ s = string(recv)
1394
+ p = js_string(prefix)
1321
1395
  # `position` counts UTF-16 code units, like JS (#3613).
1322
- unless position.nil?
1396
+ unless omitted?(position)
1323
1397
  units = utf16_units(s)
1324
1398
  return utf16_has_at?(units, utf16_units(p), clamp_index(to_integer_or_infinity(position), units.length))
1325
1399
  end
@@ -1327,11 +1401,12 @@ module BarefootJS
1327
1401
  end
1328
1402
 
1329
1403
  # `String.prototype.endsWith(suffix, endPosition?)`.
1330
- def ends_with(recv, suffix, end_position = nil)
1331
- s = recv.nil? ? '' : string(recv)
1332
- x = suffix.nil? ? '' : string(suffix)
1404
+ # An omitted or `undefined` endPosition is the length; `null` is 0.
1405
+ def ends_with(recv, suffix, end_position = OMITTED)
1406
+ s = string(recv)
1407
+ x = js_string(suffix)
1333
1408
  # `endPosition` counts UTF-16 code units, like JS (#3613).
1334
- unless end_position.nil?
1409
+ unless omitted?(end_position)
1335
1410
  units = utf16_units(s)
1336
1411
  needle = utf16_units(x)
1337
1412
  return utf16_has_at?(units, needle, clamp_index(to_integer_or_infinity(end_position), units.length) - needle.length)
@@ -1343,9 +1418,9 @@ module BarefootJS
1343
1418
  # form only, replacing the FIRST occurrence, literally (no regex
1344
1419
  # metacharacters, no `$1`-style replacement interpolation).
1345
1420
  def replace(recv, pattern, replacement)
1346
- s = recv.nil? ? '' : string(recv)
1347
- o = pattern.nil? ? '' : string(pattern)
1348
- n = replacement.nil? ? '' : string(replacement)
1421
+ s = string(recv)
1422
+ o = js_string(pattern)
1423
+ n = js_string(replacement)
1349
1424
  return n + s if o.empty?
1350
1425
 
1351
1426
  idx = s.index(o)
@@ -1366,9 +1441,9 @@ module BarefootJS
1366
1441
  # first and after the last character (`"abc".replaceAll("", "X")` ->
1367
1442
  # "XaXbXcX"), matching JS.
1368
1443
  def replace_all(recv, pattern, replacement)
1369
- s = recv.nil? ? '' : string(recv)
1370
- o = pattern.nil? ? '' : string(pattern)
1371
- n = replacement.nil? ? '' : string(replacement)
1444
+ s = string(recv)
1445
+ o = js_string(pattern)
1446
+ n = js_string(replacement)
1372
1447
  return ([''] + s.chars + ['']).join(n) if o.empty?
1373
1448
 
1374
1449
  # `+''` (not the frozen `''` literal under frozen_string_literal)
@@ -1428,19 +1503,21 @@ module BarefootJS
1428
1503
  # `String.prototype.repeat(n)` -- a count <= 0 degrades to '' rather
1429
1504
  # than raising (JS throws RangeError for negative counts; SSR
1430
1505
  # templates degrade instead of dying mid-render).
1431
- def repeat(recv, count)
1432
- s = recv.nil? ? '' : string(recv)
1433
- n = count.nil? ? 0 : count.to_i
1506
+ def repeat(recv, count = OMITTED)
1507
+ s = string(recv)
1508
+ n = to_integer_or_infinity(count)
1434
1509
  n.positive? ? s * n : ''
1435
1510
  end
1436
1511
 
1437
- # `String.prototype.padStart` / `padEnd`.
1438
- def pad_start(recv, target, pad_str = nil)
1439
- pad_string(recv.nil? ? '' : string(recv), target, pad_str, true)
1512
+ # `String.prototype.padStart` / `padEnd`. An omitted or `undefined` pad
1513
+ # string is a space; any other one is ToString'd (`null` pads with
1514
+ # "null").
1515
+ def pad_start(recv, target = OMITTED, pad_str = OMITTED)
1516
+ pad_string(string(recv), target, pad_str, true)
1440
1517
  end
1441
1518
 
1442
- def pad_end(recv, target, pad_str = nil)
1443
- pad_string(recv.nil? ? '' : string(recv), target, pad_str, false)
1519
+ def pad_end(recv, target = OMITTED, pad_str = OMITTED)
1520
+ pad_string(string(recv), target, pad_str, false)
1444
1521
  end
1445
1522
 
1446
1523
  # `Array.prototype.sort(cmp)` / `.toSorted(cmp)` -- fixed comparator
@@ -1461,7 +1538,10 @@ module BarefootJS
1461
1538
  end
1462
1539
  return recv.dup if spec.empty?
1463
1540
 
1464
- decorated = recv.each_with_index.map do |item, idx|
1541
+ # JS moves every `undefined` element to the end without handing it to
1542
+ # the comparator.
1543
+ defined, tail = recv.partition { |item| !BarefootJS.undefined?(item) }
1544
+ decorated = defined.each_with_index.map do |item, idx|
1465
1545
  keys = spec.map { |sp| sp[:key_kind] == 'field' ? field_value(item, sp[:key]) : item }
1466
1546
  [keys, item, idx]
1467
1547
  end
@@ -1478,7 +1558,7 @@ module BarefootJS
1478
1558
  result.zero? ? (x[2] <=> y[2]) : result
1479
1559
  end
1480
1560
 
1481
- sorted.map { |pair| pair[1] }
1561
+ sorted.map { |pair| pair[1] } + tail
1482
1562
  end
1483
1563
 
1484
1564
  # Fold an array into a scalar via the arithmetic-fold catalogue
@@ -1589,7 +1669,7 @@ module BarefootJS
1589
1669
  next if key_s == 'children'
1590
1670
 
1591
1671
  val = bag[key]
1592
- next if val.nil?
1672
+ next if BarefootJS.nullish?(val)
1593
1673
 
1594
1674
  if val.is_a?(TrueClass) || val.is_a?(FalseClass)
1595
1675
  next unless val
@@ -1619,6 +1699,41 @@ module BarefootJS
1619
1699
 
1620
1700
  private
1621
1701
 
1702
+ # JS ToNumber for a helper argument: `Evaluator.to_number`, with a value
1703
+ # outside its subset (an array or object) reading NaN instead of raising
1704
+ # mid-render.
1705
+ def js_number(value)
1706
+ Evaluator.to_number(value)
1707
+ rescue Evaluator::EvalUnsupported
1708
+ Float::NAN
1709
+ end
1710
+
1711
+ # JS ToString for a helper argument (a needle, a separator, a pattern):
1712
+ # `Evaluator.to_string`, which spells `null` / `undefined` as JS does.
1713
+ def js_string(value)
1714
+ Evaluator.to_string(value)
1715
+ rescue Evaluator::EvalUnsupported
1716
+ string(value)
1717
+ end
1718
+
1719
+ # Whether an optional argument takes its JS default: omitted or
1720
+ # `undefined`, never `null` (JS coerces an explicit `null` like any
1721
+ # other value: `[1, 2].slice(0, null)` is `[]`).
1722
+ def omitted?(value)
1723
+ OMITTED.equal?(value) || BarefootJS.undefined?(value)
1724
+ end
1725
+
1726
+ # `value` as `JSON.stringify` sees it: a member holding `undefined` is
1727
+ # dropped and an `undefined` element is `null`, at any depth. A host's
1728
+ # `encode_json` never receives `UNDEF`.
1729
+ def json_ready(value)
1730
+ case value
1731
+ when Hash then value.each_with_object({}) { |(k, v), out| out[k] = json_ready(v) unless BarefootJS.undefined?(v) }
1732
+ when Array then value.map { |v| BarefootJS.undefined?(v) ? nil : json_ready(v) }
1733
+ else value
1734
+ end
1735
+ end
1736
+
1622
1737
  def finite_number?(n)
1623
1738
  !(n.respond_to?(:nan?) && n.nan?) && !(n.respond_to?(:infinite?) && n.infinite?)
1624
1739
  end
@@ -1663,14 +1778,14 @@ module BarefootJS
1663
1778
  end
1664
1779
 
1665
1780
  def style_to_css(value)
1666
- return nil if value.nil?
1781
+ return nil if BarefootJS.nullish?(value)
1667
1782
  unless value.is_a?(Hash)
1668
1783
  s = string(value)
1669
1784
  return s.empty? ? nil : s
1670
1785
  end
1671
1786
  parts = value.keys.sort_by(&:to_s).filter_map do |key|
1672
1787
  v = value[key]
1673
- next if v.nil?
1788
+ next if BarefootJS.nullish?(v)
1674
1789
 
1675
1790
  prop = key.to_s.gsub(/([A-Z])/) { "-#{Regexp.last_match(1).downcase}" }
1676
1791
  "#{prop}:#{string(v)}"
@@ -1689,8 +1804,13 @@ module BarefootJS
1689
1804
  escaped.tr(' ', '+')
1690
1805
  end
1691
1806
 
1807
+ # A row field's value: JS `item.key`, `undefined` when the row has no
1808
+ # such field (or is no object).
1692
1809
  def field_value(item, key)
1693
- item.is_a?(Hash) ? item[field_key(key)] : nil
1810
+ return UNDEF unless item.is_a?(Hash)
1811
+
1812
+ k = field_key(key)
1813
+ item.key?(k) ? item[k] : UNDEF
1694
1814
  end
1695
1815
 
1696
1816
  def field_key(key)
@@ -1704,7 +1824,7 @@ module BarefootJS
1704
1824
  end
1705
1825
 
1706
1826
  def numeric_value(v)
1707
- return 0 if v.nil?
1827
+ return 0 if BarefootJS.nullish?(v)
1708
1828
  return v if v.is_a?(Numeric)
1709
1829
  return Float(v.strip) if v.is_a?(String) && v.strip =~ NUMERIC_STRING_RE
1710
1830
 
@@ -1762,14 +1882,18 @@ module BarefootJS
1762
1882
  def compare_sort_key(av, bv, compare_type)
1763
1883
  case compare_type
1764
1884
  when 'string'
1765
- (av.nil? ? '' : string(av)) <=> (bv.nil? ? '' : string(bv))
1885
+ string(av) <=> string(bv)
1766
1886
  when 'auto'
1767
1887
  if numeric_like?(av) && numeric_like?(bv)
1768
1888
  numeric_value(av) <=> numeric_value(bv)
1769
1889
  else
1770
- (av.nil? ? '' : string(av)) <=> (bv.nil? ? '' : string(bv))
1890
+ string(av) <=> string(bv)
1771
1891
  end
1772
1892
  else
1893
+ # `a - b` over an `undefined` key is NaN, which the sort reads as
1894
+ # "equal".
1895
+ return 0 if BarefootJS.undefined?(av) || BarefootJS.undefined?(bv)
1896
+
1773
1897
  numeric_value(av) <=> numeric_value(bv)
1774
1898
  end
1775
1899
  end
@@ -1780,12 +1904,14 @@ module BarefootJS
1780
1904
  indices = reverse ? (recv.length - 1).downto(0).to_a : (0...recv.length).to_a
1781
1905
  indices.each do |i|
1782
1906
  item = recv[i]
1783
- if item.nil?
1784
- return i if elem.nil?
1907
+ # Strict equality tells the nils apart: `null` matches only `null`,
1908
+ # `undefined` only `undefined`.
1909
+ if BarefootJS.nullish?(item) || BarefootJS.nullish?(elem)
1910
+ return i if item.equal?(elem)
1785
1911
 
1786
1912
  next
1787
1913
  end
1788
- return i if !elem.nil? && item == elem
1914
+ return i if item == elem
1789
1915
  end
1790
1916
  -1
1791
1917
  end
@@ -1804,7 +1930,7 @@ module BarefootJS
1804
1930
  # the caller's range check treats it as out of range instead of
1805
1931
  # `Float#to_i` raising FloatDomainError.
1806
1932
  def to_integer_or_infinity(value)
1807
- n = number(value)
1933
+ n = js_number(value)
1808
1934
  return 0 if n.respond_to?(:nan?) && n.nan?
1809
1935
  return MAX_SAFE_INDEX if n >= MAX_SAFE_INDEX
1810
1936
  return -MAX_SAFE_INDEX if n <= -MAX_SAFE_INDEX
@@ -1820,7 +1946,7 @@ module BarefootJS
1820
1946
 
1821
1947
  def utf16_index_of(recv, elem, reverse)
1822
1948
  hay = utf16_units(recv)
1823
- needle = utf16_units(string(elem))
1949
+ needle = utf16_units(js_string(elem))
1824
1950
  last = hay.length - needle.length
1825
1951
  indices = reverse ? last.downto(0) : 0.upto(last)
1826
1952
  indices.each { |i| return i if utf16_has_at?(hay, needle, i) }
@@ -1828,17 +1954,37 @@ module BarefootJS
1828
1954
  end
1829
1955
 
1830
1956
  def utf16_at(recv, i)
1831
- return nil if i.nil?
1832
-
1833
1957
  units = utf16_units(recv)
1834
- idx = to_integer_or_infinity(i)
1835
- idx += units.length if idx.negative?
1836
- return nil if idx.negative? || idx >= units.length
1958
+ idx = relative_index(i, units.length)
1959
+ return UNDEF if idx.nil?
1837
1960
 
1838
1961
  u = units[idx]
1839
1962
  (0xD800..0xDFFF).cover?(u) ? "\uFFFD" : [u].pack('U')
1840
1963
  end
1841
1964
 
1965
+ # `Array.prototype.at`'s index: ToIntegerOrInfinity, counted from the
1966
+ # end when negative; nil when it falls outside `[0, length)`.
1967
+ def relative_index(value, length)
1968
+ idx = to_integer_or_infinity(value)
1969
+ idx += length if idx.negative?
1970
+ idx >= 0 && idx < length ? idx : nil
1971
+ end
1972
+
1973
+ # A `slice` bound: counted from the end when negative, clamped to
1974
+ # `[0, length]`.
1975
+ def clamp_relative(idx, length)
1976
+ idx += length if idx.negative?
1977
+ clamp_index(idx, length)
1978
+ end
1979
+
1980
+ # JS `ToUint32` (`split`'s limit): NaN and the infinities are 0.
1981
+ def to_uint32(value)
1982
+ n = js_number(value).to_f
1983
+ return 0 if n.nan? || n.infinite?
1984
+
1985
+ n.truncate % (2**32)
1986
+ end
1987
+
1842
1988
  def clamp_index(n, len)
1843
1989
  n = 0 if n.negative?
1844
1990
  n = len if n > len
@@ -1846,11 +1992,11 @@ module BarefootJS
1846
1992
  end
1847
1993
 
1848
1994
  def pad_string(s, target, pad_str, at_start)
1849
- pad_str = pad_str.nil? ? ' ' : string(pad_str)
1995
+ pad_str = omitted?(pad_str) ? ' ' : js_string(pad_str)
1850
1996
  return s if pad_str.empty?
1851
1997
 
1852
1998
  len = s.length
1853
- t = target.nil? ? 0 : target.to_i
1999
+ t = to_integer_or_infinity(target)
1854
2000
  return s if len >= t
1855
2001
 
1856
2002
  need = t - len