BarefootJS

 view release on metacpan or  search on metacpan

lib/BarefootJS.pm  view on Meta::CPAN

package BarefootJS;
our $VERSION = "0.41.3";
use strict;
use warnings;
use utf8;
use feature 'signatures';
no warnings 'experimental::signatures';

use B ();
use JSON::PP ();
use POSIX ();
use Time::Local ();
use Scalar::Util qw(looks_like_number refaddr weaken);
use BarefootJS::Undefined ();
use BarefootJS::Evaluator ();

# JS `undefined` (BarefootJS/Undefined.pm); Perl's `undef` is JS `null`. A
# props hashref has JS's four states for a prop: the key left out (absent),
# `$BarefootJS::UNDEF` (present `undefined`), `undef` (`null`) and a value.
# `UNDEF` is `defined` in Perl's sense and `//` keeps it, so every nullish
# test in this runtime goes through `_nullish` (`is_nullish`), never
# `defined` / `//`.
our $UNDEF = $BarefootJS::Undefined::UNDEF;
sub _undef_p { BarefootJS::Undefined::is_undefined($_[0]) }
sub _nullish { BarefootJS::Undefined::is_nullish($_[0]) }

# The default of a helper's optional argument: the call passed none. JS
# reads an omitted argument as `undefined`, so `_omitted` accepts `UNDEF`
# too; an explicit `undef` is JS `null`, which each helper coerces like any
# other value (`[1, 2].slice(0, null)` is `[]`).
my $OMITTED = \'omitted';
sub _omitted { return (ref $_[0] && refaddr($_[0]) == refaddr($OMITTED)) || _undef_p($_[0]) ? 1 : 0 }

# JS ToString / ToNumber for a helper argument (a needle, a separator, a
# count), which spell `null` / `undefined` as JS does (`"null"` / 0,
# `"undefined"` / NaN); `string` / `number` are the display helpers.
sub _js_string { BarefootJS::Evaluator::_to_string($_[0]) }
sub _js_number { BarefootJS::Evaluator::_to_number($_[0]) }

# NOTE: This runtime is template-engine-agnostic AND framework-agnostic by
# design, so it can ship as a standalone CPAN distribution. It depends only on
# core Perl (subroutine signatures + the hand-rolled minimal accessor base
# below — no Mojo::Base, no Class::Tiny). Every operation that depends on *how*
# a template is rendered — JSON marshalling, raw-string marking, JSX-children
# materialisation, and named-template rendering — is delegated to a pluggable
# `backend` (see BarefootJS::Backend::Mojo for the reference Mojolicious
# implementation), which is the only component that pulls in the Mojo
# distribution, and only when it is actually used.

# ---------------------------------------------------------------------------
# Minimal accessor base (no Mojo::Base / Class::Tiny dependency)
# ---------------------------------------------------------------------------
#
# Generates read/write accessors with optional lazy defaults so the runtime
# stays free of any non-core OO base. Semantics mirror the Mojo::Base `has`
# this class used to inherit: a getter returns the stored value (building it
# from the default on first access if unset); a setter stores the value and
# returns $self for chaining. A default is either a plain scalar or a coderef
# invoked as `$default->($self)` (for per-instance refs like `[]` / `{}` and
# the lazily-required Mojo backend).
my %ATTR_DEFAULT = (
    _scripts         => sub { [] },
    _script_seen     => sub { {} },
    _preloads        => sub { [] },
    _preload_seen    => sub { {} },
    _portal_elements => sub { [] },
    _child_renderers => sub { {} },
    _is_child        => 0,
    # Lazily fall back to the Mojo reference backend so a bare-blessed
    # instance (the pure-function unit tests) and the historical
    # `BarefootJS->new($c, ...)` callers keep working unchanged. A non-Mojo
    # host injects its own backend via `BarefootJS->new($c, { backend => $b })`
    # and never triggers this require — keeping the core load Mojo-free.
    backend          => sub {
        require BarefootJS::Backend::Mojo;
        return BarefootJS::Backend::Mojo->new;
    },
);

# c            — Mojolicious controller (kept for back-compat accessors)
# config       — plugin / instance config
# backend      — the template-engine seam (#engine-abstraction)
# _scope_id    — addressable scope id
# _bf_parent / _bf_mount — slot identity when this scope is slot-attached
# _props       — props serialised into bf-p / the scope comment
# _data_key    — keyed-loop-item key, emitted as data-key on the scope root
for my $attr (qw(
    c config backend
    _scripts _script_seen _preloads _preload_seen _portal_elements _scope_id _is_child _bf_parent _bf_mount _props
    _data_key _child_renderers
)) {
    no strict 'refs';
    *{"BarefootJS::$attr"} = sub {
        my $self = shift;
        if (@_) { $self->{$attr} = shift; return $self; }
        if (!exists $self->{$attr} && exists $ATTR_DEFAULT{$attr}) {

lib/BarefootJS.pm  view on Meta::CPAN

    return %extra;
}

# An `ssrDefaults` entry's seed when the caller's prop is absent or `UNDEF`:
# its `value` (a `{"$undef": true}` sentinel in it is `UNDEF`), or `UNDEF`
# when it has none.
sub _static_fallback ($d) {
    return exists $d->{value} ? BarefootJS::Undefined::decode_undefined($d->{value}) : $UNDEF;
}

# ---------------------------------------------------------------------------
# Script Output
# ---------------------------------------------------------------------------

sub scripts ($self) {
    my @tags;
    # Preload hints BEFORE script tags — a hint that arrives after the
    # script it describes is useless. Same escaping (none; paths are
    # caller-trusted resolved URLs) as the script tags below.
    for my $path (@{$self->_preloads}) {
        push @tags, qq{<link rel="modulepreload" crossorigin href="$path">};
    }
    for my $path (@{$self->_scripts}) {
        push @tags, qq{<script type="module" src="$path"></script>};
    }
    return join("\n", @tags);
}

# ---------------------------------------------------------------------------
# Streaming SSR (Out-of-Order)
# ---------------------------------------------------------------------------

sub streaming_bootstrap ($self) {
    return q{<script>(function(){function s(id){var a=document.querySelector('[bf-async="'+id+'"]');var t=document.querySelector('template[bf-async-resolve="'+id+'"]');if(!a||!t)return;a.replaceChildren(t.content.cloneNode(true));a.removeAttribute('b...
}

sub async_boundary ($self, $id, $fallback_html) {
    # The fallback comes in via Mojo `begin %>...<% end` capture (see
    # MojoAdapter::renderAsync), which produces a CODE ref returning a
    # Mojo::ByteStream. Materialize it through the backend so the rendered
    # HTML embeds in the placeholder rather than the CODE ref's
    # stringification.
    $fallback_html = $self->backend->materialize($fallback_html);
    return qq{<div bf-async="$id">$fallback_html</div>};
}

sub async_resolve ($self, $id, $content_html) {
    return qq{<template bf-async-resolve="$id">$content_html</template><script>__bf_swap("$id")</script>};
}

# ---------------------------------------------------------------------------
# JS-compat callees (#1189) — invoked from generated Mojo templates as
# <%= bf->json($val) %>, <%= bf->floor($val) %>, etc. The MojoAdapter's
# `templatePrimitives` registry emits these helper calls in place of the
# corresponding JS callees (`JSON.stringify`, `Math.floor`, …) so the SSR
# template can render value-equivalent output without a JS engine.
#
# Failure policy mirrors the Go adapter (#1188): user-data marshalling
# (json) bubbles errors so Mojolicious aborts loudly on cycles /
# unsupported values rather than silently producing an empty payload.
# Numeric coercion follows JS semantics (NaN propagates as the special
# string 'NaN'; non-numeric input returns 'NaN' rather than 0). Strings
# always coerce to a string representation.
# ---------------------------------------------------------------------------

sub json ($self, $value) {
    # `JSON.stringify`: `null` (`undef`) is "null"; `undefined` (`UNDEF`)
    # gives no string at the top level -- the result is `UNDEF` itself,
    # which prints nothing and omits an attribute -- an object member
    # holding it is skipped, and an array element holding it is written as
    # `null`.
    #
    # A number is written as JS writes it (`_format_number`): shortest
    # round-trip digits, `-0` as `0`, an unpadded exponent (`-4e-8`,
    # `-4e+21`), and NaN / Infinity as `null`, at any depth (#3787). The
    # encoders print `%.15g` (`0.3` for `0.1 + 0.2`), pad the exponent
    # (`-4e-08`) and spell Infinity `-Inf` or `"-Inf"`. Arrays and hashes
    # are walked here with sorted keys, as the canonical encoders do;
    # strings and other leaves go through the backend's encoder (Mojo's
    # `to_json` returns a character string, suitable for embedding in HTML
    # output via Mojo::ByteStream / `<%==`).
    return $value if _undef_p($value);
    my $ref = ref $value;
    return '[' . CORE::join(',', map { _undef_p($_) ? 'null' : $self->json($_) } @$value) . ']' if $ref eq 'ARRAY';
    if ($ref eq 'HASH') {
        return '{' . CORE::join(',', map {
            $self->backend->encode_json("$_") . ':' . $self->json($value->{$_})
        } grep { !_undef_p($value->{$_}) } sort keys %$value) . '}';
    }
    if (_json_is_number($value)) {
        my $n = BarefootJS::Evaluator::_double($value + 0);
        return 'null' if $n != $n || $n == 9**9**9 || $n == -(9**9**9);
        return BarefootJS::Evaluator::_format_number($n);
    }
    return $self->backend->encode_json($value);
}

# Whether `json` writes $value as a JSON number. Decided from the scalar's
# flags the way JSON::PP / Cpanel::JSON::XS do: a scalar carrying a public
# string flag (SVf_POK) is a string, even after a numeric comparison has
# cached a number on it (`"1e5" < 0` leaves IOK/NOK set), so a JSON string
# prop keeps its quotes whatever the template compared it with. A number
# that was only stringified keeps the private flag alone (Perl 5.36+) and
# stays a number.
# `$value` as `JSON.stringify` sees it, for a host encoder: a member holding
# `undefined` is dropped and an `undefined` element is `null`, at any depth.
# The encoder (JSON::PP dies on `UNDEF`, Mojo::JSON writes `""`) never
# receives `UNDEF`. A JSON boolean and any other leaf pass through.
sub _json_ready ($value) {
    my $ref = ref $value;
    if ($ref eq 'HASH') {
        return { map { ($_ => _json_ready($value->{$_})) } grep { !_undef_p($value->{$_}) } keys %$value };
    }
    if ($ref eq 'ARRAY') {
        return [ map { _undef_p($_) ? undef : _json_ready($_) } @$value ];
    }
    return undef if _undef_p($value);
    return $value;
}

sub _json_is_number ($value) {
    return 0 if !defined $value || ref $value;
    my $flags = B::svref_2object(\$value)->FLAGS;
    return 0 if $flags & B::SVf_POK;
    return ($flags & (B::SVp_IOK | B::SVp_NOK)) ? 1 : 0;
}

sub string ($self, $value) {
    # JS `String(v)` mirror for a display sink. `undef` (`null`) and `UNDEF`
    # (`undefined`) render as the empty string here, as JSX renders them in a
    # text or attribute position -- same divergence the Go adapter documents
    # for `bf_string`. JS ToString itself is `to_string`.
    return '' if _nullish($value);
    # JS `Array.prototype.toString` is `this.join(',')`, applied
    # recursively — a bare `"$value"` interpolation would otherwise
    # stringify an ARRAY ref as its Perl memory address
    # ("ARRAY(0x...)") instead of the JS comma-join. Reached via
    # `.flat(0)`'s shallow copy stringified afterwards (#2262, shared
    # with Mojolicious/Xslate via this runtime).
    return CORE::join(',', map { $self->string($_) } @$value) if ref($value) eq 'ARRAY';
    # A JSON boolean prints as JS does (`true` / `false`), not as the `1` /
    # `0` its numeric overload yields (#3440).
    return $value ? 'true' : 'false' if _is_json_bool($value);
    # A number prints as JS `Number::toString` does, not with Perl's `%.15g`
    # (#3380); a string passes through unchanged.
    return BarefootJS::Evaluator::_format_number($value + 0) if BarefootJS::Evaluator::_is_number($value);
    return "$value";
}

# A JS boolean as a value the JSON encoder writes as `true` / `false`
# (`JSON.stringify([n, true])`): Perl holds a boolean as `1` / `''` / `0`,
# which encodes as a number or a string.
sub boolean ($self, $value) {
    return $value ? JSON::PP::true() : JSON::PP::false();
}

# A JSX text child's value: JSX renders nothing for a boolean (#3824 step 5).
# Perl holds a comparison as `1` / `''`, so only a JSON boolean is one here:
# the compiler materializes every boolean a displayed value can be with
# `boolean` first. Any other value passes through to the text sink.
sub display ($self, $value) {
    return _is_json_bool($value) ? '' : $value;
}

# A decoded JSON boolean (`Mojo::JSON::true` / `false`, a `JSON::PP::Boolean`).
sub _is_json_bool ($value) {
    my $ref = ref($value);
    return $ref eq 'JSON::PP::Boolean' || $ref eq 'Mojo::JSON::_Bool';
}

sub number ($self, $value) {
    # JS `Number(v)` mirror. Numeric coerces via Perl's implicit
    # numeric context; non-numeric / undef yield real numeric NaN
    # (`'nan' + 0`) so downstream arithmetic propagates correctly
    # (`Math.floor(NaN) === NaN`). Returning the literal string
    # "NaN" would conflate the user-passing-the-string-"NaN" case
    # with the parse-failure case, and break NaN detection in
    # downstream helpers.
    return 0 + 'nan' if _nullish($value);
    return $value + 0 if looks_like_number($value);
    return 0 + 'nan';
}

# JS `+` / `-` / `*` / `/` over numbers (#3454). The adapters emit these
# instead of Perl's native operators so the result is the IEEE double JS
# computes: a 64-bit IV sum past 2**53 rounds as a double, a perl with a
# wider NV (-Duselongdouble / -Dusequadmath) rounds to the double JS has,
# and division by zero yields +/-Infinity or NaN instead of dying. Each
# operand goes through JS ToNumber (`_num`): `undef` (`null`) is 0, `UNDEF`
# (`undefined`) NaN, a string its JS numeric value.
sub _as_double { unpack('d', pack('d', $_[0])) }
sub _num { _as_double(_js_number($_[0])) }

sub add ($self, $l, $r) {
    return _as_double(_num($l) + _num($r));
}

sub subtract ($self, $l, $r) {
    return _as_double(_num($l) - _num($r));
}

sub multiply ($self, $l, $r) {
    return _as_double(_num($l) * _num($r));
}

sub divide ($self, $l, $r) {
    return BarefootJS::Evaluator::_divide(_num($l), _num($r));
}

# JS `%` (#3474): the truncated remainder, which takes the dividend's sign
# (`-7 % 2` is -1) and keeps a fraction. Perl's native `%` floors (`-7 % 2`
# is 1) and converts both operands to integers (`NaN % 2` is 0).
sub mod ($self, $l, $r) {
    return BarefootJS::Evaluator::_remainder(_num($l), _num($r));
}

# NaN is the only float for which `$x != $x` holds. Used as the
# portable sentinel check in floor/ceil/round. The `Math` helpers coerce
# through JS ToNumber (`null` is 0, `undefined` NaN), as `Math.floor(null)`
# is 0.
sub _is_nan { my $n = shift; return $n != $n }

# True for +/-Infinity. `9**9**9` is Perl's portable infinity literal; a
# finite number is always strictly less than +Inf in magnitude.
sub _is_inf { my $n = shift; return $n == 9**9**9 || $n == -9**9**9 }

sub floor ($self, $value) {
    my $n = _js_number($value);
    return $n if _is_nan($n);
    return POSIX::floor($n);
}

sub ceil ($self, $value) {
    my $n = _js_number($value);
    return $n if _is_nan($n);
    return POSIX::ceil($n);
}

sub round ($self, $value) {
    my $n = _js_number($value);
    return $n if _is_nan($n);
    # POSIX has no `round`. JS `Math.round` rounds half toward
    # +Infinity (so `Math.round(-1.5) === -1`, not -2). `floor(n
    # + 0.5)` reproduces that for both signs.
    return POSIX::floor($n + 0.5);
}

# `Math.min(a, b)` / `Math.max(a, b)` -- two-arg forms only (#2168
# math-methods). JS returns NaN if either operand is NaN.
sub min ($self, $a, $b) {
    my $x = _js_number($a);
    my $y = _js_number($b);
    return $x if _is_nan($x);
    return $y if _is_nan($y);
    return $x < $y ? $x : $y;
}

sub max ($self, $a, $b) {
    my $x = _js_number($a);
    my $y = _js_number($b);
    return $x if _is_nan($x);
    return $y if _is_nan($y);
    return $x > $y ? $x : $y;
}

# `Math.abs()` (#2168 math-methods). `CORE::abs` avoids Perl's
# ambiguous-call warning against this package's own `abs` sub.
sub abs ($self, $value) {
    my $n = _js_number($value);
    return $n if _is_nan($n);
    return CORE::abs($n);
}

# `date($recv, $op)` -- zero-arg `Date.prototype` method lowering (#2274,
# spec entry "date"). `$recv` arrives as either a `BarefootJS::Date` (this
# runtime's own epoch-ms wrapper, below) or an ISO-8601 string (a template
# prop may carry either depending on how the host populated it); both
# normalize to a single epoch-ms integer via `_date_epoch_ms` before
# dispatch. `gmtime`'s `mon` field (index 4) is ALREADY 0-based in Perl
# (unlike every other backend's native month accessor), so — uniquely among
# this catalogue's ports — `getUTCMonth` needs NO -1. `getTime` is the exact
# epoch-ms integer already carried by `$recv`/parsed from the string, so it
# needs no float rounding even for a pre-epoch instant.
sub date ($self, $recv, $op) {
    my $ms = _date_epoch_ms($recv);
    return $op eq 'toISOString' ? '' : 0 unless defined $ms;
    return $ms if $op eq 'getTime';

    # Floor (not truncate) toward -Infinity: Perl's `/` truncates toward
    # zero, which would round a negative ms value (e.g. -14182939877) up to
    # the wrong whole second (-14182939 instead of -14182940).
    my $sec = POSIX::floor($ms / 1000);
    my $msec = $ms - ($sec * 1000);
    my @t = gmtime($sec);    # (sec,min,hour,mday,mon,year,...) -- mon is 0-based

    return $t[5] + 1900 if $op eq 'getUTCFullYear';
    return $t[4]        if $op eq 'getUTCMonth';    # already 0-based, no -1
    return $t[3]         if $op eq 'getUTCDate';
    return $t[2]         if $op eq 'getUTCHours';
    return $t[1]         if $op eq 'getUTCMinutes';
    return $t[0]         if $op eq 'getUTCSeconds';
    return POSIX::strftime('%Y-%m-%dT%H:%M:%S', @t) . sprintf('.%03dZ', $msec)
        if $op eq 'toISOString';
    return 0;
}

# Normalizes a `date()` receiver to a single epoch-ms integer: a
# `BarefootJS::Date` (unwraps `epoch_ms` directly) or an ISO-8601 string
# (`YYYY-MM-DDTHH:MM:SS[.sss]Z`, the exact shape every ISO string this

lib/BarefootJS.pm  view on Meta::CPAN

# `format_date`'s own pre-1970 handling.
package BarefootJS::_TZProbe {

    sub new ($class, $epoch_s) {
        my $days = POSIX::floor($epoch_s / 86400);
        my @t    = gmtime($epoch_s);
        return bless {
            rd_days => $days + 719_163,
            rd_secs => $epoch_s - $days * 86400,
            year    => $t[5] + 1900,
        }, $class;
    }

    sub utc_rd_values ($self) { return ($self->{rd_days}, $self->{rd_secs}, 0) }
    sub utc_year      ($self) { return $self->{year} }

    sub utc_rd_as_seconds ($self) {
        return $self->{rd_days} * 86400 + $self->{rd_secs};
    }
}

# Resolve a canonical IANA zone name's UTC offset (whole seconds) at the
# epoch-ms instant through DateTime::TimeZone (#2344). Loaded lazily so the
# 'UTC'/fixed-offset paths -- and every other helper -- keep working on a
# core-modules-only install; reaching a named zone without the module dies
# with the same loud message as an unknown zone (never a silent UTC
# fallback). 'local' and 'floating' are DateTime::TimeZone specials that
# would read the host environment / return a zoneless offset -- both
# refused explicitly, same as the JS reference refuses 'Local'.
sub _format_date_zone_offset ($tz, $ms) {
    if ($tz eq '' || lc($tz) eq 'local' || lc($tz) eq 'floating') {
        die qq{format_date: unresolvable timeZone "$tz"};
    }
    my $zone = eval {
        require DateTime::TimeZone;
        DateTime::TimeZone->new(name => $tz);
    };
    if (!$zone) {
        # Carry the underlying loader/constructor error: "unresolvable"
        # covers both an unknown zone AND a broken/absent DateTime::TimeZone
        # installation, and the two need different fixes.
        my $cause = $@ ? " ($@)" : '';
        die qq{format_date: unresolvable timeZone "$tz"$cause};
    }
    return $zone->offset_for_datetime(
        BarefootJS::_TZProbe->new(POSIX::floor($ms / 1000)));
}

# ---------------------------------------------------------------------------
# Array / String method helpers (#1448 Tier A)
# ---------------------------------------------------------------------------
#
# `Array.prototype.includes(x)` and `String.prototype.includes(sub)`
# share a method name in JS; the JSX parser can't tell the two
# receiver shapes apart without TS type inference, so both lower to
# the same IR node (`array-method` / method `includes`). This helper
# dispatches at the Perl level via `ref()`:
#   - ARRAY ref:  scan elements with `BarefootJS::Evaluator::_same_value_zero`,
#                 matching `Array.prototype.includes`'s SameValueZero
#                 semantics (no cross-type coercion, e.g. `[2].includes("2")`
#                 is false; NaN matches NaN) — the same algorithm the
#                 evaluator's serialized-callback path already uses for
#                 `.includes`, so both positions agree. This used to be a
#                 stringy `eq` scan, which coerced numbers to strings
#                 (`[2].includes("2")` was true) and diverged from JS.
#   - scalar:     `index($recv, $sub) != -1`, the needle JS ToString'd
#                 (`null` searches for "null", `undefined` for
#                 "undefined").
# Anything else (HASH ref, code ref) returns false — matches the
# JS semantic where `.includes` is only defined on Array /
# TypedArray / String.

# JS `a === b` when neither operand's type is known at compile time. Perl's
# numeric `==` reads two different non-numeric strings as `0 == 0`, and `eq`
# reads `1` and `1.0` as different, so the comparison goes by the operands'
# JS types: numbers by value, strings by content, booleans by truth value,
# `undef` (`null`) only to `undef`, `UNDEF` (`undefined`) only to `UNDEF`, an
# object or array only to the same reference,
# and values of different types never equal. The
# result is a Perl boolean, the same value the native operators yield.
sub strict_eq ($self, $l, $r) {
    return BarefootJS::Evaluator::_strict_eq($l, $r) ? !!1 : !!0;
}

# JS primitive helpers (spec/js-primitive-semantics.md, "Operation table"):
# ToBoolean, ToNumber, ToString, the relational operators, binary `+` and
# unary `-`. Each delegates to the callback evaluator's primitive of the same
# operation, so a template helper call and a callback body share one
# implementation. A boolean result is a Perl boolean, as `strict_eq`'s is.
# Unlike `number` and `string` (display helpers: `undef` / `UNDEF` -> NaN /
# ''), an `undef` operand reads as JS null here (0 / 'null') and `UNDEF` as JS
# undefined (NaN / 'undefined').
sub truthy ($self, $v) {
    return BarefootJS::Evaluator::_truthy($v) ? !!1 : !!0;
}

# Boxes for a value-position JS `l || r` / `l && r` (#3824): the adapters
# spell `l || r` as `(keep_truthy(l) || [r])->[0]` and `l && r` as
# `(keep_falsy(l) || [r])->[0]`. `keep_truthy` is the one-element arrayref
# `[$v]` when `$v` is JS-truthy and undef otherwise (`keep_falsy` the
# reverse), so Perl's `||` stops at `$v`'s box exactly when JS returns `$v`
# itself and builds `[r]` only otherwise (the short circuit); `->[0]` unboxes
# the operand. Each operand appears once, so a chain grows linearly.
sub keep_truthy ($self, $v) {
    return BarefootJS::Evaluator::_truthy($v) ? [$v] : undef;
}

sub keep_falsy ($self, $v) {
    return BarefootJS::Evaluator::_truthy($v) ? undef : [$v];
}

# The box for a value-position JS `l ?? r`: the adapters spell it as
# `(keep_nonnil(l) || [r])->[0]`, so each operand appears once. Only the two
# nils (`null`, `undefined`) are absent; `0`, `''` and `false` are kept, as
# in JS. Perl's `//` would keep `UNDEF`.
sub keep_nonnil ($self, $v) {
    return _nullish($v) ? undef : [$v];
}

sub to_number ($self, $v) { return BarefootJS::Evaluator::_to_number($v) }

sub to_string ($self, $v) { return BarefootJS::Evaluator::_to_string($v) }

sub plus ($self, $l, $r) { return BarefootJS::Evaluator::_binary('+', $l, $r) }

sub neg ($self, $v) { return BarefootJS::Evaluator::_unary('-', $v) }

sub lt ($self, $l, $r) { return BarefootJS::Evaluator::_relational('<', $l, $r) ? !!1 : !!0 }
sub le ($self, $l, $r) { return BarefootJS::Evaluator::_relational('<=', $l, $r) ? !!1 : !!0 }
sub gt ($self, $l, $r) { return BarefootJS::Evaluator::_relational('>', $l, $r) ? !!1 : !!0 }
sub ge ($self, $l, $r) { return BarefootJS::Evaluator::_relational('>=', $l, $r) ? !!1 : !!0 }

sub includes ($self, $recv, $elem) {
    if (ref($recv) eq 'ARRAY') {
        for my $item (@$recv) {
            return 1 if BarefootJS::Evaluator::_same_value_zero($item, $elem);
        }
        return 0;
    }
    return 0 if ref($recv);
    # The needle is JS ToString'd (`"anullb".includes(null)` is true).
    return index($self->string($recv), _js_string($elem)) != -1 ? 1 : 0;
}

# `Array.prototype.filter(fn)` / `.every(fn)` / `.some(fn)`. The Xslate adapter
# lowers a JS arrow predicate to a Kolon lambda (`-> $x { ... }`), which is
# callable from Perl as a code ref, and emits `$bf.filter($arr, <lambda>)`.
# `filter` returns a new arrayref; `every` / `some` return 1/0. Non-array /
# empty receivers follow JS (`filter` → [], `every` → true, `some` → false).
# (The Mojo adapter lowers these shapes inline and never reaches these methods.)
sub filter ($self, $recv, $pred) {
    return [] unless ref($recv) eq 'ARRAY';

lib/BarefootJS.pm  view on Meta::CPAN

    return BarefootJS::Evaluator::_read_index($collection, $key);
}

# JS `undefined` as a template spells it (`bf->undefined` / `$bf.undefined()`):
# the `undefined` identifier, an omitted method argument's default, the
# result of a `?.` over a nullish receiver.
sub undefined ($self) { return $UNDEF }

# The nil tests (spec/js-undefined-value.md, decisions 3 and 7): JS
# `x === undefined`, `x === null` and the loose `x == null`. A template
# spells a nil-test plan, an attribute omission and a `??` through them;
# Perl's `defined` / `//` see `UNDEF` as a value. A boolean result is a Perl
# boolean, as `strict_eq`'s is.
sub is_undefined ($self, $v) { return _undef_p($v) ? !!1 : !!0 }
sub is_null      ($self, $v) { return defined($v) ? !!0 : !!1 }
sub is_nullish   ($self, $v) { return _nullish($v) ? !!1 : !!0 }

# `isValidElement(x)` -- the framework "is this a renderable element (not
# plain text)?" predicate `Slot`'s `asChild` pattern uses (#2266). Mirrors
# JS's `'tag' in x && 'props' in x`: true only for a HASH ref carrying both
# keys (case-insensitively, matching the case-tolerant field lookups
# elsewhere in this module). A passed-through JSX child is represented as
# pre-rendered markup (a plain string) on this SSR model, so a non-empty
# STRING child is NOT a valid element -- routing `isValidElement` through
# bare truthiness here would wrongly take the element-merge branch.
sub is_element ($self, $v) {
    return 0 unless ref($v) eq 'HASH';
    my ($has_tag, $has_props) = (0, 0);
    for my $key (keys %$v) {
        $has_tag = 1 if CORE::lc($key) eq 'tag';
        $has_props = 1 if CORE::lc($key) eq 'props';
    }
    return ($has_tag && $has_props) ? 1 : 0;
}

# `Array.prototype.indexOf(x)` / `Array.prototype.lastIndexOf(x)`
# value-equality search (#1448 Tier A). Returns the 0-based position
# of the first / last matching element, or -1 if not found.
# A plain-scalar (string) receiver is `String.prototype.indexOf` /
# `.lastIndexOf` instead, counted in UTF-16 code units like JS (#3613):
# `'日本語'.indexOf('本')` is 1 and `'a😀b'.indexOf('b')` is 3. Any other
# reference returns -1 (`.indexOf` is only defined on Array / TypedArray /
# String).

sub _array_index_of ($recv, $elem, $reverse) {
    return -1 unless ref($recv) eq 'ARRAY';
    my @indices = $reverse ? (reverse 0 .. $#{$recv}) : (0 .. $#{$recv});
    for my $i (@indices) {
        my $item = $recv->[$i];
        # Strict equality tells the nils apart: `null` matches only `null`,
        # `undefined` only `undefined`.
        if (_nullish($item) || _nullish($elem)) {
            return $i if (!defined $item && !defined $elem) || (_undef_p($item) && _undef_p($elem));
            next;
        }
        return $i if $item eq $elem;
    }
    return -1;
}

# JS `ToIntegerOrInfinity` for a string position or index (#3613): NaN →
# 0, truncation toward zero, and ±Infinity clamped to ±2**53 so the
# caller's range check treats it as out of range (a bare `int()` keeps
# NaN, which then indexes element 0 with a warning).
sub _to_integer_or_infinity ($self, $value) {
    my $n = _js_number($value);
    return 0 if _is_nan($n);
    return 2**53 if $n >= 2**53;
    return -(2**53) if $n <= -(2**53);
    return int($n);
}

# `$s` as JS sees it: a list of UTF-16 code units. JS string positions
# (`indexOf`, `at`, `startsWith`'s position, …) count these, so an astral
# character such as '😀' is two units (#3613).
sub _utf16_units ($s) {
    my @units;
    for my $o (map { ord } split //, $s) {
        if ($o > 0xFFFF) {
            $o -= 0x10000;
            push @units, 0xD800 + ($o >> 10), 0xDC00 + ($o & 0x3FF);
        } else {
            push @units, $o;
        }
    }
    return \@units;
}

# Whether `$needle` (unit list) occurs in `$hay` at unit offset `$at`.
sub _utf16_has_at ($hay, $needle, $at) {
    return 0 if $at < 0 || $at + @$needle > @$hay;
    for my $i (0 .. $#$needle) {
        return 0 if $hay->[$at + $i] != $needle->[$i];
    }
    return 1;
}

sub _utf16_index_of ($self, $recv, $elem, $reverse) {
    my $hay    = _utf16_units("$recv");
    # The needle is JS ToString'd (`'anullb'.indexOf(null)` is 1).
    my $needle = _utf16_units(_js_string($elem));
    my $last   = @$hay - @$needle;
    my @indices = $reverse ? (reverse 0 .. $last) : (0 .. $last);
    for my $i (@indices) {
        return $i if _utf16_has_at($hay, $needle, $i);
    }
    return -1;
}

sub index_of ($self, $recv, $elem) {
    return $self->_utf16_index_of($recv, $elem, 0) if defined $recv && !ref($recv);
    return _array_index_of($recv, $elem, 0);
}

sub last_index_of ($self, $recv, $elem) {
    return $self->_utf16_index_of($recv, $elem, 1) if defined $recv && !ref($recv);
    return _array_index_of($recv, $elem, 1);
}

# `Array.prototype.at(i)` — supports negative indices (`.at(-1)` is
# the last element); out-of-bounds returns JS `undefined` (`UNDEF`, which
# renders as the empty string).
# Matches the Go `bf_at` arithmetic (`length + i` for i < 0) so adapter
# output stays symmetric. A plain-scalar (string) receiver is

lib/BarefootJS.pm  view on Meta::CPAN

    }
    return [] unless ref($recv) eq 'ARRAY';
    my $len = scalar @$recv;
    return [] if $len == 0;

    my ($s, $e) = $self->_clamp_slice_range($len, $start, $end);
    return [] if $s >= $e;
    return [ @{$recv}[$s .. $e - 1] ];
}

# Shared bounds arithmetic for both `slice` branches above.
sub _clamp_slice_range ($self, $len, $start, $end) {
    my $s = _omitted($start) ? 0 : $self->_to_integer_or_infinity($start);
    $s = $len + $s if $s < 0;
    $s = 0    if $s < 0;
    $s = $len if $s > $len;

    my $e = _omitted($end) ? $len : $self->_to_integer_or_infinity($end);
    $e = $len + $e if $e < 0;
    $e = 0    if $e < 0;
    $e = $len if $e > $len;

    return ($s, $e);
}

# `Array.prototype.reverse()` / `Array.prototype.toReversed()` —
# both shapes share this lowering. SSR templates render a snapshot
# of state, so JS's mutate-receiver (`reverse`) vs
# return-new-array (`toReversed`) distinction has no template-
# level meaning. Always returns a new ARRAY ref to keep callers
# safe from accidental aliasing. Non-array receivers return an
# empty ARRAY ref.

sub reverse ($self, $recv) {
    return [] unless ref($recv) eq 'ARRAY';
    return [ reverse @$recv ];
}

# `Array.prototype.flat(depth?)` (#1448 Tier C) — flatten nested ARRAY
# refs `$depth` levels deep. A `$depth` of -1 is the `Infinity` sentinel
# (flatten fully); 0 returns a shallow copy. Non-ARRAY elements are kept
# as-is (JS only flattens nested arrays). Non-ARRAY receiver → [].
sub flat ($self, $recv, $depth = 1) {
    return [] unless ref($recv) eq 'ARRAY';
    my @out;
    for my $el (@$recv) {
        if ($depth != 0 && ref($el) eq 'ARRAY') {
            my $next = $depth > 0 ? $depth - 1 : $depth;
            push @out, @{ $self->flat($el, $next) };
        }
        else {
            push @out, $el;
        }
    }
    return \@out;
}

# `Array.prototype.flat(depth)` with a DYNAMIC depth (#2094) — the depth is
# itself an arbitrary runtime value (e.g. a prop), not a compile-time literal,
# so it must be coerced with JS's `ToIntegerOrInfinity` before delegating to
# `flat` above: truncate toward zero; negative -> 0; NaN / non-numeric -> 0;
# +Infinity or a huge finite value -> flatten fully.
#
# Deliberately a SEPARATE entry point from `flat`, not a smarter version of
# it: the literal-depth path's `-1` argument is a compile-time SENTINEL baked
# into the template source, meaning "the source literally said `Infinity`". A
# genuinely dynamic depth that happens to evaluate to `-1` at render time
# means the OPPOSITE in real JS (`[1,[2]].flat(-1)` never recurses — same as
# `.flat(0)`). Since both paths would otherwise hand the same literal-looking
# argument to one shared function, that function couldn't tell which case
# it's in — so the two stay separate. Mirrors Go's `FlatDynamicDepth` /
# `coerceFlatDepth` in bf.go.
sub flat_dynamic ($self, $recv, $depth) {
    # An `undefined` depth is the default, 1; `null` coerces to 0.
    return $self->flat($recv, 1) if _omitted($depth);
    return $self->flat($recv, _coerce_flat_depth($depth));
}

# _coerce_flat_depth: JS `ToIntegerOrInfinity` for a dynamic `.flat(depth)`
# argument, collapsed to `flat`'s int contract (`-1` == flatten fully).
#
# Perl's scalar type system blurs string/number duality, so `looks_like_number`
# (already the codebase's ToNumber-style coercion check, see BarefootJS::
# Evaluator's `_to_number`) is reused here rather than inventing a new
# convention. `looks_like_number` on this Perl (5.38) already recognises the
# strings "Infinity" / "-Infinity" / "NaN" as numeric (verified empirically:
# `perl -MScalar::Util=looks_like_number -e 'print looks_like_number("Infinity")'`
# prints 1), and `$str + 0` on those strings yields the corresponding Perl
# non-finite double, so no extra string special-casing is needed here.
sub _coerce_flat_depth ($depth) {
    return 0 unless defined $depth;
    my $f;
    if (ref($depth) eq 'JSON::PP::Boolean') {
        $f = $depth ? 1 : 0;
    }
    elsif (!ref($depth) && looks_like_number($depth)) {
        $f = $depth + 0;
    }
    else {
        # undef handled above; anything else non-numeric (a plain string
        # that isn't a number, a HASH/ARRAY ref, ...) coerces via NaN.
        return 0;
    }
    return 0 if $f != $f;              # NaN
    return -1 if $f == 9**9**9;        # +Infinity -> flatten fully sentinel
    return 0  if $f == -(9**9**9);     # -Infinity -> 0
    my $trunc = int($f);               # Perl's int() truncates toward zero
    return 0  if $trunc < 0;
    return -1 if $trunc > 1_000_000;   # huge finite ~= flatten fully
    return $trunc;
}

# `Array.prototype.flatMap(fn)` value-returning field projection
# (#1448 Tier C) — map each element through a self / field projection,
# then flatten one level. `field` reads a HASH-ref key (the raw JS prop
# name, as `bf->reduce` does); a projected non-ARRAY value is kept as-is
# (flatMap = map + flat(1)). Non-ARRAY receiver → [].
sub flat_map ($self, $recv, $key_kind, $key) {
    return [] unless ref($recv) eq 'ARRAY';
    my @projected;
    for my $el (@$recv) {
        if ($key_kind eq 'field') {
            # JS `i => i.field` on a non-object, or a missing field, yields
            # `undefined`, not the element itself — so a scalar element
            # doesn't leak into the output.
            push @projected, _field_value($el, $key);
        }
        else {
            push @projected, $el;
        }
    }
    return $self->flat(\@projected, 1);
}

# `Array.prototype.flatMap(i => [i.a, i.b])` — array-literal tuple
# projection (#1448 Tier C). Each `@specs` entry is a [kind, key] arrayref
# (['self', ''] or ['field', 'a']). For each element, every leaf's value
# is appended in order. flat(1) removes only the literal wrapper, so an
# array-valued leaf is appended verbatim (no spread) — i.e. just append
# each leaf. A non-HASH element under a `field` leaf, or a missing field,
# yields `undefined` (JS `i.field`). Non-ARRAY receiver → [].
sub flat_map_tuple ($self, $recv, @specs) {
    return [] unless ref($recv) eq 'ARRAY';
    my @out;
    for my $el (@$recv) {
        for my $spec (@specs) {
            my ($kind, $key) = @$spec;
            if ($kind eq 'field') {
                push @out, _field_value($el, $key);
            }
            else {
                push @out, $el;
            }
        }
    }
    return \@out;
}

# `String.prototype.trim()` — strip leading + trailing whitespace.
# JS's `String.prototype.trim` matches `\s` in the Unicode sense
# (any whitespace including non-breaking space U+00A0); Perl's `\s`
# inside a regex with `/u` flag is the same. Undef receivers return
# the empty string (matches JS's `String(undefined).trim()` which
# would be "undefined" → "undefined", but in our template context
# undef commonly means "missing prop"; rendering the empty string
# is the safer choice and mirrors the JS-compat divergence we
# already document for `bf->string(undef) === ""`).

sub trim ($self, $recv) {
    return '' if _nullish($recv);
    return '' if ref($recv);
    my $s = "$recv";
    $s =~ s/^\s+|\s+$//gu;
    return $s;
}

# `String.prototype.trimStart()` / `.trimEnd()` — the one-sided
# siblings of `trim` above (#2183 follow-up), same `\s` /u regex
# semantics restricted to one side.

sub trim_start ($self, $recv) {
    return '' if _nullish($recv);
    return '' if ref($recv);
    my $s = "$recv";
    $s =~ s/^\s+//u;
    return $s;
}

sub trim_end ($self, $recv) {
    return '' if _nullish($recv);
    return '' if ref($recv);
    my $s = "$recv";
    $s =~ s/\s+$//u;
    return $s;
}

# `Number.prototype.toFixed(digits)` (#1897) — fixed-decimal string with
# zero-padding. JS rounds the scaled integer half toward +Infinity (the
# spec's "pick the larger n" tie-break), so `(2.5).toFixed(0)` is "3";
# bare `sprintf("%.*f")` would round half-to-even ("2"), diverging. Scale
# by 10**digits, round with `floor(x + 0.5)` (the same tie-break the
# `round` helper uses), then format the exact multiple. A negative
# `digits` clamps to 0, mirroring how the adapters default an omitted
# argument.
sub to_fixed ($self, $value, $digits = $OMITTED) {
    my $n = $self->number($value);
    # JS toFixed returns the STRINGS "NaN" / "Infinity" / "-Infinity" for
    # non-finite inputs; the numeric values would stringify per-platform
    # ("nan"/"inf"/...) and diverge.
    return 'NaN' if _is_nan($n);
    return $n < 0 ? '-Infinity' : 'Infinity' if _is_inf($n);
    # An omitted or `undefined` digit count is 0, as ToIntegerOrInfinity
    # makes `null` too.
    $digits = _omitted($digits) ? 0 : $self->_to_integer_or_infinity($digits);
    $digits = 0 if $digits < 0;
    my $factor  = 10 ** $digits;
    # Scaled as doubles, so `(1.005).toFixed(2)` sees JS's 100.49999… on a
    # perl whose NV is wider than a double (#3454).
    my $rounded = POSIX::floor(_as_double(_as_double($n) * $factor) + 0.5);
    return sprintf('%.*f', $digits, $rounded / $factor);
}

# `String.prototype.split(sep)` (#1448 Tier B) — string → ARRAY ref.
#
# Two JS-parity wrinkles drive the helper (a bare `split` emit would
# diverge from both JS and Go):
#
#   * Perl's `split` treats its first argument as a *regex*, so a
#     separator like '.' or '|' would match far too much. We
#     `quotemeta` it to force literal-string matching, mirroring JS's
#     string-separator semantics (the regex-separator form stays
#     refused upstream — see the parser arm).
#   * Perl's `split` drops trailing empty fields by default; JS keeps
#     them (`"a,".split(",")` is `["a", ""]`). Passing the `-1` limit
#     preserves them, matching JS and Go's `strings.Split`.
#
# An empty separator splits into individual characters (JS + Go agree).
# Undef receiver renders as the single-element `['']` — the same
# "missing prop → empty string" convention `bf->trim` uses.

sub split ($self, $recv, $sep = $OMITTED, $limit = $OMITTED) {
    my $s = defined $recv && !ref($recv) ? "$recv" : '';

    my @parts;
    if (_omitted($sep)) {
        # No separator → the whole string in a single-element array
        # (matches JS `"x".split()` / `.split(undefined)`). Any other one is
        # ToString'd (`null` splits on "null").
        @parts = ($s);
    }
    elsif (($sep = _js_string($sep)) eq '') {
        # Empty separator → individual characters. No `-1` limit here:
        # on an empty pattern Perl's `split` with `-1` appends a spurious
        # trailing empty field ("abc" → 'a','b','c',''), which JS/Go don't.
        @parts = split //, $s;
    }
    elsif ($s eq '') {
        # Empty input with a non-empty separator: JS `"".split(",")` is
        # `[""]` and Go's `strings.Split("", ",")` is `[""]`, but Perl's
        # `split /,/, ''` returns the empty list — special-case for parity.
        @parts = ('');
    }
    else {
        # `quotemeta` forces literal-string matching (JS string-separator
        # semantics); the `-1` keeps trailing empty fields (JS keeps them,
        # Perl's bare `split` drops them).
        my $q = quotemeta("$sep");
        @parts = split /$q/, $s, -1;
    }

    # Optional `limit` caps the number of pieces (JS `split(sep, limit)`):
    # an omitted or `undefined` one is unbounded, any other one ToUint32'd
    # (`null` and NaN are 0 → empty; a negative limit wraps to a large one,
    # effectively unbounded).
    unless (_omitted($limit)) {
        my $n = _to_uint32($limit);
        @parts = @parts[0 .. $n - 1] if $n < scalar @parts;
    }

    return [@parts];
}

# `String.prototype.startsWith(prefix, position?)` (#1448 Tier B) —
# string → boolean (1 / 0). `substr`-anchored literal comparison mirrors
# Go's `strings.HasPrefix`. An empty prefix is always true (JS parity);
# undef / non-string receivers coerce to the empty string first. The
# optional `position` re-anchors the test (UTF-16 code units, clamped to
# `[0, length]`), matching JS `"abc".startsWith("b", 1)`.

sub starts_with ($self, $recv, $prefix, $position = $OMITTED) {
    my $s = defined $recv && !ref($recv) ? "$recv" : '';
    my $p = _js_string($prefix);
    # An omitted or `undefined` position is 0; `null` is 0 too.
    unless (_omitted($position)) {
        # `position` counts UTF-16 code units, like JS (#3613).
        my $units = _utf16_units($s);
        my $n = $self->_to_integer_or_infinity($position);
        $n = 0 if $n < 0;
        $n = @$units if $n > @$units;
        return _utf16_has_at($units, _utf16_units($p), $n);
    }
    return substr($s, 0, CORE::length $p) eq $p ? 1 : 0;
}

# `String.prototype.endsWith(suffix, endPosition?)` (#1448 Tier B) —
# string → boolean (1 / 0). Mirrors Go's `strings.HasSuffix`. An empty
# suffix is always true (JS parity); a suffix longer than the string is
# false. `substr($s, -length $x)` would mis-read the whole string when
# `length $x == 0`, so that case short-circuits. The optional
# `endPosition` treats the string as if it were only that many UTF-16
# code units long (clamped to `[0, length]`), matching JS
# `"abc".endsWith("b", 2)`.

sub ends_with ($self, $recv, $suffix, $end_position = $OMITTED) {
    my $s = defined $recv && !ref($recv) ? "$recv" : '';
    my $x = _js_string($suffix);
    # An omitted or `undefined` endPosition is the length; `null` is 0.
    unless (_omitted($end_position)) {
        # `endPosition` counts UTF-16 code units, like JS (#3613).
        my $units  = _utf16_units($s);
        my $needle = _utf16_units($x);
        my $e = $self->_to_integer_or_infinity($end_position);
        $e = 0 if $e < 0;
        $e = @$units if $e > @$units;
        return _utf16_has_at($units, $needle, $e - @$needle);
    }
    return 1 if $x eq '';
    return 0 if CORE::length($s) < CORE::length($x);
    return substr($s, -CORE::length $x) eq $x ? 1 : 0;
}

# `String.prototype.replace(pattern, replacement)` — string-pattern
# form only (#1448 Tier B), replacing the FIRST occurrence (JS string-

lib/BarefootJS.pm  view on Meta::CPAN

        next if $val eq '';
        if (exists $pos{$key}) {
            $pairs[$pos{$key}][1] = $val;
        }
        else {
            $pos{$key} = scalar @pairs;
            push @pairs, [$key, $val];
        }
    }
    return $b unless @pairs;
    return "$b?" . CORE::join('&', map { _form_escape($_->[0]) . '=' . _form_escape($_->[1]) } @pairs);
}

# `String.prototype.repeat(n)` — the receiver concatenated n times
# (#1448 Tier B), via Perl's `x` operator. JS throws RangeError for a
# negative count, but SSR templates degrade to the empty string rather
# than dying mid-render, so a count <= 0 returns "" (Go's `bf_repeat`
# applies the same clamp). The count is truncated toward zero
# (`int`), matching JS's ToIntegerOrInfinity on `"a".repeat(3.7)`.

sub repeat ($self, $recv, $count = $OMITTED) {
    my $s = defined $recv && !ref($recv) ? "$recv" : '';
    # ToIntegerOrInfinity: an omitted, `undefined` or `null` count is 0.
    my $n = $self->_to_integer_or_infinity(_omitted($count) ? $UNDEF : $count);
    return $n <= 0 ? '' : $s x $n;
}

# `String.prototype.padStart` / `padEnd` (#1448 Tier B) — pad the
# receiver to `$target` characters with `$pad` (default a single space)
# repeated and truncated to fill, prepended or appended. Length is
# measured in characters (Perl `length`), matching Go's rune-based
# `bf_pad_*` — diverges from JS's UTF-16-unit length only for
# astral-plane input. An empty pad, or a receiver already >= `$target`,
# returns the receiver unchanged (JS parity). The `$target` is
# truncated toward zero (JS ToLength on the first arg).

sub _pad ($self, $s, $target, $pad, $at_start) {
    # An omitted or `undefined` pad string is a space; any other one is
    # ToString'd (`null` pads with "null"). The target is ToIntegerOrInfinity'd.
    $pad = _omitted($pad) ? ' ' : _js_string($pad);
    return $s if $pad eq '';
    my $len = CORE::length $s;
    my $t   = $self->_to_integer_or_infinity(_omitted($target) ? $UNDEF : $target);
    return $s if $len >= $t;
    my $need = $t - $len;
    # Repeat enough copies to cover $need, then trim to exactly $need.
    my $fill = substr($pad x (int($need / CORE::length($pad)) + 1), 0, $need);
    return $at_start ? $fill . $s : $s . $fill;
}

sub pad_start ($self, $recv, $target = $OMITTED, $pad = $OMITTED) {
    my $s = defined $recv && !ref($recv) ? "$recv" : '';
    return $self->_pad($s, $target, $pad, 1);
}

sub pad_end ($self, $recv, $target = $OMITTED, $pad = $OMITTED) {
    my $s = defined $recv && !ref($recv) ? "$recv" : '';
    return $self->_pad($s, $target, $pad, 0);
}

# JS `ToUint32` (`split`'s limit): NaN and the infinities are 0.
sub _to_uint32 ($value) {
    my $n = _js_number($value);
    return 0 if $n != $n || $n == 9**9**9 || $n == -(9**9**9);
    my $t = $n < 0 ? POSIX::ceil($n) : POSIX::floor($n);
    $t = POSIX::fmod($t, 4294967296);
    $t += 4294967296 if $t < 0;
    return $t;
}

# A row field's value: JS `item.key`, `undefined` when the row has no such
# field (or is no object).
sub _field_value ($item, $key) {
    return $UNDEF unless ref($item) eq 'HASH';
    return exists $item->{$key} ? $item->{$key} : $UNDEF;
}

# `Array.prototype.sort(cmp)` / `Array.prototype.toSorted(cmp)`
# lowering (#1448 Tier B). Non-mutating — JS's mutate-vs-new
# distinction is moot in SSR template context.
#
# Opts hash-ref. The compiler emits a `keys` list of per-key hashes
# in priority order; each hash carries:
#
#   key_kind     => 'self' | 'field'
#   key          => '' when key_kind eq 'self'; field name verbatim
#                   from the comparator AST (e.g. 'price', 'createdAt')
#                   when key_kind eq 'field' — no case normalisation
#                   applied. Perl hash lookups are case-sensitive so
#                   the key here must match the actual hash key the
#                   user populated.
#   compare_type => 'numeric' | 'string' | 'auto'
#   direction    => 'asc' | 'desc'
#
# Accepted comparator catalogue (gated upstream at parse time —
# anything outside refuses with BF101 before reaching this helper):
#
#   (a,b) => a.f - b.f                       → field, numeric
#   (a,b) => a - b                           → self,  numeric
#   (a,b) => a[.f].localeCompare(b[.f])      → field|self, string
#   (a,b) => a.f > b.f ? 1 : -1              → field|self, auto
#   any of the above ||-chained              → multi-key tie-breaks
#   (and reversed-operand variants for `desc`).
#
# `auto` (relational-ternary lowering) compares numerically when both
# keys `looks_like_number`, else lexically — Go's `bf_sort` applies the
# same rule so the two template adapters stay byte-equal.
#
# A future `nulls => 'first' | 'last'` knob can land per key without
# churn — the opts hash is the right place to grow.

# Evaluator-driven sort / reduce (#2018): the comparator / reducer body rides
# as a serialized-ParsedExpr JSON string and is evaluated per element, delegating
# to the shared BarefootJS::Evaluator. The adapter emits `bf->sort_eval(...)` /
# `bf->reduce_eval(...)` for any pure comparator / reducer body; a body it can't
# model (e.g. localeCompare) keeps the legacy `bf->sort` / `bf->reduce` path.
sub sort_eval ($self, $recv, $cmp_json, $param_a, $param_b, $base_env = {}) {
    return BarefootJS::Evaluator::sort_by_json($recv, $cmp_json, $param_a, $param_b, $base_env);
}

sub reduce_eval ($self, $recv, $body_json, $acc_name, $item_name, $init, $direction = 'left', $base_env = {}) {

lib/BarefootJS.pm  view on Meta::CPAN


sub flat_map_eval ($self, $recv, $proj_json, $param, $base_env = {}) {
    return BarefootJS::Evaluator::flat_map_json($recv, $proj_json, $param, $base_env);
}

# Value-producing `.map(cb)` (#2073): project each element through the
# serialized projection body, one result per element (no flatten). Composes
# through the array-method chain (`.map(cb).join(' ')`).
sub map_eval ($self, $recv, $proj_json, $param, $base_env = {}) {
    return BarefootJS::Evaluator::map_json($recv, $proj_json, $param, $base_env);
}

sub sort ($self, $recv, $opts = {}) {
    return [] unless ref($recv) eq 'ARRAY';

    # Normalise the per-key specs (priority order, length >= 1).
    my @spec = map {
        {
            key_kind     => $_->{key_kind}     // 'self',
            key          => $_->{key}          // '',
            compare_type => $_->{compare_type} // 'numeric',
            direction    => $_->{direction}    // 'asc',
        }
    } @{ $opts->{keys} // [] };
    return [ @$recv ] unless @spec;

    # JS moves every `undefined` element to the end without handing it to
    # the comparator.
    my @tail = grep { _undef_p($_) } @$recv;

    # Schwartzian transform: project each item to all its sort keys
    # once, then compare projected keys. Cheaper than re-resolving the
    # field accessors inside every comparison for non-trivial arrays.
    my @keyed = map {
        my $item = $_;
        my @ks = map {
            $_->{key_kind} eq 'field' ? _field_value($item, $_->{key}) : $item;
        } @spec;
        [ \@ks, $item ];
    } grep { !_undef_p($_) } @$recv;

    my $cmp = sub {
        for my $i (0 .. $#spec) {
            my $sp = $spec[$i];
            my $c  = _compare_sort_key($a->[0][$i], $b->[0][$i], $sp->{compare_type});
            next if $c == 0;            # tie on this key — try the next
            return $sp->{direction} eq 'desc' ? -$c : $c;
        }
        return 0;
    };

    my @sorted = sort $cmp @keyed;
    return [ (map { $_->[1] } @sorted), @tail ];
}

# Compare two projected keys, ascending orientation (-1 / 0 / 1); the
# caller negates for 'desc'. 'auto' compares numerically when both
# keys look like numbers, else lexically (matches Go's `bf_sort`).
# A nil key (`null` / `undefined`) reads as '' lexically and `null` as 0
# numerically, so the order stays total without warnings; a numeric
# `a.f - b.f` over an `undefined` key is NaN, which the sort reads as
# "equal".
sub _compare_sort_key ($av, $bv, $compare_type) {
    my $str = sub ($v) { _nullish($v) ? '' : $v };
    if ($compare_type eq 'string') {
        return $str->($av) cmp $str->($bv);
    }
    if ($compare_type eq 'auto') {
        if (!_undef_p($av) && !_undef_p($bv) && looks_like_number($av // '') && looks_like_number($bv // '')) {
            return ($av // 0) <=> ($bv // 0);
        }
        return $str->($av) cmp $str->($bv);
    }
    return 0 if _undef_p($av) || _undef_p($bv);
    return ($av // 0) <=> ($bv // 0);    # numeric
}

# Fold an array into a scalar via the arithmetic-fold catalogue
# (#1448 Tier C). Mirrors Go's `bf_reduce` and JS `reduce(fn, init)` /
# `reduceRight(fn, init)` for the shapes `(acc, x) => acc <op> x` /
# `(acc, x) => acc <op> x.field`:
#
#   bf->reduce($recv, {
#     op        => '+' | '*',
#     key_kind  => 'self' | 'field',
#     key       => '<field>',         # when key_kind eq 'field'
#     type      => 'numeric' | 'string',
#     init      => <seed>,            # number, or string for concat
#     direction => 'left' | 'right',  # 'right' = reduceRight (default 'left')
#   })
#
# Numeric folds accumulate with `+` / `*` (non-numeric keys coalesce to
# 0); string folds concatenate via `bf->string` (undef → ''). The init
# seeds the accumulator, so an empty array returns it unchanged — exactly
# like JS. `direction => 'right'` folds right-to-left (reduceRight); only
# observable for string concat, since numeric sum / product commute.
# Float stringification can diverge from Go's for inexact binary
# fractions (e.g. 0.1 + 0.2); integer sums — the common case — agree.
sub reduce ($self, $recv, $opts = {}) {
    my $op        = $opts->{op}        // '+';
    my $key_kind  = $opts->{key_kind}  // 'self';
    my $key       = $opts->{key}       // '';
    my $type      = $opts->{type}      // 'numeric';
    my $direction = $opts->{direction} // 'left';

    my @items = ref($recv) eq 'ARRAY' ? @$recv : ();
    # reduceRight folds right-to-left; reversing the snapshot keeps the
    # single forward loop below. Only observable for string concat —
    # numeric sum / product commute. Qualify as CORE::reverse — this
    # package defines `sub reverse` (the `.reverse()` helper), so a bare
    # `reverse` is ambiguous under `use warnings`.
    @items = CORE::reverse(@items) if $direction eq 'right';
    my $project = sub ($item) {
        $key_kind eq 'field' && ref($item) eq 'HASH' ? $item->{$key} : $item;
    };
    # The catalogue folds read a nil (`null` / `undefined`) item as '' / 0
    # (`string` / the numeric guard below), as they always have.

    if ($type eq 'string') {
        my $acc = $opts->{init} // '';
        $acc .= $self->string($project->($_)) for @items;



( run in 0.959 second using v1.01-cache-2.11-cpan-60884a8df76 )