alexei / sprintf.js

sprintf.js is a complete open source JavaScript sprintf implementation
BSD 3-Clause "New" or "Revised" License
2.11k stars 291 forks source link

feat: expose parser #207

Open bertho-zero opened 3 years ago

bertho-zero commented 3 years ago

This PR exposes the parser as a non-enumerable property.

alexei commented 3 years ago

Hey Kévin, thanks for your input. I'd appreciate some clarifications about this change.

bertho-zero commented 3 years ago

I forked VError to be browser compatible, so I replaced joyent/node-extsprintf with sprintf-js but I can't seem to reproduce the SError class without this change.

SError, which is just like VError but interprets printf-style arguments more strictly.

SError throw an error when using a %s token with null or undefined, for example:

sprintf('%s', null) // throw an error

For that it is necessary to parse the tokens before calling sprintf-js.

alexei commented 3 years ago

Oh, I see. This has been asked before (i.e. supporting relaxed, strict modes) and while I agree to the idea, I'm against such approaches where the (undocumented) internals get exposed. At one point I suggested proxying arguments, but I guess that would only work with named placeholders where you pass an object.

alexei commented 3 years ago

See also https://github.com/alexei/sprintf.js/pull/165

bertho-zero commented 3 years ago

I don't see how to check the arguments without using the ast that comes out of the parser, it seems normal to me to export it and document it for more advanced use cases like this.

alexei commented 3 years ago

It's possible I didn't understand your use case. TBH I don't even know what SError and VError are. But if you want it to not raise on missing argument, you can use a proxy with named placeholders and have the proxy return something on missing key.

bertho-zero commented 3 years ago

VError is a class that extends native Error and uses sprintf to construct its message. SError should do the same thing but stricter with strings. The documentation is available here, I invite you to take a tour to better understand.

To know if a token is %s I need to parse the string, I don't see how the placeholders could help me, the string comes from the developer who uses VError, not from me, I have no control over the placeholders.

bertho-zero commented 3 years ago

What is the inconvenience of exposing the parser?

How can I parse the arguments to do some preprocessing before calling sprintf, without duplicating the code of the parser part?

alexei commented 3 years ago

What is the inconvenience of exposing the parser?

Probably none, if you do it intentionally. That is not the case with this library.