Skip to content

Support optional chaining and nullish coalescing in the CSP evaluator - #4914

Open
m-develops wants to merge 1 commit into
alpinejs:mainfrom
m-develops:csp-optional-chaining-nullish
Open

m-develops wants to merge 1 commit into
alpinejs:mainfrom
m-develops:csp-optional-chaining-nullish

Conversation

@m-develops

Copy link
Copy Markdown

?. and ?? are the two operators a template reaches for when data may be missing: user?.name, data?.color ?? ''. The CSP evaluator rejects both, so under the CSP build every such attribute has to be rewritten to (user || {}).name or moved into a component method.

Why now. Livewire's csp_safe mode uses this build, and Filament is working on supporting it. Its templates use these two operators in dozens of attributes, and Dan Harrin asked for them to be supported here rather than rewritten in every template: filamentphp/filament#7032 (reply in thread)

What this does. Adds ?. and ?? with JavaScript's semantics, and nothing beyond a member access, a call or a fallback that the evaluator already allows:

  • A chain whose base is null or undefined evaluates to undefined as a whole, so user?.profile.name does not throw on the second link, and (user?.profile).name still does. The arguments of a call that short-circuits are not evaluated.
  • ?? only falls through for null and undefined (0, '' and false stay), evaluates its right side lazily like && and || do since Fix && and || not short-circuiting in CSP evaluator #4823, and sits between || and the ternary in precedence.

The approach follows #4810 by @dasm, with the whole-chain short-circuit and the lazy evaluation added. Unit tests for all of the above, a Cypress test, and a docs entry.

Adds `?.` and `??` to the CSP build's expression parser, the two
operators templates reach for when data may be missing.

Both follow JavaScript's semantics. A chain whose base is null or
undefined evaluates to undefined as a whole, so `user?.profile.name`
does not throw on the second link, and the arguments of a call that
short-circuits are not evaluated. `??` only falls through for null and
undefined, evaluates its right side lazily, and sits between `||` and
the ternary in precedence.

Based on the approach of alpinejs#4810 by dasm.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant