diff --git a/.gitignore b/.gitignore index 3f2c92b..7585238 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ - -/.vscode +book diff --git a/LICENSE.txt b/LICENSE.txt index 388e08a..e27e162 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,5 +1,4 @@ Attribution-ShareAlike 4.0 International - ======================================================================= Creative Commons Corporation ("Creative Commons") is not a law firm and diff --git a/README.md b/README.md index 88b870e..1a32c69 100644 --- a/README.md +++ b/README.md @@ -1 +1,6 @@ -# Specification \ No newline at end of file +# Specification + +- Read the License + - [as Text](./LICENSE.txt) + - [as Markup](./docs/0-2024-0/LICENSE.md) +- [Read the Specification](./docs/0-2024-0/index.md) diff --git a/SUMMARY.md b/SUMMARY.md new file mode 100644 index 0000000..c613033 --- /dev/null +++ b/SUMMARY.md @@ -0,0 +1,18 @@ +# Summary + +- [Welcome](./0-2024-0/ENTRY.md) +- [Introduction](./0-2024-0/introduction) +- [Convention](./0-2024-0/convention.md) +- **Build-ins** + - '[On-Hand](./0-2024-0/built-in_on-hand.md)' + - _Types_ + - [Basic](./0-2024-0/built-in_type.md) + - [Data Structure](./0-2024-0/built-in_datastruct.md) + - [Flow Control](./0-2024-0/built-in_flow-constrol.md) + - [Operation](./0-2024-0/built-in_operation.md) + - _Syntax Sugar_ + - [A Pinch](./0-2024-0/built-in_syntactic-sugar.md) + - [Another Pinch](./0-2024-0/built-in_more-sugar.md) +- [Tips and Tricks](./0-2024-0/tips-and-tricks.md) +- [Appendice](./0-2024-0/appendice.md) + - [A](./0-2024-0/appendix-a.md) diff --git a/book.toml b/book.toml new file mode 100644 index 0000000..67fc924 --- /dev/null +++ b/book.toml @@ -0,0 +1,17 @@ +[book] +authors = ["Sara Tasche"] +language = "en" +multilingual = true +src = "docs" +title = "minimaLang - Specification" + + +[output.html] +smart-punctuation = true +git-repository-url = "https://github.com/minimaLang/" +git-repository-icon = "fa-github" +# edit-url-template = "" + +[output.html.print] +enable = true +page-break = true diff --git a/docs/0-2024-0/ENTRY.md b/docs/0-2024-0/ENTRY.md new file mode 100644 index 0000000..4252d0e --- /dev/null +++ b/docs/0-2024-0/ENTRY.md @@ -0,0 +1,4 @@ +# Welcome + +- [Introduction](./0-2024-0/introduction) +- [Convention](./0-2024-0/convention.md) diff --git a/docs/0-2024-0/appendice.md b/docs/0-2024-0/appendice.md new file mode 100644 index 0000000..8d7d3d4 --- /dev/null +++ b/docs/0-2024-0/appendice.md @@ -0,0 +1,3 @@ +# Appendice + +- [A](appendix-a.md) diff --git a/docs/md/appendix-a.md b/docs/0-2024-0/appendix-a.md similarity index 59% rename from docs/md/appendix-a.md rename to docs/0-2024-0/appendix-a.md index 123c89f..c08e570 100644 --- a/docs/md/appendix-a.md +++ b/docs/0-2024-0/appendix-a.md @@ -1,3 +1 @@ # Appendix A - -( ... ) diff --git a/docs/0-2024-0/built-in_datastruct.md b/docs/0-2024-0/built-in_datastruct.md new file mode 100644 index 0000000..cd1c1f4 --- /dev/null +++ b/docs/0-2024-0/built-in_datastruct.md @@ -0,0 +1,89 @@ +# Data Structure + +- [Mark](#mark) +- [Pair](#pair) +- [Sequence](#sequence) + - [of Value](#of-value) + - [of Expression](#of-expression) + +## Mark + +| Symbol | Syntax | Name +| ---------- | -------------- | ---- +| `"` .. `"` | _Sym> <> <1:Key> <2:Value> +``` + +### of Expression + +| Token | Name +| ------------ | --------------------- +| `{` | Expression-List-Begin +| _Expression_ | Expression +| `}` | Expression-List-End + +```minimaL +{ + 1 A : + 2 B : +} +``` diff --git a/docs/md/flow-control.md b/docs/0-2024-0/built-in_flow-control.md similarity index 53% rename from docs/md/flow-control.md rename to docs/0-2024-0/built-in_flow-control.md index 96c3a7f..b5d5f4c 100644 --- a/docs/md/flow-control.md +++ b/docs/0-2024-0/built-in_flow-control.md @@ -7,14 +7,14 @@ ## Loop -A _Loop_ is a combination of a _Branch_ and a _Comparsion_. +A _Loop_ is a combination of a _Branch_ (Jump) and a _Comparsion_. ```minimaL -A 200 : -B 10 : +200 : A +10 : B .. Loop1 A B - : C - C 0 ?0 : Loop1 .. + C 0 ?0 : Loop1 ! ``` In other programming language is this equvialent to @@ -30,13 +30,13 @@ In other programming language is this equvialent to ## Branch -| Name | Token | -| :-------- | :--------: | -| Condition | `?0`, `?1` | -| Branch | `:` | +| Name | Token | +| --------- | ----------- | +| Condition | `?0`, `?1` | +| Branch | _label_ `!` | | Syntax | -| :---------: | +| ----------- | | _Condition_ | | _Value_ | | _Branch_ | @@ -44,17 +44,23 @@ In other programming language is this equvialent to The jump target is a [Label](#label). -- _Valid_ - 1. `20 21 - 0 = ?0 : Jump ..` - 2. `5 5 - 0 = : A ?0 : Jump ..` +- _Example_ + 1. `20 21 - 0 ?0 : Jump !` - _Invalid_ - 1. `20 21 - 0 = ?0 Jump ..` - 2. `20 21 - 0 = :` + 1. `20 21 - 0 ?0 Jump !` + 2. `20 10 - ?0 : Jump !` + 3. `20 21 - 0 : Jump !` + 4. `20 21 - 0 ?0 : Jump` + +1. Colon missing (`:`) +2. No comparative value +3. Condition missing +4. Branch-Symbol missing (`!`) ## Label | Token | -| :---: | +| ----- | | `..` | See [Branch](#branch), [Loop](#loop) @@ -73,12 +79,13 @@ A _Label_ can be used to ... ### Define -| Syntax | -| :---------------: | -| _Token_ LabelName | +| Token | Syntax | Name | +| ----- | ---------- | --------- | +| `..` | `..` label | Set-Label | +| `..` | label `..` | Get-Label | ### Jump -| Syntax | -| :---------------: | -| LabelName _Token_ | +| Token | Syntax | Name | +| ----- | ---------- | ------- | +| `!` | label `!` | Jump-To | diff --git a/docs/0-2024-0/built-in_more-sugar.md b/docs/0-2024-0/built-in_more-sugar.md new file mode 100644 index 0000000..788f1c3 --- /dev/null +++ b/docs/0-2024-0/built-in_more-sugar.md @@ -0,0 +1,19 @@ +# More Sugar + +- [Familiarize with used syntax convention](syntax-convention.md) + +## Value-List + +| Token | Syntax | Name | +| :--------: | :------: | :--------: | +| `{` .. `}` | _.._ _?_ | Value-List | + +```minimaL +{ 0 1 2 3 } 2 ** { A B C D } : +``` + +- Answers + 1. [_A_] 0 + 2. [_B_] 2 + 3. [_C_] 4 + 4. [_D_] 9 diff --git a/docs/0-2024-0/built-in_on-hand.md b/docs/0-2024-0/built-in_on-hand.md new file mode 100644 index 0000000..c44ab27 --- /dev/null +++ b/docs/0-2024-0/built-in_on-hand.md @@ -0,0 +1,5 @@ +# On-Hand + +Please read _[Syntax Convention](convention.md)_ + +## Overview diff --git a/docs/0-2024-0/built-in_operation.md b/docs/0-2024-0/built-in_operation.md new file mode 100644 index 0000000..05b7050 --- /dev/null +++ b/docs/0-2024-0/built-in_operation.md @@ -0,0 +1,368 @@ +# Operations + +See [Convention](convention.md) + +- [Stack](#stack) +- [Logic](#logic) +- [Comparsion](#comparsion) +- [Arithmetic](#arithmetic) +- [Branch](#branch-anchor-condition-jump) + +## Stack + +| Symbol | Syntax | Name +| ------- | --------- | ------------------------------ +| `^` | _<>_ | [Pick](#pick-and-put) +| `.` | _<>_ | [Put](#pick-and-put) +| `:` | _<1> <2>_ | [Pass](#pass) +| `~` | _<>_ | [Drop](#drop) +| `&` | _<>_ | [Peek](#peek) +| `_` `,` | _-_ | [Separate](#separate) +| `\` | _-_ | [No-Operation](#no-operation) + +### Pick and Put + +_Pick_ takes a value, \ +and _Put_ place it on the stack. \ +_Pick_ and _Put_ are mostly used implicitly. + +One example is the mathematical operation ``2 3 +``. + +#### Explanation (_Pick and Put_) + +- The operation _Addition_ `+` causes the values 2 and 3 ... + - to be picked `^` from the stack + - passed (applied) to the function _Addition_ `+` + - finally its result is placed `.` on the stack. + +#### Explanation (_Pass_) + +```minimaL +6 A : +``` + +The _hand_ called `A` contains the answer `6`. + +See _[On-hand](built-in_on-hand.md)_. + +### Drop + +_Drop_ discards a value. \ +It deletes it from the stack. + +#### Explanation (_Drop_) + +```minimaL +2 ~ 3 3 + +``` + +_Answer_ is `6`. + +- Stack + - `2` + - `~` + - [`0`] + - `3` + - `3` + - `+` + - [`6`] + +### Peek + +| Symbol | Count | Syntax | Name +| ------ | :---: | ------------ | --------------------- +| `&` | 1 | _<>var <2> <2> <2> ` | 2 | _<1> <2> <2> ` | 2 | _<1> <2> L : +2 1 = Q : +``` + +- Answers + 1. [_L_] 1 (`'t`); is true + 2. [_Q_] 0 (`'f`); is false + +## Arithmetic + +| Symbol | Count | Syntax | Name +| -------- | :---: | -------------- | ---------------- +| `+`, `-` | 2 | _<1> <2> <2> <2> <$n_ | Set-Default-Catch-List-Byte-Size-To-n + +- **Notice** + - You can use [`$`](built-in_type#bit) to mark a value as a bit-field. \ + `$010` is a short-cut for `010 >bit`. + - `'{=$4` _(A is size of 4)_ is default size; if not defined otherwise. + - `'{A$`, `{A$0` use the defined default size. + +- See + - [Set byte-size](#set-byte-size) + - [Built-in type _Bit_](built-in_type#bit). + +| Symbol | Count | Syntax | Name +| ------ | :---: | ---------- | ------------------ +| `shl` | 1 | _<1> <> ). + +| Symbol | Count | Syntax | Name +| ------ | :---: | ------------- | --------------- +| `..` | 1 | _Sym> <>Anch_ | Set-Anchor +| `?` | 1 | _<> ~ Anch = 1? Access-Granted :: + :: Access-Denied +] +.. Access-Granted [ ] +``` + +/ End diff --git a/docs/0-2024-0/built-in_syntactic-sugar.md b/docs/0-2024-0/built-in_syntactic-sugar.md new file mode 100644 index 0000000..93041b1 --- /dev/null +++ b/docs/0-2024-0/built-in_syntactic-sugar.md @@ -0,0 +1,7 @@ +# Syntactic Sugar + +## What is Syntactic Sugar? + +## Why Syntactic Sugar? + +## What Syntactic Sugar is built-in? diff --git a/docs/md/built-in_type.md b/docs/0-2024-0/built-in_type.md similarity index 82% rename from docs/md/built-in_type.md rename to docs/0-2024-0/built-in_type.md index 9a7c2b7..14c0eb9 100644 --- a/docs/md/built-in_type.md +++ b/docs/0-2024-0/built-in_type.md @@ -1,15 +1,15 @@ # Type - [Variable](#variable) -- [Literal](#literal) - [Character](#character) +- [Literal](#literal) -Read about the syntax convention used [Syntax Convention](syntax-convention). +Read about the syntax convention [Syntax Convention](syntax-convention). ## Variable | Token | Length | **Case-Sensitive?** | Allowed Infix Character | -| :-------------: | :----- | :------------------ | :--------------------- | +| :-------------- | :----- | :------------------ | :--------------------- | | _Alpha-Numeric_ | 2..* | No | `-`, `_` | | _Alpha-Numeric_ | 1 | Yes | | @@ -27,17 +27,25 @@ Read about the syntax convention used [Syntax Convention](syntax-convention). - `A_B` - `A-B` +## Character + +| Syntax | Token | +| :----- | :---------- | +| Begin | `"` | +| ... | _Character_ | +| End | `"` | + ## Literal | Name | Token | -| :--------: | :-------------- | +| :--------- | :-------------- | | Symbol | `'` | | Identifier | _Alpha-Numeric_ | | Dash | `-` | | Underscore | `_` | | Syntax | -| :-------------------: | +| :-------------------- | | <1> `'` | | <1..*> _Identifier_ | | (<0..1> `Dash`) | @@ -52,11 +60,3 @@ Read about the syntax convention used [Syntax Convention](syntax-convention). - _Invalid_ - `'!` - `'A:` - -## Character - -| Syntax | Token | -| :----- | :---------: | -| Begin | `"` | -| ... | _Character_ | -| End | `"` | diff --git a/docs/md/convention.md b/docs/0-2024-0/convention.md similarity index 76% rename from docs/md/convention.md rename to docs/0-2024-0/convention.md index fb50be7..5e43d18 100644 --- a/docs/md/convention.md +++ b/docs/0-2024-0/convention.md @@ -1,5 +1,11 @@ # Convention +## Internal Convention + +- **See** (Syntax Convention)[syntax-convention.md] + +## Use of Chars + This is just a suggestion. \ Use as you like. diff --git a/docs/0-2024-0/introduction.md b/docs/0-2024-0/introduction.md new file mode 100644 index 0000000..e10b99d --- /dev/null +++ b/docs/0-2024-0/introduction.md @@ -0,0 +1 @@ +# Introduction diff --git a/docs/0-2024-0/specification.md b/docs/0-2024-0/specification.md new file mode 100644 index 0000000..cd8f40a --- /dev/null +++ b/docs/0-2024-0/specification.md @@ -0,0 +1,31 @@ +# Specification + +**[LICENSE](../LICENSE.md)** + +| Version | Status | +| :------: | :------ | +| 0.2024.0 | _DRAFT_ | + +- **[Show Syntax Convention](syntax-convention.md)** + +- [Operation](built-in_operation.md) + - [Stack](built-in_operation.md#stack) + - [Logic](built-in_operation.md#logic) + - [Math](built-in_operation.md#math) + - [Bit](built-in_operation.md#bit-operation) +- [Type](built-in_type.md) + - [Variable](built-in_type.md#variable) + - [Character](built-in_type.md#character) + - [Literal](built-in_type.md#literal) +- [Data Struct](built-in_datastruct.md) + - [Mark](built-in_datastruct.md#mark) + - [Pair](built-in_datastruct.md#pair) + - [Sequence](built-in_datastruct.md#sequence) + - [of Value](built-in_datastruct.md#of-value) + - [of Expression](built-in_datastruct.md#of-expression) +- [Flow Control](flow-control.md) + - [Loop](flow-control.md#loop) + - [Branch](flow-control.md#branch) + - [Label](flow-control.md#label) + - [Define](flow-control.md#define) + - [Jump](flow-control.md#jump) diff --git a/docs/0-2024-0/syntax-convention.md b/docs/0-2024-0/syntax-convention.md new file mode 100644 index 0000000..7a563ee --- /dev/null +++ b/docs/0-2024-0/syntax-convention.md @@ -0,0 +1,50 @@ +# Syntax + +- [Suggestions](concention.md) + +1. [Overview](#overview) +2. [Basics](#basics) + - Token + 1. [Template](#basics-token-template) + 2. [Definition](#basics-token-definition) + +## Overview + +| Syntax +| -------------------- +| <1> `'` +| <1..*>_Identifier_ +| (<0..1>`Dash`) +| (<0..*>_Identifier_) +| (<0..1>`Underscore`) + +1. Symbols enclosed in round brackets are optional. +2. One number enclosed in `<` `>` shows the mandatory length. +3. The Symbol `..` between numbers indicates the permitted frequency. + - `..*` indicates an unlimited frequency. + +## Basics + +1. ← [Overview](#overview) +2. [Token](#token) + +### Token + +1. [Template](#basics-token-template) +2. [Definition](#basics-token-definition) + +#### Basics (Token Template) + +1. <_TokenTemplateName_=(_Range_)> +2. <_TokenTemplateName_=_TokenList_> +3. in {_Token_}, in {_TokenTemplateName_} + +#### Basics (Token Definition) + +| Token | Syntax | Name +| ------------------ | --------------------------- | ------------ +| <_numeric_=(0..0)> | _Token_ _Token_* | Numeric +| <_nocap_=(a..z)> | (_Token_? _Token_*)+ | Alpha-NoCap +| <_allcap_=(A..Z)> | (_Token_? _Token_*)+ | Alpha-AllCap +| <_alpha_>=(A..z)> | _in_ {_allcap_ & _nocap_}+ | Alpha +| _alpha_numeric_ | _numeric_? (in {_alpha_}+) | AlphaNumeric diff --git a/docs/md/tips-and-tricks.md b/docs/0-2024-0/tips-and-tricks.md similarity index 100% rename from docs/md/tips-and-tricks.md rename to docs/0-2024-0/tips-and-tricks.md diff --git a/docs/CODE_OF_CONDUCT.md b/docs/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..2917541 --- /dev/null +++ b/docs/CODE_OF_CONDUCT.md @@ -0,0 +1,3 @@ +# The Code of Conduct + +( ... ) diff --git a/docs/CONTRIBUTION.md b/docs/CONTRIBUTION.md new file mode 100644 index 0000000..27a16e1 --- /dev/null +++ b/docs/CONTRIBUTION.md @@ -0,0 +1,65 @@ +# Contribution + +> ![WARN] +> Your agreement to the [Code of Conduct](CODE_OF_CONDUCT.md) +> and the license is mandatory before any participation! +> If you disagree with even one point, +> your co-operation will be rejected. +> If you subsequently no longer agree, +> you will be excluded from the collaboration. +> But your previous work will be retained in +> accordance with the [licence](LICENSE.md). + +--- + +## How can I Participate? + +There are several ways to participate. \ +Some points are + +- [File an Issue, write a Report or a Request](#file-an-issue) + - Is there a bug? + - Do you have a suggestion? + - Do you have a question? + - Something is missing? + - None of the above points apply or doesn't fit? +- [Write an Implementation](#write-an-implementation) +- **[Keep in Touch](#keep-in-touch)**. + +### File an Issue + +1. Is there a bug? + - File a _Fault Report_ (FR) \ + if it is a logical fault in the specification + - File a _Bug Report_ (BR) \ + if there is a bug in the official implementation +2. Do you have a suggestion? + - File a _Suggestion for Discussion_ (SD) +3. Do you have a question? + - File a _Request for Response_ (RR) +4. Something is missing? + - Please write it. +5. None of the above points apply or doesn't fit? + - Please write it down. + +Thank you! + +### Write an Implementation + +You could write an implementation. + +1. Clone the repository +2. Write your implementation +3. Send a _Pull Request_ (PR) +4. Wait for a response +5. Discuss the response +6. Keep it rolling + +Thank You! + +### Keep in Touch + +- Be polite and read our [Code of Conduct](CODE_OF_CONDUCT.md) +- [Visit the repository](https://github.com/minimaLang/) and take a look around. + - Keep it rolling! + - Contact me or a contributor. diff --git a/docs/Chapter_1.md b/docs/Chapter_1.md new file mode 100644 index 0000000..927892f --- /dev/null +++ b/docs/Chapter_1.md @@ -0,0 +1,11 @@ +# Chapter 1 + +> ![INFO] +> Agreement to +> the _Code of Conduct_ and to +> the _License_ +> is required for participation. + +1. [Code of Conduct](./CODE_OF_CONDUCT.md) +2. [License](./LICENSE.md) +3. [How To Contribute](./CONSTRIBUTION.md) diff --git a/docs/Chapter_2.md b/docs/Chapter_2.md new file mode 100644 index 0000000..8ca6b76 --- /dev/null +++ b/docs/Chapter_2.md @@ -0,0 +1,5 @@ +# Chapter 2 + +- [Welcome](./0-2024-0/ENTRY.md) +- [Introduction](./0-2024-0/introduction) +- [Convention](./0-2024-0/convention.md) diff --git a/docs/Chapter_3.md b/docs/Chapter_3.md new file mode 100644 index 0000000..978ac0c --- /dev/null +++ b/docs/Chapter_3.md @@ -0,0 +1,9 @@ +# Chapter 3 + +- **Build-ins** + - [On-Hand](./0-2024-0/built-in_on-hand.md) + - _Types_ + - [Basic](./0-2024-0/built-in_type.md) + - [Data Structure](./0-2024-0/built-in_datastruct.md) + - [Flow Control](./0-2024-0/built-in_flow-constrol.md) + - [Operation](./0-2024-0/built-in_operation.md) diff --git a/docs/Chapter_4.md b/docs/Chapter_4.md new file mode 100644 index 0000000..51ac5cf --- /dev/null +++ b/docs/Chapter_4.md @@ -0,0 +1,8 @@ +# Chapter 4 + +- _Syntax Sugar_ + - [A Pinch](./0-2024-0/built-in_syntactic-sugar.md) + - [Another Pinch](./0-2024-0/built-in_more-sugar.md) +- [Tips and Tricks](./0-2024-0/tips-and-tricks.md) +- [Appendice](./0-2024-0/appendice.md) + - [A](./0-2024-0/appendix-a.md) diff --git a/docs/LICENSE.md b/docs/LICENSE.md new file mode 100644 index 0000000..ff26809 --- /dev/null +++ b/docs/LICENSE.md @@ -0,0 +1,360 @@ +Attribution-ShareAlike 4.0 International +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses +-------------------------------------- + +Creative Commons public licenses provide a standard set of terms and \ +conditions that creators and other rights holders may use to share \ +original works of authorship and other material subject to copyright \ +and certain other rights specified in the public license below. The \ +following considerations are for informational purposes only, are not \ +exhaustive, and do not form part of our licenses. + \ + +Considerations for licensors: Our public licenses are \ +intended for use by those authorized to give the public \ +permission to use material in ways otherwise restricted by \ +copyright and certain other rights. Our licenses are \ +irrevocable. Licensors should read and understand the terms \ +and conditions of the license they choose before applying it. \ +Licensors should also secure all rights necessary before \ +applying our licenses so that the public can reuse the \ +material as expected. Licensors should clearly mark any \ +material not subject to the license. This includes other CC- \ +licensed material, or material used under an exception or \ +limitation to copyright. More considerations for licensors: \ + + +Considerations for the public: By using one of our public \ +licenses, a licensor grants the public permission to use the \ +licensed material under specified terms and conditions. If \ +the licensor's permission is not necessary for any reason--for \ +example, because of any applicable exception or limitation to \ +copyright--then that use is not regulated by the license. Our \ +licenses grant only permissions under copyright and certain \ +other rights that a licensor has authority to grant. Use of \ +the licensed material may still be restricted for other \ +reasons, including because others have copyright or other \ +rights in the material. A licensor may make special requests, \ +such as asking that all changes be marked or described. \ +Although not required by our licenses, you are encouraged to \ +respect those requests where reasonable. More considerations \ +for the public: + +--- + +## Creative Commons Attribution-ShareAlike 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree \ +to be bound by the terms and conditions of this Creative Commons \ +Attribution-ShareAlike 4.0 International Public License ("Public \ +License"). To the extent this Public License may be interpreted as a \ +contract, You are granted the Licensed Rights in consideration of Your \ +acceptance of these terms and conditions, and the Licensor grants You \ +such rights in consideration of benefits the Licensor receives from \ +making the Licensed Material available under these terms and \ +conditions. + +### Section 1 -- Definitions. + +a. Adapted Material means material subject to Copyright and Similar \ + Rights that is derived from or based upon the Licensed Material \ + and in which the Licensed Material is translated, altered, \ + arranged, transformed, or otherwise modified in a manner requiring \ + permission under the Copyright and Similar Rights held by the \ + Licensor. For purposes of this Public License, where the Licensed \ + Material is a musical work, performance, or sound recording, \ + Adapted Material is always produced where the Licensed Material is \ + synched in timed relation with a moving image. +b. Adapter's License means the license You apply to Your Copyright \ + and Similar Rights in Your contributions to Adapted Material in \ + accordance with the terms and conditions of this Public License. \ +c. BY-SA Compatible License means a license listed at \ + creativecommons.org/compatiblelicenses, approved by Creative \ + Commons as essentially the equivalent of this Public License. \ +d. Copyright and Similar Rights means copyright and/or similar rights \ + closely related to copyright including, without limitation, \ + performance, broadcast, sound recording, and Sui Generis Database \ + Rights, without regard to how the rights are labeled or \ + categorized. For purposes of this Public License, the rights \ + specified in Section 2(b)(1)-(2) are not Copyright and Similar \ + Rights. +e. Effective Technological Measures means those measures that, in the \ + absence of proper authority, may not be circumvented under laws \ + fulfilling obligations under Article 11 of the WIPO Copyright \ + Treaty adopted on December 20, 1996, and/or similar international \ + agreements. +f. Exceptions and Limitations means fair use, fair dealing, and/or \ + any other exception or limitation to Copyright and Similar Rights \ + that applies to Your use of the Licensed Material. +g. License Elements means the license attributes listed in the name \ + of a Creative Commons Public License. The License Elements of this \ + Public License are Attribution and ShareAlike. +h. Licensed Material means the artistic or literary work, database, \ + or other material to which the Licensor applied this Public \ + License. +i. Licensed Rights means the rights granted to You subject to the \ + terms and conditions of this Public License, which are limited to \ + all Copyright and Similar Rights that apply to Your use of the \ + Licensed Material and that the Licensor has authority to license. \ +j. Licensor means the individual(s) or entity(ies) granting rights \ + under this Public License. +k. Share means to provide material to the public by any means or \ + process that requires permission under the Licensed Rights, such \ + as reproduction, public display, public performance, distribution, \ + dissemination, communication, or importation, and to make material \ + available to the public including in ways that members of the \ + public may access the material from a place and at a time \ + individually chosen by them. +l. Sui Generis Database Rights means rights other than copyright \ + resulting from Directive 96/9/EC of the European Parliament and of \ + the Council of 11 March 1996 on the legal protection of databases, \ + as amended and/or succeeded, as well as other essentially \ + equivalent rights anywhere in the world. +m. You means the individual or entity exercising the Licensed Rights \ + under this Public License. Your has a corresponding meaning. + +### Section 2 -- Scope. + +a. License grant. + 1. Subject to the terms and conditions of this Public License, \ + the Licensor hereby grants You a worldwide, royalty-free, \ + non-sublicensable, non-exclusive, irrevocable license to \ + exercise the Licensed Rights in the Licensed Material to: + a. reproduce and Share the Licensed Material, \ + in whole or in part; and + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where \ + Exceptions and Limitations apply to Your use, this Public \ + License does not apply, and You do not need to comply with \ + its terms and conditions. + 3. Term. The term of this Public License is specified in Section 6(a). + 4. Media and formats; technical modifications allowed. The \ + Licensor authorizes You to exercise the Licensed Rights in \ + all media and formats whether now known or hereafter created, \ + and to make technical modifications necessary to do so. The \ + Licensor waives and/or agrees not to assert any right or \ + authority to forbid You from making technical modifications \ + necessary to exercise the Licensed Rights, including \ + technical modifications necessary to circumvent Effective \ + Technological Measures. For purposes of this Public License, \ + simply making modifications authorized by this Section 2(a) \ + (4) never produces Adapted Material. + 5. Downstream recipients. + a. Offer from the Licensor -- Licensed Material. Every \ + recipient of the Licensed Material automatically \ + receives an offer from the Licensor to exercise the \ + Licensed Rights under the terms and conditions of this \ + Public License. + b. Additional offer from the Licensor -- Adapted Material. \ + Every recipient of Adapted Material from You \ + automatically receives an offer from the Licensor to \ + exercise the Licensed Rights in the Adapted Material \ + under the conditions of the Adapter's License You apply. + c. No downstream restrictions. You may not offer or impose \ + any additional or different terms or conditions on, or \ + apply any Effective Technological Measures to, the \ + Licensed Material if doing so restricts exercise of the \ + Licensed Rights by any recipient of the Licensed \ + Material. + 6. No endorsement. Nothing in this Public License constitutes or \ + may be construed as permission to assert or imply that You \ + are, or that Your use of the Licensed Material is, connected \ + with, or sponsored, endorsed, or granted official status by, \ + the Licensor or others designated to receive attribution as \ + provided in Section 3(a)(1)(A)(i). +b. Other rights. + 1. Moral rights, such as the right of integrity, are not \ + licensed under this Public License, nor are publicity, \ + privacy, and/or other similar personality rights; however, to \ + the extent possible, the Licensor waives and/or agrees not to \ + assert any such rights held by the Licensor to the limited \ + extent necessary to allow You to exercise the Licensed \ + Rights, but not otherwise. + 2. Patent and trademark rights are not licensed under this \ + Public License. + 3. To the extent possible, the Licensor waives any right to \ + collect royalties from You for the exercise of the Licensed \ + Rights, whether directly or through a collecting society \ + under any voluntary or waivable statutory or compulsory \ + licensing scheme. In all other cases the Licensor expressly \ + reserves any right to collect such royalties. + +### Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the \ +following conditions. + +a. Attribution. + 1. If You Share the Licensed Material (including in modified \ + form), You must: + a. retain the following if it is supplied by the Licensor \ + with the Licensed Material: + i. identification of the creator(s) of the Licensed \ + Material and any others designated to receive \ + attribution, in any reasonable manner requested by \ + the Licensor (including by pseudonym if \ + designated); + ii. a copyright notice; + iii. a notice that refers to this Public License; + iv. a notice that refers to the disclaimer of \ + warranties; + v. a URI or hyperlink to the Licensed Material to the \ + extent reasonably practicable; + b. indicate if You modified the Licensed Material and \ + retain an indication of any previous modifications; and + c. indicate the Licensed Material is licensed under this \ + Public License, and include the text of, or the URI or \ + hyperlink to, this Public License. + 2. You may satisfy the conditions in Section 3(a)(1) in any \ + reasonable manner based on the medium, means, and context in \ + which You Share the Licensed Material. For example, it may be \ + reasonable to satisfy the conditions by providing a URI or \ + hyperlink to a resource that includes the required \ + information. + 3. If requested by the Licensor, You must remove any of the \ + information required by Section 3(a)(1)(A) to the extent \ + reasonably practicable. +b. ShareAlike. + In addition to the conditions in Section 3(a), if You Share \ + Adapted Material You produce, the following conditions also apply. \ + 1. The Adapter's License You apply must be a Creative Commons \ + license with the same License Elements, this version or \ + later, or a BY-SA Compatible License. + 2. You must include the text of, or the URI or hyperlink to, the \ + Adapter's License You apply. You may satisfy this condition \ + in any reasonable manner based on the medium, means, and \ + context in which You Share Adapted Material. + 3. You may not offer or impose any additional or different terms \ + or conditions on, or apply any Effective Technological \ + Measures to, Adapted Material that restrict exercise of the \ + rights granted under the Adapter's License You apply. + +### Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that \ +apply to Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right \ + to extract, reuse, reproduce, and Share all or a substantial \ + portion of the contents of the database; +b. if You include all or a substantial portion of the database \ + contents in a database in which You have Sui Generis Database \ + Rights, then the database in which You have Sui Generis Database \ + Rights (but not its individual contents) is Adapted Material, \ + including for purposes of Section 3(b); and +c. You must comply with the conditions in Section 3(a) if You Share \ + all or a substantial portion of the contents of the database. + +> For the avoidance of doubt, this Section 4 supplements and does not \ +> replace Your obligations under this Public License where the Licensed \ +> Rights include other Copyright and Similar Rights. \ + +### Section 5 -- Disclaimer of Warranties and Limitation of Liability. + +a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE \ + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS \ + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF \ + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, \ + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, \ + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR \ + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, \ + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT \ + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT \ + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. +b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE \ + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, \ + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, \ + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, \ + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR \ + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN \ + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR \ + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR \ + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. +c. The disclaimer of warranties and limitation of liability provided \ + above shall be interpreted in a manner that, to the extent \ + possible, most closely approximates an absolute disclaimer and \ + waiver of all liability. + +### Section 6 -- Term and Termination. + +a. This Public License applies for the term of the Copyright and \ + Similar Rights licensed here. However, if You fail to comply with \ + this Public License, then Your rights under this Public License \ + terminate automatically. +b. Where Your right to use the Licensed Material has terminated under \ + Section 6(a), it reinstates: + 1. automatically as of the date the violation is cured, provided \ + it is cured within 30 days of Your discovery of the \ + violation; or + 2. upon express reinstatement by the Licensor. + > For the avoidance of doubt, this Section 6(b) does not affect any \ + > right the Licensor may have to seek remedies for Your violations \ + > of this Public License. +c. For the avoidance of doubt, the Licensor may also offer the \ + Licensed Material under separate terms or conditions or stop \ + distributing the Licensed Material at any time; however, doing so \ + will not terminate this Public License. +d. Sections 1, 5, 6, 7, and 8 survive termination of this Public \ + License. + +### Section 7 -- Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different \ + terms or conditions communicated by You unless expressly agreed. \ +b. Any arrangements, understandings, or agreements regarding the \ + Licensed Material not stated herein are separate from and \ + independent of the terms and conditions of this Public License. + +## Section 8 -- Interpretation. + +a. For the avoidance of doubt, this Public License does not, and \ + shall not be interpreted to, reduce, limit, restrict, or impose \ + conditions on any use of the Licensed Material that could lawfully \ + be made without permission under this Public License. +b. To the extent possible, if any provision of this Public License is \ + deemed unenforceable, it shall be automatically reformed to the \ + minimum extent necessary to make it enforceable. If the provision \ + cannot be reformed, it shall be severed from this Public License \ + without affecting the enforceability of the remaining terms and \ + conditions. +c. No term or condition of this Public License will be waived and no \ + failure to comply consented to unless expressly agreed to by the \ + Licensor. +d. Nothing in this Public License constitutes or may be interpreted \ + as a limitation upon, or waiver of, any privileges and immunities \ + that apply to the Licensor or You, including from the legal \ + processes of any jurisdiction or authority. + +--- + +Creative Commons is not a party to its public \ +licenses. Notwithstanding, Creative Commons may elect to apply one of \ +its public licenses to material it publishes and in those instances \ +will be considered the “Licensor.” The text of the Creative Commons \ +public licenses is dedicated to the public domain under the CC0 Public \ +Domain Dedication. Except for the limited purpose of indicating that \ +material is shared under a Creative Commons public license or as \ +otherwise permitted by the Creative Commons policies published at \ +creativecommons.org/policies, Creative Commons does not authorize the \ +use of the trademark "Creative Commons" or any other trademark or logo \ +of Creative Commons without its prior written consent including, \ +without limitation, in connection with any unauthorized modifications \ +to any of its public licenses or any other arrangements, \ +understandings, or agreements concerning use of licensed material. For \ +the avoidance of doubt, this paragraph does not form part of the \ +public licenses. + +Creative Commons may be contacted at . diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md new file mode 100644 index 0000000..beb865c --- /dev/null +++ b/docs/SUMMARY.md @@ -0,0 +1,6 @@ +# Summary + +- [Chapter 1](./Chapter_1.md) +- [Chapter 2](./Chapter_2.md) +- [Chapter 3](./Chapter_3.md) +- [Chapter 4](./Chapter_4.md) diff --git a/docs/TABLE_OF_CONTENT.md b/docs/TABLE_OF_CONTENT.md new file mode 100644 index 0000000..6843020 --- /dev/null +++ b/docs/TABLE_OF_CONTENT.md @@ -0,0 +1,22 @@ +# Content + +- [Chapter 1](./Chapter_1.md) + - [Code of Conduct](./CODE_OF_CONDUCT.md) + - [License](./LICENSE.md) + - [How To Contribute](./CONSTRIBUTION.md) +- [Chapter 2](./Chapter_2.md) + - [Welcome](./0-2024-0/ENTRY.md) + - [Introduction](./0-2024-0/introduction) + - [Convention](./0-2024-0/convention.md) +- [Chapter 3](./Chapter_3.md) + - [On-Hand](./0-2024-0/built-in_on-hand.md) + - [Basic Types](./0-2024-0/built-in_type.md) + - [Data Structure](./0-2024-0/built-in_datastruct.md) + - [Flow Control](./0-2024-0/built-in_flow-constrol.md) + - [Operation](./0-2024-0/built-in_operation.md) +- [Chapter 4](./Chapter_4.md) + - [A Pinch of Sugar](./0-2024-0/built-in_syntactic-sugar.md) + - [Another Pinch of Sugar](./0-2024-0/built-in_more-sugar.md) + - [Tips and Tricks](./0-2024-0/tips-and-tricks.md) + - [Appendice](./0-2024-0/appendice.md) + - [A](./0-2024-0/appendix-a.md) diff --git a/docs/html/index.html b/docs/html/index.html deleted file mode 100644 index 0d306f1..0000000 --- a/docs/html/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - Specification - minimaLang - - -
-

Specification minimaLang

-

Work in Progress.

-
- - diff --git a/docs/index.md b/docs/index.md index 1ebf65c..717a91d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,2 +1,8 @@ # minimaLang A programming language with minimal syntax. + +- [License](./LICENSE.md) + - [as RDF](./License.rdf) +- [Code of Conduct](./CODE_OF_CONDUCT.md) +- [How to Contribut](./CONTRIBUTION.md) +- [Specification](./0-2024-0/ENTRY.md) diff --git a/docs/md/License.md b/docs/md/License.md deleted file mode 100644 index f721089..0000000 --- a/docs/md/License.md +++ /dev/null @@ -1,8 +0,0 @@ -# License - minimaLang-Specification - -![ ](https://licensebuttons.net/i/l/by-sa/eeeeee/66/22/11/88x31.png) - -**minimaLang-Specification** © (since) 2024 by Sara Tasche is \ -licensed under _Creative Commons Attribution-ShareAlike 4.0 International_; \ -from now on and every further version. \ -To view a copy of this license, visit . diff --git a/docs/md/built-in_datastruct.md b/docs/md/built-in_datastruct.md deleted file mode 100644 index 93f6eb8..0000000 --- a/docs/md/built-in_datastruct.md +++ /dev/null @@ -1,98 +0,0 @@ -# Data Structure - -- [Pair](#pair) -- [Sequence](#sequence) - - [of Value](#of-value) - - [of Expression](#of-expression) - -## Pair - -| Token | -| :---------: | -| `(` `;` `)` | - -A pair consists of _key_ and _value_. \ -The _key_ must be of type _[Constant](built-in_type#constant)_. - -| Syntax | -| :-----: | -| `(` | -| _Key_ | -| _Value_ | -| `;` | -| ... | -| `)` | - -```minimaL -( 'A 31 ; 'B 21 ) : C -C 'A N : -C 'B M : -``` - -- `N` answers `32` -- `M` answers `21` - -## Sequence - -| Token | -| :--------: | -| `[` .. `]` | -| `{` .. `}` | - -- [Value](#of-value) -- [Expression](#of-expression) - -### of Value - -| Type | Token | -| :---: | :------: | -| Begin | `(` | -| Infix | _Values_ | -| End | `)` | - -- _Valid_ - 1. `[ 1 2 3 ]` - 2. `( [ 1 2 3 ] [ A B C ] )` - 3. `( [ 1 A 5 ] )` -- _Invalid_ - 1. `( 1 2 3 )` - 2. `( )` - 3. `[ ]` - -```minimaL -A 1 : -B 2 : -C 3 : -> [ A B C ] + > O : -``` - -`O` answers `6` - -```minimaL -D 1 : -E 2 : -F 3 : -G 2 : -[ D E ] < + / > -``` - -### of Expression - -| Type | Token | -| :---: | :----------: | -| Begin | `{` | -| Infix | _Expression_ | -| End | `}` | - -```minimaL -{ - A 1 : - B 2 : -} -``` - -```minimaL -.. L { A 1 : } -``` - -See [Label](flow-control#label) diff --git a/docs/md/introduction.md b/docs/md/introduction.md deleted file mode 100644 index de17f20..0000000 --- a/docs/md/introduction.md +++ /dev/null @@ -1,39 +0,0 @@ -# Introduction - -- [Motivation](#motivation) -- [Goal](#goal) -- [No-Goal](#no-goal) -- _Specification_ - - [Lastest](specification) - - Appendices - - [A](appendix-a.md) - -## Disclaimer - -Every document is licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). \ -See [License](License). - -## Motivation - -I had been thinking about developing my own programming language for some time. \ -I had made attempts before, but never really realised them. \ -Now it should be different. - -The reason for the light syntax and the minimalist function is \ -that I want to build on this programming language. \ -Mainly as an intermediate language. - -## Goal - -I **want to** ... - -1. a simple, minimalistic, syntax -2. with minimalistic function - - with little syntax sugar, if needed (see 3.) -3. easy to understand, easy to learn - -## No-Goal - -I do **not want** to ... - -- write an all-purposes programming language diff --git a/docs/md/main.md b/docs/md/main.md deleted file mode 100644 index 87822bf..0000000 --- a/docs/md/main.md +++ /dev/null @@ -1,30 +0,0 @@ -# Specification for minimaLang - -_minimaLang_, or _minimaL_ for short, is a stack-based programming language with minimal syntax. \ -The syntax is reverse polish notation (RPN). - -- [Content](#content) -- [Implementation](#implementation) -- [Notes](#notes) - -## Content - -- [Specification](specification) -- [Appendix A](appendix-a) - -- [Introduction](introduction) - - [Motivation](introduction#motivation) - - [Goal](introduction#goal) - - [No Goal](introduction#no-goal) - -- [Syntax Convention](syntax-convention) -- [Tips and Tricks](tips-and-tricks) - -## Implementation - -None known. -Own implementation comming later. - -## Notes - -_Now or never_. diff --git a/docs/md/operation.md b/docs/md/operation.md deleted file mode 100644 index 391352b..0000000 --- a/docs/md/operation.md +++ /dev/null @@ -1,135 +0,0 @@ -# Operations - -See [Convention](convention) - -- [Stack](#stack) -- [Logic](#logic) -- [Comparsion](#comparsion) -- [Math](#math) - -## Stack - -| Token | -| :----------------- | -| `^`, `.`, `~`, `:` | - -- Pick-up a value ([`^` 'Pick'](#pick-and-put)) -- Put-down a value ([`.` 'Put'](#pick-and-put)) -- Discard a value ([`~` 'Drop'](#drop)) -- Pass a value ([`:` 'Pass'](#pass)) - -### Pick and Put - -_Pick_ takes a value, \ -and _Put_ place it on the stack. - -_Pick_ and _Put_ are mostly used implicitly. \ - -One example is the mathematical operation - -```minimaL -2 3 + -``` - -The operation _Addition_ `+` causes the values 2 and 3 ... - -- to be picked `^` from the stack -- applied to the function _Addition_ `+` -- and its result is placed on `.` the stack. - -### Drop - -_Drop_ discards a value. \ -It deletes it from the stack. - -```minimaL -2 ~ 3 3 + -``` - -- Stack - - `2` - - `~` - - [`0`] - - `3` - - `3` - - `+` - - [`6`] - -The answer `6` is on the stack. - -### Pass - -_Pass_ causes a value to be stored '_on-hand_', \ -which is like (but not equal to) a named _variable_. - -```minimaL -6 A : -``` - -The _hand_ called `A` contains the answer `6`. - -There are two type of _hands_ ... - -- a value _bearer_ -- and a value _accumulator_ (also called a _collector_) - -_On-hand_ will be discussed later. - -## Logic - -| Token | Syntax | -| :--------: | :---------------------------------------: | -| `'+`, `'/` | _Operand1_ _Operand2_ **Binary-Operator** | -| `'-` | _Operand_ **Unary-Operator** | - -- `'+` And -- `'/` Or -- `'-` Not - -## Comparsion - -| Token | Syntax | -| :---: | :---------------------------------------: | -| `=` | _Operand1_ _Operand2_ **Binary-Operator** | - -```minimaL -2 A : -2 B : -A B = C : -``` - -`C` _Answers_ `1`. - -```minimaL -2 A : -1 B : -A B - C : -C 0 = D : -D B - E : -``` - -- Answers; Step-by-Step - 1. _Pass Values to_ `A` and `B` - - `A` _Contains_ `2` - - `B` _Contains_ `1` - 2. _Substract `B` from `A`_; _Answer_ is `1` - - _Pass_ _Answer_ to `C`; - 3. _Compare `C` with `0`; _Answer_ is_ `-1` - - _Pass_ _Answer_ to `D`; - 4. _Substract_ `B` from `D`; - - _Pass_ _Answer_ to `E` - 5. _Answer_ is `0` - -## Math - -| Token | Syntax | -| :----------------: | :---------------------------------------: | -| `+`, `-`, `*`, `/` | _Operand1_ _Operand2_ **Binary-Operator** | -| `{` .. `}` | _Operand_ { _Unary-Operator_ } | - -```minimaL -2 3 + 2 * -``` - -Is equivalent to `(2 + 3) * 2`. \ -_Answer_ is `10`. diff --git a/docs/md/specification-version-0-2024-0.md b/docs/md/specification-version-0-2024-0.md deleted file mode 100644 index 8d6d64a..0000000 --- a/docs/md/specification-version-0-2024-0.md +++ /dev/null @@ -1,27 +0,0 @@ -# Specification - -| Version | Status | -| :------: | :------ | -| 0.2024.0 | _DRAFT_ | - -- **[Show Syntax Convention](syntax-convention)** - -- [Operation](built-in_operation) - - [Stack](built-in_operation#stack) - - [Logic](built-in_operation#logic) - - [Math](built-in_operation#math) -- [Type](built-in_type) - - [Variable](built-in_type#variable) - - [Literal](built-in_type#literal) - - [Character](built-in_type#character) -- [Data Struct](built-in_datastruct) - - [Pair](built-in_datastruct#pair) - - [Sequence](built-in_datastruct#sequence) - - [of Value](built-in_datastruct#of-value) - - [of Expression](built-in_datastruct#of-expression) -- [Flow Control](flow-control) - - [Loop](flow-control#loop) - - [Branch](flow-control#branch) - - [Label](flow-control#label) - - [Define](flow-control#define) - - [Jump](flow-control#jump) diff --git a/docs/md/specification.md b/docs/md/specification.md deleted file mode 100644 index 088d6e2..0000000 --- a/docs/md/specification.md +++ /dev/null @@ -1,8 +0,0 @@ -# Specification - -- [Draft](#draft) - -## Draft - -- **0.2024.0** - - [Show](specification-version-0-2024-0.md) diff --git a/docs/md/syntax-convention.md b/docs/md/syntax-convention.md deleted file mode 100644 index 476a753..0000000 --- a/docs/md/syntax-convention.md +++ /dev/null @@ -1,14 +0,0 @@ -# Syntax - -| Syntax | -| :------------------: | -| <1> `'` | -| <1..*>_Identifier_ | -| (<0..1>`Dash`) | -| (<0..*>_Identifier_) | -| (<0..1>`Underscore`) | - -1. Symbols enclosed in round brackets are optional. -2. One number enclosed in `<` `>` shows the mandatory length. -3. The Symbol `..` between numbers indicates the permitted frequency. - - `..*` indicates an unlimited frequency. diff --git a/docs/snippets/Licence.html b/docs/snippets/Licence.html deleted file mode 100644 index 976c974..0000000 --- a/docs/snippets/Licence.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - Licence - minimaLang Specification - - - -

- - minimaLang Specification by - - Sara Tasche is licensed under - - Creative Commons Attribution-ShareAlike 4.0 International
- - - -
-

- - - diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..fa0b816 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,13 @@ +{ + "name": "Specification", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/stimulus-store": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/stimulus-store/-/stimulus-store-0.0.3.tgz", + "integrity": "sha512-SQGdf2BZpItO0g1jW1vwwA9ZRvlymoQJQe9r8pfTkZ+NsPgkXR5uO8y8Ue+tQDZa8DSAD3RZ1Io2YuDVnBygJQ==", + "license": "MIT" + } + } +} diff --git a/node_modules/stimulus-store/LICENSE.md b/node_modules/stimulus-store/LICENSE.md new file mode 100644 index 0000000..ef5b90c --- /dev/null +++ b/node_modules/stimulus-store/LICENSE.md @@ -0,0 +1,19 @@ +# Copyright (c) 2023 Omar Luqman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/stimulus-store/README.md b/node_modules/stimulus-store/README.md new file mode 100644 index 0000000..8a32b0d --- /dev/null +++ b/node_modules/stimulus-store/README.md @@ -0,0 +1,155 @@ + + +

+ + Stimulus Store Logo + +

+ +
+ + [![GitHub package.json version](https://img.shields.io/github/package-json/v/omarluq/stimulus-store)](https://github.com/omarluq/stimulus-store) + [![GitHub Actions](https://github.com/omarluq/stimulus-store/actions/workflows/test.yml/badge.svg)](https://github.com/omarluq/stimulus-store/actions/workflows/test.yml) + [![Netlify Status](https://api.netlify.com/api/v1/badges/f2b2e5e9-67f0-4e3f-b6b5-8e1310ea4ad7/deploy-status)](https://netlify.com) + [![Last Commit](https://img.shields.io/github/last-commit/omarluq/stimulus-store)](https://github.com/omarluq/stimulus-store/commits/main) + [![Commit Activity](https://img.shields.io/github/commit-activity/m/omarluq/stimulus-store)](https://github.com/omarluq/stimulus-store/graphs/commit-activity) + [![All Contributors](https://img.shields.io/github/all-contributors/omarluq/stimulus-store)](https://github.com/omarluq/stimulus-store/graphs/contributors) + [![Pull Requests](https://img.shields.io/github/issues-pr/omarluq/stimulus-store)](https://github.com/omarluq/stimulus-store/pulls) + [![Closed Pull Requests](https://img.shields.io/github/issues-pr-closed-raw/omarluq/stimulus-store)](https://github.com/omarluq/stimulus-store/pulls?q=is%3Apr+is%3Aclosed) + [![GitHub issues](https://img.shields.io/github/issues/omarluq/stimulus-store)](https://github.com/omarluq/stimulus-store/issues) + [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/omarluq/stimulus-store) + [![GitHub stars](https://img.shields.io/github/stars/omarluq/stimulus-store?style=flat)](https://github.com/omarluq/stimulus-store/stargazers) + [![GitHub forks](https://img.shields.io/github/forks/omarluq/stimulus-store?style=flat)](https://github.com/omarluq/stimulus-store/network/members) + [![GitHub watchers](https://img.shields.io/github/watchers/omarluq/stimulus-store?style=flat)](https://github.com/omarluq/stimulus-store/watchers) + [![Type Definitions](https://img.shields.io/npm/types/stimulus-store)](https://www.typescriptlang.org) + [![BiomeJS](https://img.shields.io/badge/-BiomeJs-60A5FA?logo=biome&logoColor=white)](https://biomejs.dev) + [![Maintainability](https://api.codeclimate.com/v1/badges/a99a88d28ad37a79dbf6/maintainability)](https://codeclimate.com/github/omarluq/stimulus-store/maintainability) + [![Test Coverage](https://api.codeclimate.com/v1/badges/a99a88d28ad37a79dbf6/test_coverage)](https://codeclimate.com/github/omarluq/stimulus-store/test_coverage) + [![npm version](https://badge.fury.io/js/stimulus-store.svg)](https://npmjs.com/package/stimulus-store) + [![npm downloads](https://img.shields.io/npm/dm/stimulus-store.svg)](https://npmjs.com/package/stimulus-store) + [![Bundle Size](https://img.shields.io/bundlephobia/minzip/stimulus-store@0.0.2)](https://bundlephobia.com/result?p=stimulus-store@0.0.2) + [![Bundle Min](https://img.shields.io/bundlephobia/min/stimulus-store@0.0.2)](https://bundlephobia.com/result?p=stimulus-store@0.0.2) + [![Tree-shaking size](https://badgen.net/bundlephobia/tree-shaking/stimulus-store@0.0.2)](https://bundlephobia.com/result?p=stimulus-store@0.0.2) + [![Top Language](https://img.shields.io/github/languages/top/omarluq/stimulus-store)](https://github.com/omarluq/stimulus-store) + [![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/omarluq/stimulus-store)](https://github.com/omarluq/stimulus-store) + [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/omarluq/stimulus-store) + [![Dependabot](https://badgen.net/github/dependabot/omarluq/stimulus-store)](https://dependabot.com) + [![Made with Love](https://img.shields.io/badge/Made%20with-Love-ff69b4.svg)](https://github.com/omarluq/stimulus-store) + [![](https://dcbadge.vercel.app/api/server/ScU4JKgxaU?style=flat)](https://discord.gg/ScU4JKgxaU) + +
+ +
+ +

+ Ultra lightweight state management for your Stimulus powered web applications. +

+ +
+ +- **Create and manage global state with ease.** 🔄 +- **Share state between different controllers effortlessly using a unified, atomic `Store` class.** 🔀 +- **1.04KB Minified and Brotlied** 🪶 + +## Installation + +### With a build system + +Install with [npm](https://www.npmjs.com/): + +```sh +npm install stimulus-store +``` + +Install with [yarn](https://yarnpkg.com): + +```sh +yarn add stimulus-store +``` + +### UMD + +If you prefer not to use a build system, you can load `stimulus-store` in a ` + + + + +
+ + +``` + +## Documentation + +complete documentation on Stimulus Store, including guides, API details, and more can be found on [www.stimulus-store.com](https://www.stimulus-store.com). + +## Contributors ✨ + +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + + + + + + + + + + + + + + + + +
Tomas Caraccia
Tomas Caraccia

💻 ⚠️ 📖 🚧 👀 💬
Omar Luq
Omar Luq

💻 ⚠️ 📖 🚧 👀 💬
+ + Add your contributions + +
+ + + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! + +
+ +## License + +This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details. diff --git a/node_modules/stimulus-store/dist/bundle.cjs.js b/node_modules/stimulus-store/dist/bundle.cjs.js new file mode 100644 index 0000000..7ec19a0 --- /dev/null +++ b/node_modules/stimulus-store/dist/bundle.cjs.js @@ -0,0 +1,2 @@ +"use strict";function e(e,t=!1){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,((e,r)=>0!==r||t?e.toUpperCase():e.toLowerCase())).replace(/\s+/g,"")}const t={String:String,Number:Number,Array:Array,Object:Object,Boolean:Boolean};class r{constructor(e,t){this.name=e,this.subscribers=new Set,this.type=t}async set(e,t={filter:()=>!0}){if(e instanceof Promise)return this.resolvePromise(e,t);if(e===this.get())return;const r="function"==typeof e?e(this.get()):e;!function(e,t){if(Object.getPrototypeOf(e).constructor!==t)throw new Error(`Value '${e}' must be of type ${t.name}`)}(r,this.type),this.setInitialValue(r),this.setValue(r),this.notifySubscribers(t)}get(){return this.value}resetValue(){this.setValue(this.initialValue)}setValue(e){this.value=e}setInitialValue(e){void 0===this.value&&(this.initialValue=e)}subscribe(e){return this.subscribers.add(e),e(this.get()),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}getSubscription(){return{subscribe:e=>this.subscribe(e)}}notifySubscribers(e){Array.from(this.subscribers).filter((()=>e.filter(this.get()))).forEach((e=>e(this.get())))}async resolvePromise(e,t){try{const r=await e;this.set(r,t)}catch(e){!function(e){throw new Error(`Failed to resolve promise:\n${e}`)}(e)}}}exports.createStore=function(e){const s=e.name,o=e.type,n=e.initialValue;!function(e){if(void 0===e)throw new Error("Store must be initialized with a value")}(n),function(e){if("string"!=typeof e)throw new Error("Store name must be of Type string")}(s),function(e){if("function"!=typeof t[e])throw new Error(`Invalid type: ${e}`)}(o.name);const i=Symbol(s),a=new r(i,o);return a.set(n).catch((e=>function(e){if(e instanceof Error)throw new Error(`Failed to create store: ${e.message}`);throw new Error("An unknown error occurred while creating the store")}(e))),a},exports.useStore=function(t){const r=t.constructor?.stores,s=[];!function(e){if(!e)throw new Error("'useStore' was called on a controller without a 'stores' static property. The 'stores' property is undefined.");if(!Array.isArray(e))throw new Error("'useStore' was called on a controller with a 'stores' static property that is not an array.");if(0===e.length)throw new Error("'useStore' was called on a controller with an empty 'stores' static property. The 'stores' array should contain at least one store.")}(r),r?.forEach((r=>{const o=r.name.toString().slice(7,-1),n=e(o),i=`on${e(o,!0)}Update`,a=t[i],c=r.getSubscription();if(a){const r=e=>{a.call(t,e)},n=`update${e(o,!0)}`;t[n]=r,s.push(c.subscribe(r))}const u=`set${e(o,!0)}Value`;t[u]=e=>{r.set(e)};const l=`reset${e(o,!0)}`;t[l]=()=>{r.resetValue()};const h=`${n}Value`;Object.defineProperty(t,h,{get:()=>r.get(),enumerable:!0,configurable:!0});let f=!1;const b=new Proxy(r,{get:(e,t,r)=>(f=function(e,t){return t||!0}(0,f),Reflect.get(e,t,r))});Object.defineProperty(t,n,{get:()=>b,enumerable:!0,configurable:!0})}));const o=t.disconnect.bind(t);t.disconnect=()=>{s.forEach((e=>{e&&e()})),o()}}; +//# sourceMappingURL=bundle.cjs.js.map diff --git a/node_modules/stimulus-store/dist/bundle.cjs.js.map b/node_modules/stimulus-store/dist/bundle.cjs.js.map new file mode 100644 index 0000000..bfe9eff --- /dev/null +++ b/node_modules/stimulus-store/dist/bundle.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundle.cjs.js","sources":["../src/utils/camelize.ts","../src/store/storeValuesTypeMap.ts","../src/store/store.ts","../src/errors/storeErrorHandlers.ts","../src/store/createStore.ts","../src/errors/createStoreErrorHandlers.ts","../src/hooks/useStore.ts","../src/errors/useStoreErrorHandlers.ts","../src/errors/useStoreWarningHandlers.ts"],"sourcesContent":["export function camelize(str: string, firstCharUppercase = false): string {\n const pattern1: RegExp = /(?:^\\w|[A-Z]|\\b\\w)/g\n const pattern2: RegExp = /\\s+/g\n const result: string = str\n .replace(pattern1, (word, index) =>\n index === 0 && !firstCharUppercase\n ? word.toLowerCase()\n : word.toUpperCase(),\n )\n .replace(pattern2, '')\n return result\n}\n","import type { TypeKey } from '../types/typeKey'\n\n/**\n * A mapping from type names to their corresponding constructor types.\n * - Allows type checking values at runtime.\n * - Allows the use of the following types: String, Number, Array, Object, Boolean.\n * - Each type has its own constructor type: StringConstructor, NumberConstructor, ArrayConstructor, ObjectConstructor, BooleanConstructor.\n * - TypeKey is a union of all the constructor types.\n * @type {Record}\n *\n */\n\nexport const typeMap: Record = {\n String: String,\n Number: Number,\n Array: Array,\n Object: Object,\n Boolean: Boolean,\n}\n","import type {\n CurrentValueCallback,\n NotifySubscriberOptions,\n SetOptions,\n StoreValue,\n Subscription,\n TypeKey,\n UnsubscribeFunction,\n UpdateMethod,\n} from 'types'\nimport { checkValue, handlePromiseError } from '../errors/storeErrorHandlers'\n/**\n * @template T The type of the value that the store holds.\n * Store Class Explanation:\n *\n * The `Store` class is a versatile class for managing and subscribing to data updates in JavaScript applications.\n * It provides a structured way to store data and notify subscribers when the data changes.\n *\n * Key Features:\n * - Generic Class: Can work with different types of data (specified when creating an instance).\n * - Constructor: Sets the initial value of the store.\n * - `set` Method: Updates the value and notifies subscribers.\n * - `get` Method: Gets the current value.\n * - `subscribe` Method: Subscribes to updates and calls a callback function when data changes.\n * - `unsubscribe` Method: Removes a subscription.\n * - `notifySubscribers` Method: Notifies subscribers when data changes.\n */\n\nexport class Store {\n readonly name: symbol\n private value!: StoreValue\n private initialValue!: StoreValue\n private subscribers: Set\n private type: TypeKey\n\n /**\n * Creates a new store.\n *\n * @param {symbol} name - The name of the store.\n * @param {TypeKey} type - The type of the store's value.\n */\n constructor(name: symbol, type: TypeKey) {\n this.name = name\n this.subscribers = new Set()\n this.type = type\n }\n\n /**\n * Sets the value of the store and notifies subscribers.\n *\n * @param {T | CurrentValueCallback | Promise} newValue - The new value.\n * @param {SetOptions} [options={ filter: () => true }] - The options for setting the value.\n */\n async set(\n newValue:\n | StoreValue\n | CurrentValueCallback\n | Promise,\n options: SetOptions = { filter: () => true },\n ) {\n if (newValue instanceof Promise)\n return this.resolvePromise(newValue, options)\n if (newValue === this.get()) return\n const finalValue: StoreValue =\n typeof newValue === 'function'\n ? (newValue as CurrentValueCallback)(this.get())\n : newValue\n checkValue(finalValue, this.type)\n this.setInitialValue(finalValue)\n this.setValue(finalValue)\n this.notifySubscribers(options)\n }\n\n /**\n * Gets the current value of the store.\n *\n * @returns {StoreValue} The current value.\n */\n get(): StoreValue {\n return this.value\n }\n\n /**\n * Resets the store to its initial value.\n */\n resetValue(): void {\n this.setValue(this.initialValue)\n }\n\n private setValue(value: StoreValue): void {\n this.value = value\n }\n\n private setInitialValue(value: StoreValue): void {\n if (this.value === undefined) this.initialValue = value\n }\n\n /**\n * Subscribes to the store.\n *\n * @param {UpdateMethod} callback - The function to call when the store's value changes.\n * @returns {UnsubscribeFunction} A function that unsubscribes the callback.\n */\n private subscribe(callback: UpdateMethod): UnsubscribeFunction {\n this.subscribers.add(callback)\n callback(this.get()) // Immediate call for initial value\n return () => this.unsubscribe(callback) // Return an unsubscribe function\n }\n\n /**\n * Unsubscribes from the store.\n *\n * @param {UpdateMethod} callback - The function to unsubscribe.\n */\n private unsubscribe(callback: UpdateMethod) {\n this.subscribers.delete(callback)\n }\n\n /**\n * Gets a subscription object with subscribe, when invoked subscribe returns an unsubscribe function.\n *\n * @returns {Subscription} A subscription object.\n */\n public getSubscription(): Subscription {\n return {\n subscribe: (callback: UpdateMethod) => this.subscribe(callback),\n }\n }\n\n private notifySubscribers(options: NotifySubscriberOptions) {\n Array.from(this.subscribers)\n .filter(() => options.filter(this.get()))\n .forEach((callback) => callback(this.get()))\n }\n\n private async resolvePromise(\n newValue: Promise,\n options: SetOptions,\n ) {\n try {\n const resolvedValue = await newValue\n this.set(resolvedValue, options)\n } catch (error) {\n handlePromiseError(error)\n }\n }\n}\n","/**\n * Checks if the value is of the specified type.\n * @param {unknown} value - The value to check.\n * @param {new (...args: unknown[]) => unknown} type - The type constructor for the expected type.\n * @throws {Error} If the value is not of the expected type.\n */\nexport function checkValue(\n value: unknown,\n type: new (...args: unknown[]) => unknown,\n): void {\n if (Object.getPrototypeOf(value).constructor !== type) {\n throw new Error(`Value '${value}' must be of type ${type.name}`)\n }\n}\n\n/**\n * Handles errors that occur when a promise fails to resolve.\n * @param {unknown} error - The error that occurred.\n * @throws {Error} A new error with a message indicating that the promise failed to resolve.\n */\nexport function handlePromiseError(error: unknown): never {\n throw new Error(`Failed to resolve promise:\\n${error}`)\n}\n","import {\n checkInitialValue,\n checkName,\n checkTypeConstructor,\n handleStoreSetError,\n} from '../errors/createStoreErrorHandlers'\nimport type { StoreOptions } from '../types/storeOptions'\nimport type { StoreValue } from '../types/storeValue'\nimport type { TypeKey } from '../types/typeKey'\nimport { Store } from './store'\n\n/**\n * The createStore function is a factory function that creates and returns a new instance of the Store class.\n * It takes an options object as a parameter, which should include the name, initialValue, and type for the new store.\n *\n * Here's a technical breakdown of how it works:\n * - The function destructure's the name, type, and initialValue properties from the options object.\n * - It checks if initialValue is undefined. If it is, the function throws an error because a store must be initialized with a value.\n * - It checks if name is not a string. If it isn't, the function throws an error because the store's name must be a string. This name is used to create a unique Symbol which serves as the identifier for the store.\n * - It creates a new Symbol using the name and assigns it to symbolName.\n * - It creates a new instance of the Store class, passing symbolName, initialValue, and type to the Store constructor, and returns this new instance.\n *\n * The Store class encapsulates the state (the initialValue) and provides methods to get and set that state. The type is used for type checking to ensure that the store's value always matches the expected type.\n *\n * Usage Example:\n * ```javascript\n * const countStore = createStore({ name: 'count', initialValue: 0, type: Number });\n * ```\n *\n * @param {StoreOptions} options - The options for the store.\n * @param {string} options.name - The name of the store. This will be used to create a unique Symbol.\n * @param {T} options.initialValue - The initial value of the store. This must be provided.\n * @param {TypeKey} options.type - The type of the store's value. This is used for type checking [String, Number, Boolean, Array, Object].\n *\n * @returns {Store} The new store.\n *\n * @throws {Error} If no initial value is provided.\n * @throws {Error} If the name is not a string.\n */\n\nexport function createStore(options: StoreOptions): Store {\n const name: string = options.name\n const type: TypeKey = options.type\n const initialValue: StoreValue = options.initialValue\n checkInitialValue(initialValue)\n checkName(name)\n checkTypeConstructor(type.name)\n const symbolName = Symbol(name)\n\n const store: Store = new Store(symbolName, type)\n store.set(initialValue).catch((error) => handleStoreSetError(error))\n return store\n}\n","import { typeMap } from '../store/storeValuesTypeMap'\n\n/**\n * Checks if the initial value is defined.\n * @param {T} initialValue - The initial value of the store.\n * @throws {Error} If the initial value is undefined.\n */\nexport function checkInitialValue(initialValue: T): void {\n if (typeof initialValue === 'undefined') {\n throw new Error('Store must be initialized with a value')\n }\n}\n\n/**\n * Checks if the store name is a string.\n * @param {string} name - The name of the store.\n * @throws {Error} If the store name is not a string.\n */\nexport function checkName(name: string): void {\n if (typeof name !== 'string') {\n throw new Error('Store name must be of Type string')\n }\n}\n\n/**\n * Checks if the type constructor exists in the type map.\n * @param {string} type - The type of the store value.\n * @throws {Error} If the type constructor does not exist in the type map.\n */\nexport function checkTypeConstructor(type: string): void {\n const typeConstructor = typeMap[type]\n if (typeof typeConstructor !== 'function') {\n throw new Error(`Invalid type: ${type}`)\n }\n}\n\n/**\n * Handles errors that occur when setting the store value.\n * @param {unknown} error - The error that occurred.\n * @throws {Error} A new error with the same message if the original error is an instance of Error.\n * @throws {Error} A new error with a generic message if the original error is not an instance of Error.\n */\nexport function handleStoreSetError(error: unknown): never {\n if (error instanceof Error) {\n throw new Error(`Failed to create store: ${error.message}`)\n }\n throw new Error('An unknown error occurred while creating the store')\n}\n","import type { StoreController, StoreValue, Subscription } from 'types'\nimport { checkStores } from '../errors/useStoreErrorHandlers'\nimport { warnDirectAccess } from '../errors/useStoreWarningHandlers'\nimport type { Store } from '../store/store'\nimport { camelize } from '../utils/camelize'\n/**\n * useStore Function\n * The useStore function simplifies the process of subscribing to and handling updates from multiple store instances\n * within a Stimulus controller. It also allows direct access to store values on the controller.\n * How It Works:\n * 1. Retrieves the stores from the controller's constructor.\n * 2. Iterates over the stores.\n * 3. Identifies the type of each store and constructs an update method name.\n * 4. Creates update methods for stores if corresponding onStoreUpdate methods exist on the controller.\n * 5. Dynamically assigns update methods to the controller with specific names based on store types.\n * 6. Subscribes update methods to stores to handle updates.\n * 7. Allows direct access to store values on the controller.\n * 8. Enhances the controller's disconnect method to include cleanup for all subscriptions.\n *\n * Usage Example:\n * ```javascript\n * import { Controller } from \"@hotwired/stimulus\";\n * import { useStore } from \"stimulus-store\";\n * import { myStore } from \"./stores/myStore\"; // Import your store class\n *\n * export default class extends Controller {\n * static stores = [myStore];\n *\n * connect() {\n * // Use the useStore function to subscribe to specific stores\n * useStore(this);\n * }\n *\n * // Implement specific update methods for each store\n * onMyStoreUpdate() {\n * // Handle updates for MyStore\n * console.log(\"MyStore updated:\", this.myStoreValue);\n * }\n * }\n * ```\n * @param {Object} controller - The Stimulus controller instance that wants to subscribe to the stores.\n * @template T - The type of data stored in the stores.\n */\n\nexport function useStore(controller: StoreController) {\n const stores: Store[] | undefined = controller.constructor?.stores\n const unsubscribeFunctions: (() => void)[] = []\n\n // If 'stores' is undefined or empty, throw an error\n checkStores(stores)\n\n stores?.forEach((store) => {\n const storeName: symbol = store.name\n const storeNameAsString: string = storeName.toString().slice(7, -1)\n const camelizedName: string = camelize(storeNameAsString)\n const onStoreUpdateMethodName: string = `on${camelize(\n storeNameAsString,\n true,\n )}Update`\n const onStoreUpdateMethod = controller[onStoreUpdateMethodName] as (\n value: StoreValue,\n ) => void\n const subscription: Subscription = store.getSubscription()\n\n if (onStoreUpdateMethod) {\n const updateMethod: (value: StoreValue) => void = (value) => {\n onStoreUpdateMethod.call(controller, value)\n }\n\n const methodName = `update${camelize(storeNameAsString, true)}`\n controller[methodName] = updateMethod\n\n unsubscribeFunctions.push(subscription.subscribe(updateMethod))\n }\n\n // Add a helper method to set the store value\n const setStoreValueMethodName = `set${camelize(\n storeNameAsString,\n true,\n )}Value`\n controller[setStoreValueMethodName] = (\n value:\n | StoreValue\n | Promise\n | ((prev: StoreValue) => StoreValue),\n ) => {\n store.set(value)\n }\n\n // Add a helper method to reset the store value\n const resetStoreMethodName = `reset${camelize(storeNameAsString, true)}`\n controller[resetStoreMethodName] = () => {\n store.resetValue()\n }\n\n const storeGetterMethodName: string = `${camelizedName}Value`\n\n Object.defineProperty(controller, storeGetterMethodName, {\n get: () => store.get(),\n enumerable: true,\n configurable: true,\n })\n\n let isWarned = false\n\n // Wrap the store in a Proxy to intercept direct access\n const storeProxy = new Proxy(store, {\n get: (target, prop, receiver) => {\n isWarned = warnDirectAccess(camelizedName, isWarned)\n return Reflect.get(target, prop, receiver)\n },\n })\n\n Object.defineProperty(controller, camelizedName, {\n get: () => storeProxy,\n enumerable: true,\n configurable: true,\n })\n })\n\n const originalDisconnect = controller.disconnect.bind(controller)\n controller.disconnect = () => {\n unsubscribeFunctions.forEach((unsubscribe) => {\n if (unsubscribe) {\n unsubscribe()\n }\n })\n originalDisconnect()\n }\n}\n","/**\n * Checks if the stores array is defined, not empty, and is an array.\n * @param {unknown} stores - The stores array to check.\n * @throws {Error} If the stores array is undefined, empty, or not an array.\n */\nexport function checkStores(stores: unknown): void {\n if (!stores) {\n throw new Error(\n `'useStore' was called on a controller without a 'stores' static property. The 'stores' property is undefined.`,\n )\n }\n\n if (!Array.isArray(stores)) {\n throw new Error(\n `'useStore' was called on a controller with a 'stores' static property that is not an array.`,\n )\n }\n\n if (stores.length === 0) {\n throw new Error(\n `'useStore' was called on a controller with an empty 'stores' static property. The 'stores' array should contain at least one store.`,\n )\n }\n}\n","/**\n * Logs a warning message if the store is accessed directly and `isWarned` is false.\n * @param {string} camelizedName - The camelized name of the store.\n * @param {boolean} isWarned - A flag indicating if the warning has already been logged.\n * @returns {boolean} Returns true if the warning was logged, otherwise returns the original `isWarned` value.\n */\nexport function warnDirectAccess(\n camelizedName: string,\n isWarned: boolean,\n): boolean {\n if (!isWarned) {\n console.warn(\n `Warning: You are accessing the '${camelizedName}' instance directly. Consider using 'on${\n camelizedName.charAt(0).toUpperCase() + camelizedName.slice(1)\n }Update' and '${camelizedName}Value' instead.`,\n )\n return true\n }\n return isWarned\n}\n"],"names":["camelize","str","firstCharUppercase","replace","word","index","toUpperCase","toLowerCase","typeMap","String","Number","Array","Object","Boolean","Store","constructor","name","type","this","subscribers","Set","set","newValue","options","filter","Promise","resolvePromise","get","finalValue","value","getPrototypeOf","Error","checkValue","setInitialValue","setValue","notifySubscribers","resetValue","initialValue","undefined","subscribe","callback","add","unsubscribe","delete","getSubscription","from","forEach","resolvedValue","error","handlePromiseError","checkInitialValue","checkName","checkTypeConstructor","symbolName","Symbol","store","catch","message","handleStoreSetError","controller","stores","unsubscribeFunctions","isArray","length","checkStores","storeNameAsString","toString","slice","camelizedName","onStoreUpdateMethodName","onStoreUpdateMethod","subscription","updateMethod","call","methodName","push","setStoreValueMethodName","resetStoreMethodName","storeGetterMethodName","defineProperty","enumerable","configurable","isWarned","storeProxy","Proxy","target","prop","receiver","warnDirectAccess","Reflect","originalDisconnect","disconnect","bind"],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/stimulus-store/dist/bundle.esm.js b/node_modules/stimulus-store/dist/bundle.esm.js new file mode 100644 index 0000000..27bb862 --- /dev/null +++ b/node_modules/stimulus-store/dist/bundle.esm.js @@ -0,0 +1,2 @@ +function e(e,t=!1){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,((e,r)=>0!==r||t?e.toUpperCase():e.toLowerCase())).replace(/\s+/g,"")}function t(t){const r=t.constructor?.stores,s=[];!function(e){if(!e)throw new Error("'useStore' was called on a controller without a 'stores' static property. The 'stores' property is undefined.");if(!Array.isArray(e))throw new Error("'useStore' was called on a controller with a 'stores' static property that is not an array.");if(0===e.length)throw new Error("'useStore' was called on a controller with an empty 'stores' static property. The 'stores' array should contain at least one store.")}(r),r?.forEach((r=>{const o=r.name.toString().slice(7,-1),n=e(o),i=`on${e(o,!0)}Update`,a=t[i],c=r.getSubscription();if(a){const r=e=>{a.call(t,e)},n=`update${e(o,!0)}`;t[n]=r,s.push(c.subscribe(r))}const u=`set${e(o,!0)}Value`;t[u]=e=>{r.set(e)};const l=`reset${e(o,!0)}`;t[l]=()=>{r.resetValue()};const h=`${n}Value`;Object.defineProperty(t,h,{get:()=>r.get(),enumerable:!0,configurable:!0});let f=!1;const b=new Proxy(r,{get:(e,t,r)=>(f=function(e,t){return t||!0}(0,f),Reflect.get(e,t,r))});Object.defineProperty(t,n,{get:()=>b,enumerable:!0,configurable:!0})}));const o=t.disconnect.bind(t);t.disconnect=()=>{s.forEach((e=>{e&&e()})),o()}}const r={String:String,Number:Number,Array:Array,Object:Object,Boolean:Boolean};class s{constructor(e,t){this.name=e,this.subscribers=new Set,this.type=t}async set(e,t={filter:()=>!0}){if(e instanceof Promise)return this.resolvePromise(e,t);if(e===this.get())return;const r="function"==typeof e?e(this.get()):e;!function(e,t){if(Object.getPrototypeOf(e).constructor!==t)throw new Error(`Value '${e}' must be of type ${t.name}`)}(r,this.type),this.setInitialValue(r),this.setValue(r),this.notifySubscribers(t)}get(){return this.value}resetValue(){this.setValue(this.initialValue)}setValue(e){this.value=e}setInitialValue(e){void 0===this.value&&(this.initialValue=e)}subscribe(e){return this.subscribers.add(e),e(this.get()),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}getSubscription(){return{subscribe:e=>this.subscribe(e)}}notifySubscribers(e){Array.from(this.subscribers).filter((()=>e.filter(this.get()))).forEach((e=>e(this.get())))}async resolvePromise(e,t){try{const r=await e;this.set(r,t)}catch(e){!function(e){throw new Error(`Failed to resolve promise:\n${e}`)}(e)}}}function o(e){const t=e.name,o=e.type,n=e.initialValue;!function(e){if(void 0===e)throw new Error("Store must be initialized with a value")}(n),function(e){if("string"!=typeof e)throw new Error("Store name must be of Type string")}(t),function(e){if("function"!=typeof r[e])throw new Error(`Invalid type: ${e}`)}(o.name);const i=Symbol(t),a=new s(i,o);return a.set(n).catch((e=>function(e){if(e instanceof Error)throw new Error(`Failed to create store: ${e.message}`);throw new Error("An unknown error occurred while creating the store")}(e))),a}export{o as createStore,t as useStore}; +//# sourceMappingURL=bundle.esm.js.map diff --git a/node_modules/stimulus-store/dist/bundle.esm.js.map b/node_modules/stimulus-store/dist/bundle.esm.js.map new file mode 100644 index 0000000..d18f388 --- /dev/null +++ b/node_modules/stimulus-store/dist/bundle.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundle.esm.js","sources":["../src/utils/camelize.ts","../src/hooks/useStore.ts","../src/errors/useStoreErrorHandlers.ts","../src/errors/useStoreWarningHandlers.ts","../src/store/storeValuesTypeMap.ts","../src/store/store.ts","../src/errors/storeErrorHandlers.ts","../src/store/createStore.ts","../src/errors/createStoreErrorHandlers.ts"],"sourcesContent":["export function camelize(str: string, firstCharUppercase = false): string {\n const pattern1: RegExp = /(?:^\\w|[A-Z]|\\b\\w)/g\n const pattern2: RegExp = /\\s+/g\n const result: string = str\n .replace(pattern1, (word, index) =>\n index === 0 && !firstCharUppercase\n ? word.toLowerCase()\n : word.toUpperCase(),\n )\n .replace(pattern2, '')\n return result\n}\n","import type { StoreController, StoreValue, Subscription } from 'types'\nimport { checkStores } from '../errors/useStoreErrorHandlers'\nimport { warnDirectAccess } from '../errors/useStoreWarningHandlers'\nimport type { Store } from '../store/store'\nimport { camelize } from '../utils/camelize'\n/**\n * useStore Function\n * The useStore function simplifies the process of subscribing to and handling updates from multiple store instances\n * within a Stimulus controller. It also allows direct access to store values on the controller.\n * How It Works:\n * 1. Retrieves the stores from the controller's constructor.\n * 2. Iterates over the stores.\n * 3. Identifies the type of each store and constructs an update method name.\n * 4. Creates update methods for stores if corresponding onStoreUpdate methods exist on the controller.\n * 5. Dynamically assigns update methods to the controller with specific names based on store types.\n * 6. Subscribes update methods to stores to handle updates.\n * 7. Allows direct access to store values on the controller.\n * 8. Enhances the controller's disconnect method to include cleanup for all subscriptions.\n *\n * Usage Example:\n * ```javascript\n * import { Controller } from \"@hotwired/stimulus\";\n * import { useStore } from \"stimulus-store\";\n * import { myStore } from \"./stores/myStore\"; // Import your store class\n *\n * export default class extends Controller {\n * static stores = [myStore];\n *\n * connect() {\n * // Use the useStore function to subscribe to specific stores\n * useStore(this);\n * }\n *\n * // Implement specific update methods for each store\n * onMyStoreUpdate() {\n * // Handle updates for MyStore\n * console.log(\"MyStore updated:\", this.myStoreValue);\n * }\n * }\n * ```\n * @param {Object} controller - The Stimulus controller instance that wants to subscribe to the stores.\n * @template T - The type of data stored in the stores.\n */\n\nexport function useStore(controller: StoreController) {\n const stores: Store[] | undefined = controller.constructor?.stores\n const unsubscribeFunctions: (() => void)[] = []\n\n // If 'stores' is undefined or empty, throw an error\n checkStores(stores)\n\n stores?.forEach((store) => {\n const storeName: symbol = store.name\n const storeNameAsString: string = storeName.toString().slice(7, -1)\n const camelizedName: string = camelize(storeNameAsString)\n const onStoreUpdateMethodName: string = `on${camelize(\n storeNameAsString,\n true,\n )}Update`\n const onStoreUpdateMethod = controller[onStoreUpdateMethodName] as (\n value: StoreValue,\n ) => void\n const subscription: Subscription = store.getSubscription()\n\n if (onStoreUpdateMethod) {\n const updateMethod: (value: StoreValue) => void = (value) => {\n onStoreUpdateMethod.call(controller, value)\n }\n\n const methodName = `update${camelize(storeNameAsString, true)}`\n controller[methodName] = updateMethod\n\n unsubscribeFunctions.push(subscription.subscribe(updateMethod))\n }\n\n // Add a helper method to set the store value\n const setStoreValueMethodName = `set${camelize(\n storeNameAsString,\n true,\n )}Value`\n controller[setStoreValueMethodName] = (\n value:\n | StoreValue\n | Promise\n | ((prev: StoreValue) => StoreValue),\n ) => {\n store.set(value)\n }\n\n // Add a helper method to reset the store value\n const resetStoreMethodName = `reset${camelize(storeNameAsString, true)}`\n controller[resetStoreMethodName] = () => {\n store.resetValue()\n }\n\n const storeGetterMethodName: string = `${camelizedName}Value`\n\n Object.defineProperty(controller, storeGetterMethodName, {\n get: () => store.get(),\n enumerable: true,\n configurable: true,\n })\n\n let isWarned = false\n\n // Wrap the store in a Proxy to intercept direct access\n const storeProxy = new Proxy(store, {\n get: (target, prop, receiver) => {\n isWarned = warnDirectAccess(camelizedName, isWarned)\n return Reflect.get(target, prop, receiver)\n },\n })\n\n Object.defineProperty(controller, camelizedName, {\n get: () => storeProxy,\n enumerable: true,\n configurable: true,\n })\n })\n\n const originalDisconnect = controller.disconnect.bind(controller)\n controller.disconnect = () => {\n unsubscribeFunctions.forEach((unsubscribe) => {\n if (unsubscribe) {\n unsubscribe()\n }\n })\n originalDisconnect()\n }\n}\n","/**\n * Checks if the stores array is defined, not empty, and is an array.\n * @param {unknown} stores - The stores array to check.\n * @throws {Error} If the stores array is undefined, empty, or not an array.\n */\nexport function checkStores(stores: unknown): void {\n if (!stores) {\n throw new Error(\n `'useStore' was called on a controller without a 'stores' static property. The 'stores' property is undefined.`,\n )\n }\n\n if (!Array.isArray(stores)) {\n throw new Error(\n `'useStore' was called on a controller with a 'stores' static property that is not an array.`,\n )\n }\n\n if (stores.length === 0) {\n throw new Error(\n `'useStore' was called on a controller with an empty 'stores' static property. The 'stores' array should contain at least one store.`,\n )\n }\n}\n","/**\n * Logs a warning message if the store is accessed directly and `isWarned` is false.\n * @param {string} camelizedName - The camelized name of the store.\n * @param {boolean} isWarned - A flag indicating if the warning has already been logged.\n * @returns {boolean} Returns true if the warning was logged, otherwise returns the original `isWarned` value.\n */\nexport function warnDirectAccess(\n camelizedName: string,\n isWarned: boolean,\n): boolean {\n if (!isWarned) {\n console.warn(\n `Warning: You are accessing the '${camelizedName}' instance directly. Consider using 'on${\n camelizedName.charAt(0).toUpperCase() + camelizedName.slice(1)\n }Update' and '${camelizedName}Value' instead.`,\n )\n return true\n }\n return isWarned\n}\n","import type { TypeKey } from '../types/typeKey'\n\n/**\n * A mapping from type names to their corresponding constructor types.\n * - Allows type checking values at runtime.\n * - Allows the use of the following types: String, Number, Array, Object, Boolean.\n * - Each type has its own constructor type: StringConstructor, NumberConstructor, ArrayConstructor, ObjectConstructor, BooleanConstructor.\n * - TypeKey is a union of all the constructor types.\n * @type {Record}\n *\n */\n\nexport const typeMap: Record = {\n String: String,\n Number: Number,\n Array: Array,\n Object: Object,\n Boolean: Boolean,\n}\n","import type {\n CurrentValueCallback,\n NotifySubscriberOptions,\n SetOptions,\n StoreValue,\n Subscription,\n TypeKey,\n UnsubscribeFunction,\n UpdateMethod,\n} from 'types'\nimport { checkValue, handlePromiseError } from '../errors/storeErrorHandlers'\n/**\n * @template T The type of the value that the store holds.\n * Store Class Explanation:\n *\n * The `Store` class is a versatile class for managing and subscribing to data updates in JavaScript applications.\n * It provides a structured way to store data and notify subscribers when the data changes.\n *\n * Key Features:\n * - Generic Class: Can work with different types of data (specified when creating an instance).\n * - Constructor: Sets the initial value of the store.\n * - `set` Method: Updates the value and notifies subscribers.\n * - `get` Method: Gets the current value.\n * - `subscribe` Method: Subscribes to updates and calls a callback function when data changes.\n * - `unsubscribe` Method: Removes a subscription.\n * - `notifySubscribers` Method: Notifies subscribers when data changes.\n */\n\nexport class Store {\n readonly name: symbol\n private value!: StoreValue\n private initialValue!: StoreValue\n private subscribers: Set\n private type: TypeKey\n\n /**\n * Creates a new store.\n *\n * @param {symbol} name - The name of the store.\n * @param {TypeKey} type - The type of the store's value.\n */\n constructor(name: symbol, type: TypeKey) {\n this.name = name\n this.subscribers = new Set()\n this.type = type\n }\n\n /**\n * Sets the value of the store and notifies subscribers.\n *\n * @param {T | CurrentValueCallback | Promise} newValue - The new value.\n * @param {SetOptions} [options={ filter: () => true }] - The options for setting the value.\n */\n async set(\n newValue:\n | StoreValue\n | CurrentValueCallback\n | Promise,\n options: SetOptions = { filter: () => true },\n ) {\n if (newValue instanceof Promise)\n return this.resolvePromise(newValue, options)\n if (newValue === this.get()) return\n const finalValue: StoreValue =\n typeof newValue === 'function'\n ? (newValue as CurrentValueCallback)(this.get())\n : newValue\n checkValue(finalValue, this.type)\n this.setInitialValue(finalValue)\n this.setValue(finalValue)\n this.notifySubscribers(options)\n }\n\n /**\n * Gets the current value of the store.\n *\n * @returns {StoreValue} The current value.\n */\n get(): StoreValue {\n return this.value\n }\n\n /**\n * Resets the store to its initial value.\n */\n resetValue(): void {\n this.setValue(this.initialValue)\n }\n\n private setValue(value: StoreValue): void {\n this.value = value\n }\n\n private setInitialValue(value: StoreValue): void {\n if (this.value === undefined) this.initialValue = value\n }\n\n /**\n * Subscribes to the store.\n *\n * @param {UpdateMethod} callback - The function to call when the store's value changes.\n * @returns {UnsubscribeFunction} A function that unsubscribes the callback.\n */\n private subscribe(callback: UpdateMethod): UnsubscribeFunction {\n this.subscribers.add(callback)\n callback(this.get()) // Immediate call for initial value\n return () => this.unsubscribe(callback) // Return an unsubscribe function\n }\n\n /**\n * Unsubscribes from the store.\n *\n * @param {UpdateMethod} callback - The function to unsubscribe.\n */\n private unsubscribe(callback: UpdateMethod) {\n this.subscribers.delete(callback)\n }\n\n /**\n * Gets a subscription object with subscribe, when invoked subscribe returns an unsubscribe function.\n *\n * @returns {Subscription} A subscription object.\n */\n public getSubscription(): Subscription {\n return {\n subscribe: (callback: UpdateMethod) => this.subscribe(callback),\n }\n }\n\n private notifySubscribers(options: NotifySubscriberOptions) {\n Array.from(this.subscribers)\n .filter(() => options.filter(this.get()))\n .forEach((callback) => callback(this.get()))\n }\n\n private async resolvePromise(\n newValue: Promise,\n options: SetOptions,\n ) {\n try {\n const resolvedValue = await newValue\n this.set(resolvedValue, options)\n } catch (error) {\n handlePromiseError(error)\n }\n }\n}\n","/**\n * Checks if the value is of the specified type.\n * @param {unknown} value - The value to check.\n * @param {new (...args: unknown[]) => unknown} type - The type constructor for the expected type.\n * @throws {Error} If the value is not of the expected type.\n */\nexport function checkValue(\n value: unknown,\n type: new (...args: unknown[]) => unknown,\n): void {\n if (Object.getPrototypeOf(value).constructor !== type) {\n throw new Error(`Value '${value}' must be of type ${type.name}`)\n }\n}\n\n/**\n * Handles errors that occur when a promise fails to resolve.\n * @param {unknown} error - The error that occurred.\n * @throws {Error} A new error with a message indicating that the promise failed to resolve.\n */\nexport function handlePromiseError(error: unknown): never {\n throw new Error(`Failed to resolve promise:\\n${error}`)\n}\n","import {\n checkInitialValue,\n checkName,\n checkTypeConstructor,\n handleStoreSetError,\n} from '../errors/createStoreErrorHandlers'\nimport type { StoreOptions } from '../types/storeOptions'\nimport type { StoreValue } from '../types/storeValue'\nimport type { TypeKey } from '../types/typeKey'\nimport { Store } from './store'\n\n/**\n * The createStore function is a factory function that creates and returns a new instance of the Store class.\n * It takes an options object as a parameter, which should include the name, initialValue, and type for the new store.\n *\n * Here's a technical breakdown of how it works:\n * - The function destructure's the name, type, and initialValue properties from the options object.\n * - It checks if initialValue is undefined. If it is, the function throws an error because a store must be initialized with a value.\n * - It checks if name is not a string. If it isn't, the function throws an error because the store's name must be a string. This name is used to create a unique Symbol which serves as the identifier for the store.\n * - It creates a new Symbol using the name and assigns it to symbolName.\n * - It creates a new instance of the Store class, passing symbolName, initialValue, and type to the Store constructor, and returns this new instance.\n *\n * The Store class encapsulates the state (the initialValue) and provides methods to get and set that state. The type is used for type checking to ensure that the store's value always matches the expected type.\n *\n * Usage Example:\n * ```javascript\n * const countStore = createStore({ name: 'count', initialValue: 0, type: Number });\n * ```\n *\n * @param {StoreOptions} options - The options for the store.\n * @param {string} options.name - The name of the store. This will be used to create a unique Symbol.\n * @param {T} options.initialValue - The initial value of the store. This must be provided.\n * @param {TypeKey} options.type - The type of the store's value. This is used for type checking [String, Number, Boolean, Array, Object].\n *\n * @returns {Store} The new store.\n *\n * @throws {Error} If no initial value is provided.\n * @throws {Error} If the name is not a string.\n */\n\nexport function createStore(options: StoreOptions): Store {\n const name: string = options.name\n const type: TypeKey = options.type\n const initialValue: StoreValue = options.initialValue\n checkInitialValue(initialValue)\n checkName(name)\n checkTypeConstructor(type.name)\n const symbolName = Symbol(name)\n\n const store: Store = new Store(symbolName, type)\n store.set(initialValue).catch((error) => handleStoreSetError(error))\n return store\n}\n","import { typeMap } from '../store/storeValuesTypeMap'\n\n/**\n * Checks if the initial value is defined.\n * @param {T} initialValue - The initial value of the store.\n * @throws {Error} If the initial value is undefined.\n */\nexport function checkInitialValue(initialValue: T): void {\n if (typeof initialValue === 'undefined') {\n throw new Error('Store must be initialized with a value')\n }\n}\n\n/**\n * Checks if the store name is a string.\n * @param {string} name - The name of the store.\n * @throws {Error} If the store name is not a string.\n */\nexport function checkName(name: string): void {\n if (typeof name !== 'string') {\n throw new Error('Store name must be of Type string')\n }\n}\n\n/**\n * Checks if the type constructor exists in the type map.\n * @param {string} type - The type of the store value.\n * @throws {Error} If the type constructor does not exist in the type map.\n */\nexport function checkTypeConstructor(type: string): void {\n const typeConstructor = typeMap[type]\n if (typeof typeConstructor !== 'function') {\n throw new Error(`Invalid type: ${type}`)\n }\n}\n\n/**\n * Handles errors that occur when setting the store value.\n * @param {unknown} error - The error that occurred.\n * @throws {Error} A new error with the same message if the original error is an instance of Error.\n * @throws {Error} A new error with a generic message if the original error is not an instance of Error.\n */\nexport function handleStoreSetError(error: unknown): never {\n if (error instanceof Error) {\n throw new Error(`Failed to create store: ${error.message}`)\n }\n throw new Error('An unknown error occurred while creating the store')\n}\n"],"names":["camelize","str","firstCharUppercase","replace","word","index","toUpperCase","toLowerCase","useStore","controller","stores","constructor","unsubscribeFunctions","Error","Array","isArray","length","checkStores","forEach","store","storeNameAsString","name","toString","slice","camelizedName","onStoreUpdateMethodName","onStoreUpdateMethod","subscription","getSubscription","updateMethod","value","call","methodName","push","subscribe","setStoreValueMethodName","set","resetStoreMethodName","resetValue","storeGetterMethodName","Object","defineProperty","get","enumerable","configurable","isWarned","storeProxy","Proxy","target","prop","receiver","warnDirectAccess","Reflect","originalDisconnect","disconnect","bind","unsubscribe","typeMap","String","Number","Boolean","Store","type","this","subscribers","Set","newValue","options","filter","Promise","resolvePromise","finalValue","getPrototypeOf","checkValue","setInitialValue","setValue","notifySubscribers","initialValue","undefined","callback","add","delete","from","resolvedValue","error","handlePromiseError","createStore","checkInitialValue","checkName","checkTypeConstructor","symbolName","Symbol","catch","message","handleStoreSetError"],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/stimulus-store/dist/bundle.umd.js b/node_modules/stimulus-store/dist/bundle.umd.js new file mode 100644 index 0000000..83eeaa2 --- /dev/null +++ b/node_modules/stimulus-store/dist/bundle.umd.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StimulusStore={})}(this,(function(e){"use strict";function t(e,t=!1){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,((e,r)=>0!==r||t?e.toUpperCase():e.toLowerCase())).replace(/\s+/g,"")}const r={String:String,Number:Number,Array:Array,Object:Object,Boolean:Boolean};class s{constructor(e,t){this.name=e,this.subscribers=new Set,this.type=t}async set(e,t={filter:()=>!0}){if(e instanceof Promise)return this.resolvePromise(e,t);if(e===this.get())return;const r="function"==typeof e?e(this.get()):e;!function(e,t){if(Object.getPrototypeOf(e).constructor!==t)throw new Error(`Value '${e}' must be of type ${t.name}`)}(r,this.type),this.setInitialValue(r),this.setValue(r),this.notifySubscribers(t)}get(){return this.value}resetValue(){this.setValue(this.initialValue)}setValue(e){this.value=e}setInitialValue(e){void 0===this.value&&(this.initialValue=e)}subscribe(e){return this.subscribers.add(e),e(this.get()),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}getSubscription(){return{subscribe:e=>this.subscribe(e)}}notifySubscribers(e){Array.from(this.subscribers).filter((()=>e.filter(this.get()))).forEach((e=>e(this.get())))}async resolvePromise(e,t){try{const r=await e;this.set(r,t)}catch(e){!function(e){throw new Error(`Failed to resolve promise:\n${e}`)}(e)}}}e.createStore=function(e){const t=e.name,o=e.type,n=e.initialValue;!function(e){if(void 0===e)throw new Error("Store must be initialized with a value")}(n),function(e){if("string"!=typeof e)throw new Error("Store name must be of Type string")}(t),function(e){if("function"!=typeof r[e])throw new Error(`Invalid type: ${e}`)}(o.name);const i=Symbol(t),a=new s(i,o);return a.set(n).catch((e=>function(e){if(e instanceof Error)throw new Error(`Failed to create store: ${e.message}`);throw new Error("An unknown error occurred while creating the store")}(e))),a},e.useStore=function(e){const r=e.constructor?.stores,s=[];!function(e){if(!e)throw new Error("'useStore' was called on a controller without a 'stores' static property. The 'stores' property is undefined.");if(!Array.isArray(e))throw new Error("'useStore' was called on a controller with a 'stores' static property that is not an array.");if(0===e.length)throw new Error("'useStore' was called on a controller with an empty 'stores' static property. The 'stores' array should contain at least one store.")}(r),r?.forEach((r=>{const o=r.name.toString().slice(7,-1),n=t(o),i=`on${t(o,!0)}Update`,a=e[i],c=r.getSubscription();if(a){const r=t=>{a.call(e,t)},n=`update${t(o,!0)}`;e[n]=r,s.push(c.subscribe(r))}const u=`set${t(o,!0)}Value`;e[u]=e=>{r.set(e)};const l=`reset${t(o,!0)}`;e[l]=()=>{r.resetValue()};const f=`${n}Value`;Object.defineProperty(e,f,{get:()=>r.get(),enumerable:!0,configurable:!0});let h=!1;const b=new Proxy(r,{get:(e,t,r)=>(h=function(e,t){return t||!0}(0,h),Reflect.get(e,t,r))});Object.defineProperty(e,n,{get:()=>b,enumerable:!0,configurable:!0})}));const o=e.disconnect.bind(e);e.disconnect=()=>{s.forEach((e=>{e&&e()})),o()}}})); +//# sourceMappingURL=bundle.umd.js.map diff --git a/node_modules/stimulus-store/dist/bundle.umd.js.map b/node_modules/stimulus-store/dist/bundle.umd.js.map new file mode 100644 index 0000000..dad84be --- /dev/null +++ b/node_modules/stimulus-store/dist/bundle.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundle.umd.js","sources":["../src/utils/camelize.ts","../src/store/storeValuesTypeMap.ts","../src/store/store.ts","../src/errors/storeErrorHandlers.ts","../src/store/createStore.ts","../src/errors/createStoreErrorHandlers.ts","../src/hooks/useStore.ts","../src/errors/useStoreErrorHandlers.ts","../src/errors/useStoreWarningHandlers.ts"],"sourcesContent":["export function camelize(str: string, firstCharUppercase = false): string {\n const pattern1: RegExp = /(?:^\\w|[A-Z]|\\b\\w)/g\n const pattern2: RegExp = /\\s+/g\n const result: string = str\n .replace(pattern1, (word, index) =>\n index === 0 && !firstCharUppercase\n ? word.toLowerCase()\n : word.toUpperCase(),\n )\n .replace(pattern2, '')\n return result\n}\n","import type { TypeKey } from '../types/typeKey'\n\n/**\n * A mapping from type names to their corresponding constructor types.\n * - Allows type checking values at runtime.\n * - Allows the use of the following types: String, Number, Array, Object, Boolean.\n * - Each type has its own constructor type: StringConstructor, NumberConstructor, ArrayConstructor, ObjectConstructor, BooleanConstructor.\n * - TypeKey is a union of all the constructor types.\n * @type {Record}\n *\n */\n\nexport const typeMap: Record = {\n String: String,\n Number: Number,\n Array: Array,\n Object: Object,\n Boolean: Boolean,\n}\n","import type {\n CurrentValueCallback,\n NotifySubscriberOptions,\n SetOptions,\n StoreValue,\n Subscription,\n TypeKey,\n UnsubscribeFunction,\n UpdateMethod,\n} from 'types'\nimport { checkValue, handlePromiseError } from '../errors/storeErrorHandlers'\n/**\n * @template T The type of the value that the store holds.\n * Store Class Explanation:\n *\n * The `Store` class is a versatile class for managing and subscribing to data updates in JavaScript applications.\n * It provides a structured way to store data and notify subscribers when the data changes.\n *\n * Key Features:\n * - Generic Class: Can work with different types of data (specified when creating an instance).\n * - Constructor: Sets the initial value of the store.\n * - `set` Method: Updates the value and notifies subscribers.\n * - `get` Method: Gets the current value.\n * - `subscribe` Method: Subscribes to updates and calls a callback function when data changes.\n * - `unsubscribe` Method: Removes a subscription.\n * - `notifySubscribers` Method: Notifies subscribers when data changes.\n */\n\nexport class Store {\n readonly name: symbol\n private value!: StoreValue\n private initialValue!: StoreValue\n private subscribers: Set\n private type: TypeKey\n\n /**\n * Creates a new store.\n *\n * @param {symbol} name - The name of the store.\n * @param {TypeKey} type - The type of the store's value.\n */\n constructor(name: symbol, type: TypeKey) {\n this.name = name\n this.subscribers = new Set()\n this.type = type\n }\n\n /**\n * Sets the value of the store and notifies subscribers.\n *\n * @param {T | CurrentValueCallback | Promise} newValue - The new value.\n * @param {SetOptions} [options={ filter: () => true }] - The options for setting the value.\n */\n async set(\n newValue:\n | StoreValue\n | CurrentValueCallback\n | Promise,\n options: SetOptions = { filter: () => true },\n ) {\n if (newValue instanceof Promise)\n return this.resolvePromise(newValue, options)\n if (newValue === this.get()) return\n const finalValue: StoreValue =\n typeof newValue === 'function'\n ? (newValue as CurrentValueCallback)(this.get())\n : newValue\n checkValue(finalValue, this.type)\n this.setInitialValue(finalValue)\n this.setValue(finalValue)\n this.notifySubscribers(options)\n }\n\n /**\n * Gets the current value of the store.\n *\n * @returns {StoreValue} The current value.\n */\n get(): StoreValue {\n return this.value\n }\n\n /**\n * Resets the store to its initial value.\n */\n resetValue(): void {\n this.setValue(this.initialValue)\n }\n\n private setValue(value: StoreValue): void {\n this.value = value\n }\n\n private setInitialValue(value: StoreValue): void {\n if (this.value === undefined) this.initialValue = value\n }\n\n /**\n * Subscribes to the store.\n *\n * @param {UpdateMethod} callback - The function to call when the store's value changes.\n * @returns {UnsubscribeFunction} A function that unsubscribes the callback.\n */\n private subscribe(callback: UpdateMethod): UnsubscribeFunction {\n this.subscribers.add(callback)\n callback(this.get()) // Immediate call for initial value\n return () => this.unsubscribe(callback) // Return an unsubscribe function\n }\n\n /**\n * Unsubscribes from the store.\n *\n * @param {UpdateMethod} callback - The function to unsubscribe.\n */\n private unsubscribe(callback: UpdateMethod) {\n this.subscribers.delete(callback)\n }\n\n /**\n * Gets a subscription object with subscribe, when invoked subscribe returns an unsubscribe function.\n *\n * @returns {Subscription} A subscription object.\n */\n public getSubscription(): Subscription {\n return {\n subscribe: (callback: UpdateMethod) => this.subscribe(callback),\n }\n }\n\n private notifySubscribers(options: NotifySubscriberOptions) {\n Array.from(this.subscribers)\n .filter(() => options.filter(this.get()))\n .forEach((callback) => callback(this.get()))\n }\n\n private async resolvePromise(\n newValue: Promise,\n options: SetOptions,\n ) {\n try {\n const resolvedValue = await newValue\n this.set(resolvedValue, options)\n } catch (error) {\n handlePromiseError(error)\n }\n }\n}\n","/**\n * Checks if the value is of the specified type.\n * @param {unknown} value - The value to check.\n * @param {new (...args: unknown[]) => unknown} type - The type constructor for the expected type.\n * @throws {Error} If the value is not of the expected type.\n */\nexport function checkValue(\n value: unknown,\n type: new (...args: unknown[]) => unknown,\n): void {\n if (Object.getPrototypeOf(value).constructor !== type) {\n throw new Error(`Value '${value}' must be of type ${type.name}`)\n }\n}\n\n/**\n * Handles errors that occur when a promise fails to resolve.\n * @param {unknown} error - The error that occurred.\n * @throws {Error} A new error with a message indicating that the promise failed to resolve.\n */\nexport function handlePromiseError(error: unknown): never {\n throw new Error(`Failed to resolve promise:\\n${error}`)\n}\n","import {\n checkInitialValue,\n checkName,\n checkTypeConstructor,\n handleStoreSetError,\n} from '../errors/createStoreErrorHandlers'\nimport type { StoreOptions } from '../types/storeOptions'\nimport type { StoreValue } from '../types/storeValue'\nimport type { TypeKey } from '../types/typeKey'\nimport { Store } from './store'\n\n/**\n * The createStore function is a factory function that creates and returns a new instance of the Store class.\n * It takes an options object as a parameter, which should include the name, initialValue, and type for the new store.\n *\n * Here's a technical breakdown of how it works:\n * - The function destructure's the name, type, and initialValue properties from the options object.\n * - It checks if initialValue is undefined. If it is, the function throws an error because a store must be initialized with a value.\n * - It checks if name is not a string. If it isn't, the function throws an error because the store's name must be a string. This name is used to create a unique Symbol which serves as the identifier for the store.\n * - It creates a new Symbol using the name and assigns it to symbolName.\n * - It creates a new instance of the Store class, passing symbolName, initialValue, and type to the Store constructor, and returns this new instance.\n *\n * The Store class encapsulates the state (the initialValue) and provides methods to get and set that state. The type is used for type checking to ensure that the store's value always matches the expected type.\n *\n * Usage Example:\n * ```javascript\n * const countStore = createStore({ name: 'count', initialValue: 0, type: Number });\n * ```\n *\n * @param {StoreOptions} options - The options for the store.\n * @param {string} options.name - The name of the store. This will be used to create a unique Symbol.\n * @param {T} options.initialValue - The initial value of the store. This must be provided.\n * @param {TypeKey} options.type - The type of the store's value. This is used for type checking [String, Number, Boolean, Array, Object].\n *\n * @returns {Store} The new store.\n *\n * @throws {Error} If no initial value is provided.\n * @throws {Error} If the name is not a string.\n */\n\nexport function createStore(options: StoreOptions): Store {\n const name: string = options.name\n const type: TypeKey = options.type\n const initialValue: StoreValue = options.initialValue\n checkInitialValue(initialValue)\n checkName(name)\n checkTypeConstructor(type.name)\n const symbolName = Symbol(name)\n\n const store: Store = new Store(symbolName, type)\n store.set(initialValue).catch((error) => handleStoreSetError(error))\n return store\n}\n","import { typeMap } from '../store/storeValuesTypeMap'\n\n/**\n * Checks if the initial value is defined.\n * @param {T} initialValue - The initial value of the store.\n * @throws {Error} If the initial value is undefined.\n */\nexport function checkInitialValue(initialValue: T): void {\n if (typeof initialValue === 'undefined') {\n throw new Error('Store must be initialized with a value')\n }\n}\n\n/**\n * Checks if the store name is a string.\n * @param {string} name - The name of the store.\n * @throws {Error} If the store name is not a string.\n */\nexport function checkName(name: string): void {\n if (typeof name !== 'string') {\n throw new Error('Store name must be of Type string')\n }\n}\n\n/**\n * Checks if the type constructor exists in the type map.\n * @param {string} type - The type of the store value.\n * @throws {Error} If the type constructor does not exist in the type map.\n */\nexport function checkTypeConstructor(type: string): void {\n const typeConstructor = typeMap[type]\n if (typeof typeConstructor !== 'function') {\n throw new Error(`Invalid type: ${type}`)\n }\n}\n\n/**\n * Handles errors that occur when setting the store value.\n * @param {unknown} error - The error that occurred.\n * @throws {Error} A new error with the same message if the original error is an instance of Error.\n * @throws {Error} A new error with a generic message if the original error is not an instance of Error.\n */\nexport function handleStoreSetError(error: unknown): never {\n if (error instanceof Error) {\n throw new Error(`Failed to create store: ${error.message}`)\n }\n throw new Error('An unknown error occurred while creating the store')\n}\n","import type { StoreController, StoreValue, Subscription } from 'types'\nimport { checkStores } from '../errors/useStoreErrorHandlers'\nimport { warnDirectAccess } from '../errors/useStoreWarningHandlers'\nimport type { Store } from '../store/store'\nimport { camelize } from '../utils/camelize'\n/**\n * useStore Function\n * The useStore function simplifies the process of subscribing to and handling updates from multiple store instances\n * within a Stimulus controller. It also allows direct access to store values on the controller.\n * How It Works:\n * 1. Retrieves the stores from the controller's constructor.\n * 2. Iterates over the stores.\n * 3. Identifies the type of each store and constructs an update method name.\n * 4. Creates update methods for stores if corresponding onStoreUpdate methods exist on the controller.\n * 5. Dynamically assigns update methods to the controller with specific names based on store types.\n * 6. Subscribes update methods to stores to handle updates.\n * 7. Allows direct access to store values on the controller.\n * 8. Enhances the controller's disconnect method to include cleanup for all subscriptions.\n *\n * Usage Example:\n * ```javascript\n * import { Controller } from \"@hotwired/stimulus\";\n * import { useStore } from \"stimulus-store\";\n * import { myStore } from \"./stores/myStore\"; // Import your store class\n *\n * export default class extends Controller {\n * static stores = [myStore];\n *\n * connect() {\n * // Use the useStore function to subscribe to specific stores\n * useStore(this);\n * }\n *\n * // Implement specific update methods for each store\n * onMyStoreUpdate() {\n * // Handle updates for MyStore\n * console.log(\"MyStore updated:\", this.myStoreValue);\n * }\n * }\n * ```\n * @param {Object} controller - The Stimulus controller instance that wants to subscribe to the stores.\n * @template T - The type of data stored in the stores.\n */\n\nexport function useStore(controller: StoreController) {\n const stores: Store[] | undefined = controller.constructor?.stores\n const unsubscribeFunctions: (() => void)[] = []\n\n // If 'stores' is undefined or empty, throw an error\n checkStores(stores)\n\n stores?.forEach((store) => {\n const storeName: symbol = store.name\n const storeNameAsString: string = storeName.toString().slice(7, -1)\n const camelizedName: string = camelize(storeNameAsString)\n const onStoreUpdateMethodName: string = `on${camelize(\n storeNameAsString,\n true,\n )}Update`\n const onStoreUpdateMethod = controller[onStoreUpdateMethodName] as (\n value: StoreValue,\n ) => void\n const subscription: Subscription = store.getSubscription()\n\n if (onStoreUpdateMethod) {\n const updateMethod: (value: StoreValue) => void = (value) => {\n onStoreUpdateMethod.call(controller, value)\n }\n\n const methodName = `update${camelize(storeNameAsString, true)}`\n controller[methodName] = updateMethod\n\n unsubscribeFunctions.push(subscription.subscribe(updateMethod))\n }\n\n // Add a helper method to set the store value\n const setStoreValueMethodName = `set${camelize(\n storeNameAsString,\n true,\n )}Value`\n controller[setStoreValueMethodName] = (\n value:\n | StoreValue\n | Promise\n | ((prev: StoreValue) => StoreValue),\n ) => {\n store.set(value)\n }\n\n // Add a helper method to reset the store value\n const resetStoreMethodName = `reset${camelize(storeNameAsString, true)}`\n controller[resetStoreMethodName] = () => {\n store.resetValue()\n }\n\n const storeGetterMethodName: string = `${camelizedName}Value`\n\n Object.defineProperty(controller, storeGetterMethodName, {\n get: () => store.get(),\n enumerable: true,\n configurable: true,\n })\n\n let isWarned = false\n\n // Wrap the store in a Proxy to intercept direct access\n const storeProxy = new Proxy(store, {\n get: (target, prop, receiver) => {\n isWarned = warnDirectAccess(camelizedName, isWarned)\n return Reflect.get(target, prop, receiver)\n },\n })\n\n Object.defineProperty(controller, camelizedName, {\n get: () => storeProxy,\n enumerable: true,\n configurable: true,\n })\n })\n\n const originalDisconnect = controller.disconnect.bind(controller)\n controller.disconnect = () => {\n unsubscribeFunctions.forEach((unsubscribe) => {\n if (unsubscribe) {\n unsubscribe()\n }\n })\n originalDisconnect()\n }\n}\n","/**\n * Checks if the stores array is defined, not empty, and is an array.\n * @param {unknown} stores - The stores array to check.\n * @throws {Error} If the stores array is undefined, empty, or not an array.\n */\nexport function checkStores(stores: unknown): void {\n if (!stores) {\n throw new Error(\n `'useStore' was called on a controller without a 'stores' static property. The 'stores' property is undefined.`,\n )\n }\n\n if (!Array.isArray(stores)) {\n throw new Error(\n `'useStore' was called on a controller with a 'stores' static property that is not an array.`,\n )\n }\n\n if (stores.length === 0) {\n throw new Error(\n `'useStore' was called on a controller with an empty 'stores' static property. The 'stores' array should contain at least one store.`,\n )\n }\n}\n","/**\n * Logs a warning message if the store is accessed directly and `isWarned` is false.\n * @param {string} camelizedName - The camelized name of the store.\n * @param {boolean} isWarned - A flag indicating if the warning has already been logged.\n * @returns {boolean} Returns true if the warning was logged, otherwise returns the original `isWarned` value.\n */\nexport function warnDirectAccess(\n camelizedName: string,\n isWarned: boolean,\n): boolean {\n if (!isWarned) {\n console.warn(\n `Warning: You are accessing the '${camelizedName}' instance directly. Consider using 'on${\n camelizedName.charAt(0).toUpperCase() + camelizedName.slice(1)\n }Update' and '${camelizedName}Value' instead.`,\n )\n return true\n }\n return isWarned\n}\n"],"names":["camelize","str","firstCharUppercase","replace","word","index","toUpperCase","toLowerCase","typeMap","String","Number","Array","Object","Boolean","Store","constructor","name","type","this","subscribers","Set","set","newValue","options","filter","Promise","resolvePromise","get","finalValue","value","getPrototypeOf","Error","checkValue","setInitialValue","setValue","notifySubscribers","resetValue","initialValue","undefined","subscribe","callback","add","unsubscribe","delete","getSubscription","from","forEach","resolvedValue","error","handlePromiseError","checkInitialValue","checkName","checkTypeConstructor","symbolName","Symbol","store","catch","message","handleStoreSetError","controller","stores","unsubscribeFunctions","isArray","length","checkStores","storeNameAsString","toString","slice","camelizedName","onStoreUpdateMethodName","onStoreUpdateMethod","subscription","updateMethod","call","methodName","push","setStoreValueMethodName","resetStoreMethodName","storeGetterMethodName","defineProperty","enumerable","configurable","isWarned","storeProxy","Proxy","target","prop","receiver","warnDirectAccess","Reflect","originalDisconnect","disconnect","bind"],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/stimulus-store/dist/errors/createStoreErrorHandlers.d.ts b/node_modules/stimulus-store/dist/errors/createStoreErrorHandlers.d.ts new file mode 100644 index 0000000..d2556b2 --- /dev/null +++ b/node_modules/stimulus-store/dist/errors/createStoreErrorHandlers.d.ts @@ -0,0 +1,25 @@ +/** + * Checks if the initial value is defined. + * @param {T} initialValue - The initial value of the store. + * @throws {Error} If the initial value is undefined. + */ +export declare function checkInitialValue(initialValue: T): void; +/** + * Checks if the store name is a string. + * @param {string} name - The name of the store. + * @throws {Error} If the store name is not a string. + */ +export declare function checkName(name: string): void; +/** + * Checks if the type constructor exists in the type map. + * @param {string} type - The type of the store value. + * @throws {Error} If the type constructor does not exist in the type map. + */ +export declare function checkTypeConstructor(type: string): void; +/** + * Handles errors that occur when setting the store value. + * @param {unknown} error - The error that occurred. + * @throws {Error} A new error with the same message if the original error is an instance of Error. + * @throws {Error} A new error with a generic message if the original error is not an instance of Error. + */ +export declare function handleStoreSetError(error: unknown): never; diff --git a/node_modules/stimulus-store/dist/errors/storeErrorHandlers.d.ts b/node_modules/stimulus-store/dist/errors/storeErrorHandlers.d.ts new file mode 100644 index 0000000..9ca2628 --- /dev/null +++ b/node_modules/stimulus-store/dist/errors/storeErrorHandlers.d.ts @@ -0,0 +1,13 @@ +/** + * Checks if the value is of the specified type. + * @param {unknown} value - The value to check. + * @param {new (...args: unknown[]) => unknown} type - The type constructor for the expected type. + * @throws {Error} If the value is not of the expected type. + */ +export declare function checkValue(value: unknown, type: new (...args: unknown[]) => unknown): void; +/** + * Handles errors that occur when a promise fails to resolve. + * @param {unknown} error - The error that occurred. + * @throws {Error} A new error with a message indicating that the promise failed to resolve. + */ +export declare function handlePromiseError(error: unknown): never; diff --git a/node_modules/stimulus-store/dist/errors/useStoreErrorHandlers.d.ts b/node_modules/stimulus-store/dist/errors/useStoreErrorHandlers.d.ts new file mode 100644 index 0000000..d55080e --- /dev/null +++ b/node_modules/stimulus-store/dist/errors/useStoreErrorHandlers.d.ts @@ -0,0 +1,6 @@ +/** + * Checks if the stores array is defined, not empty, and is an array. + * @param {unknown} stores - The stores array to check. + * @throws {Error} If the stores array is undefined, empty, or not an array. + */ +export declare function checkStores(stores: unknown): void; diff --git a/node_modules/stimulus-store/dist/errors/useStoreWarningHandlers.d.ts b/node_modules/stimulus-store/dist/errors/useStoreWarningHandlers.d.ts new file mode 100644 index 0000000..4daf591 --- /dev/null +++ b/node_modules/stimulus-store/dist/errors/useStoreWarningHandlers.d.ts @@ -0,0 +1,7 @@ +/** + * Logs a warning message if the store is accessed directly and `isWarned` is false. + * @param {string} camelizedName - The camelized name of the store. + * @param {boolean} isWarned - A flag indicating if the warning has already been logged. + * @returns {boolean} Returns true if the warning was logged, otherwise returns the original `isWarned` value. + */ +export declare function warnDirectAccess(camelizedName: string, isWarned: boolean): boolean; diff --git a/node_modules/stimulus-store/dist/hooks/useStore.d.ts b/node_modules/stimulus-store/dist/hooks/useStore.d.ts new file mode 100644 index 0000000..5a186ac --- /dev/null +++ b/node_modules/stimulus-store/dist/hooks/useStore.d.ts @@ -0,0 +1,40 @@ +import type { StoreController } from 'types'; +/** + * useStore Function + * The useStore function simplifies the process of subscribing to and handling updates from multiple store instances + * within a Stimulus controller. It also allows direct access to store values on the controller. + * How It Works: + * 1. Retrieves the stores from the controller's constructor. + * 2. Iterates over the stores. + * 3. Identifies the type of each store and constructs an update method name. + * 4. Creates update methods for stores if corresponding onStoreUpdate methods exist on the controller. + * 5. Dynamically assigns update methods to the controller with specific names based on store types. + * 6. Subscribes update methods to stores to handle updates. + * 7. Allows direct access to store values on the controller. + * 8. Enhances the controller's disconnect method to include cleanup for all subscriptions. + * + * Usage Example: + * ```javascript + * import { Controller } from "@hotwired/stimulus"; + * import { useStore } from "stimulus-store"; + * import { myStore } from "./stores/myStore"; // Import your store class + * + * export default class extends Controller { + * static stores = [myStore]; + * + * connect() { + * // Use the useStore function to subscribe to specific stores + * useStore(this); + * } + * + * // Implement specific update methods for each store + * onMyStoreUpdate() { + * // Handle updates for MyStore + * console.log("MyStore updated:", this.myStoreValue); + * } + * } + * ``` + * @param {Object} controller - The Stimulus controller instance that wants to subscribe to the stores. + * @template T - The type of data stored in the stores. + */ +export declare function useStore(controller: StoreController): void; diff --git a/node_modules/stimulus-store/dist/index.d.ts b/node_modules/stimulus-store/dist/index.d.ts new file mode 100644 index 0000000..6386668 --- /dev/null +++ b/node_modules/stimulus-store/dist/index.d.ts @@ -0,0 +1,2 @@ +export { useStore } from './hooks/useStore'; +export { createStore } from './store/createStore'; diff --git a/node_modules/stimulus-store/dist/store/createStore.d.ts b/node_modules/stimulus-store/dist/store/createStore.d.ts new file mode 100644 index 0000000..60e6dfa --- /dev/null +++ b/node_modules/stimulus-store/dist/store/createStore.d.ts @@ -0,0 +1,31 @@ +import type { StoreOptions } from '../types/storeOptions'; +import { Store } from './store'; +/** + * The createStore function is a factory function that creates and returns a new instance of the Store class. + * It takes an options object as a parameter, which should include the name, initialValue, and type for the new store. + * + * Here's a technical breakdown of how it works: + * - The function destructure's the name, type, and initialValue properties from the options object. + * - It checks if initialValue is undefined. If it is, the function throws an error because a store must be initialized with a value. + * - It checks if name is not a string. If it isn't, the function throws an error because the store's name must be a string. This name is used to create a unique Symbol which serves as the identifier for the store. + * - It creates a new Symbol using the name and assigns it to symbolName. + * - It creates a new instance of the Store class, passing symbolName, initialValue, and type to the Store constructor, and returns this new instance. + * + * The Store class encapsulates the state (the initialValue) and provides methods to get and set that state. The type is used for type checking to ensure that the store's value always matches the expected type. + * + * Usage Example: + * ```javascript + * const countStore = createStore({ name: 'count', initialValue: 0, type: Number }); + * ``` + * + * @param {StoreOptions} options - The options for the store. + * @param {string} options.name - The name of the store. This will be used to create a unique Symbol. + * @param {T} options.initialValue - The initial value of the store. This must be provided. + * @param {TypeKey} options.type - The type of the store's value. This is used for type checking [String, Number, Boolean, Array, Object]. + * + * @returns {Store} The new store. + * + * @throws {Error} If no initial value is provided. + * @throws {Error} If the name is not a string. + */ +export declare function createStore(options: StoreOptions): Store; diff --git a/node_modules/stimulus-store/dist/store/store.d.ts b/node_modules/stimulus-store/dist/store/store.d.ts new file mode 100644 index 0000000..d001645 --- /dev/null +++ b/node_modules/stimulus-store/dist/store/store.d.ts @@ -0,0 +1,71 @@ +import type { CurrentValueCallback, SetOptions, StoreValue, Subscription, TypeKey } from 'types'; +/** + * @template T The type of the value that the store holds. + * Store Class Explanation: + * + * The `Store` class is a versatile class for managing and subscribing to data updates in JavaScript applications. + * It provides a structured way to store data and notify subscribers when the data changes. + * + * Key Features: + * - Generic Class: Can work with different types of data (specified when creating an instance). + * - Constructor: Sets the initial value of the store. + * - `set` Method: Updates the value and notifies subscribers. + * - `get` Method: Gets the current value. + * - `subscribe` Method: Subscribes to updates and calls a callback function when data changes. + * - `unsubscribe` Method: Removes a subscription. + * - `notifySubscribers` Method: Notifies subscribers when data changes. + */ +export declare class Store { + readonly name: symbol; + private value; + private initialValue; + private subscribers; + private type; + /** + * Creates a new store. + * + * @param {symbol} name - The name of the store. + * @param {TypeKey} type - The type of the store's value. + */ + constructor(name: symbol, type: TypeKey); + /** + * Sets the value of the store and notifies subscribers. + * + * @param {T | CurrentValueCallback | Promise} newValue - The new value. + * @param {SetOptions} [options={ filter: () => true }] - The options for setting the value. + */ + set(newValue: StoreValue | CurrentValueCallback | Promise, options?: SetOptions): Promise; + /** + * Gets the current value of the store. + * + * @returns {StoreValue} The current value. + */ + get(): StoreValue; + /** + * Resets the store to its initial value. + */ + resetValue(): void; + private setValue; + private setInitialValue; + /** + * Subscribes to the store. + * + * @param {UpdateMethod} callback - The function to call when the store's value changes. + * @returns {UnsubscribeFunction} A function that unsubscribes the callback. + */ + private subscribe; + /** + * Unsubscribes from the store. + * + * @param {UpdateMethod} callback - The function to unsubscribe. + */ + private unsubscribe; + /** + * Gets a subscription object with subscribe, when invoked subscribe returns an unsubscribe function. + * + * @returns {Subscription} A subscription object. + */ + getSubscription(): Subscription; + private notifySubscribers; + private resolvePromise; +} diff --git a/node_modules/stimulus-store/dist/store/storeValuesTypeMap.d.ts b/node_modules/stimulus-store/dist/store/storeValuesTypeMap.d.ts new file mode 100644 index 0000000..5628ff0 --- /dev/null +++ b/node_modules/stimulus-store/dist/store/storeValuesTypeMap.d.ts @@ -0,0 +1,11 @@ +import type { TypeKey } from '../types/typeKey'; +/** + * A mapping from type names to their corresponding constructor types. + * - Allows type checking values at runtime. + * - Allows the use of the following types: String, Number, Array, Object, Boolean. + * - Each type has its own constructor type: StringConstructor, NumberConstructor, ArrayConstructor, ObjectConstructor, BooleanConstructor. + * - TypeKey is a union of all the constructor types. + * @type {Record} + * + */ +export declare const typeMap: Record; diff --git a/node_modules/stimulus-store/dist/types/Subscription.d.ts b/node_modules/stimulus-store/dist/types/Subscription.d.ts new file mode 100644 index 0000000..bac638b --- /dev/null +++ b/node_modules/stimulus-store/dist/types/Subscription.d.ts @@ -0,0 +1,6 @@ +import type { UnsubscribeFunction } from './unsubscribeFunction' +import type { UpdateMethod } from './updateMethod' + +export interface Subscription { + subscribe: (callback: UpdateMethod) => UnsubscribeFunction +} diff --git a/node_modules/stimulus-store/dist/types/currentValueCallback.d.ts b/node_modules/stimulus-store/dist/types/currentValueCallback.d.ts new file mode 100644 index 0000000..fec74f0 --- /dev/null +++ b/node_modules/stimulus-store/dist/types/currentValueCallback.d.ts @@ -0,0 +1,5 @@ +import type { StoreValue } from './storeValue' + +export declare type CurrentValueCallback = ( + currentValue: StoreValue, +) => StoreValue diff --git a/node_modules/stimulus-store/dist/types/notifySubscriberOptions.d.ts b/node_modules/stimulus-store/dist/types/notifySubscriberOptions.d.ts new file mode 100644 index 0000000..4b49d0e --- /dev/null +++ b/node_modules/stimulus-store/dist/types/notifySubscriberOptions.d.ts @@ -0,0 +1,3 @@ +import type { SetOptions } from './setOptions.d' + +export declare type NotifySubscriberOptions = SetOptions diff --git a/node_modules/stimulus-store/dist/types/setCallback.d.ts b/node_modules/stimulus-store/dist/types/setCallback.d.ts new file mode 100644 index 0000000..2231b5f --- /dev/null +++ b/node_modules/stimulus-store/dist/types/setCallback.d.ts @@ -0,0 +1,3 @@ +import type { StoreValue } from './storeValue' + +export declare type SetCallback = (value: StoreValue) => StoreValue diff --git a/node_modules/stimulus-store/dist/types/setOptions.d.ts b/node_modules/stimulus-store/dist/types/setOptions.d.ts new file mode 100644 index 0000000..526cc86 --- /dev/null +++ b/node_modules/stimulus-store/dist/types/setOptions.d.ts @@ -0,0 +1,5 @@ +import type { StoreValue } from './storeValue' + +export declare type SetOptions = { + filter: (value: StoreValue) => boolean +} diff --git a/node_modules/stimulus-store/dist/types/storeController.d.ts b/node_modules/stimulus-store/dist/types/storeController.d.ts new file mode 100644 index 0000000..1d9d111 --- /dev/null +++ b/node_modules/stimulus-store/dist/types/storeController.d.ts @@ -0,0 +1,24 @@ +import type { Controller } from '@hotwired/stimulus' +import type { Store } from '../store/store' + +/** + * Interface for a StoreController. + * @template T The type of the store's value. + * @extends {Controller} + */ +export interface StoreController extends Controller { + /** + * Allows any additional properties. + */ + [key: string]: any + + /** + * The constructor for the StoreController. + */ + constructor: { + /** + * An optional array of stores. + */ + stores?: Store[] + } +} diff --git a/node_modules/stimulus-store/dist/types/storeOptions.d.ts b/node_modules/stimulus-store/dist/types/storeOptions.d.ts new file mode 100644 index 0000000..15fd4aa --- /dev/null +++ b/node_modules/stimulus-store/dist/types/storeOptions.d.ts @@ -0,0 +1,23 @@ +import type { StoreValue } from './storeValue' +import type { TypeKey } from './typeKey' + +/** + * Interface for the options to create a store. + * @template T The type of the store's initial value. + */ +export interface StoreOptions { + /** + * The name of the store. + */ + name: string + + /** + * The type of the store's value. + */ + type: TypeKey + + /** + * The initial value of the store. + */ + initialValue: StoreValue +} diff --git a/node_modules/stimulus-store/dist/types/storeValue.d.ts b/node_modules/stimulus-store/dist/types/storeValue.d.ts new file mode 100644 index 0000000..76b7347 --- /dev/null +++ b/node_modules/stimulus-store/dist/types/storeValue.d.ts @@ -0,0 +1 @@ +export type StoreValue = string | number | boolean | object | Array diff --git a/node_modules/stimulus-store/dist/types/typeKey.d.ts b/node_modules/stimulus-store/dist/types/typeKey.d.ts new file mode 100644 index 0000000..c627de7 --- /dev/null +++ b/node_modules/stimulus-store/dist/types/typeKey.d.ts @@ -0,0 +1,6 @@ +type String = new (...args: unknown[]) => string +type Number = new (...args: unknown[]) => number +type Array = new (...args: unknown[]) => unknown[] +type Object = new (...args: unknown[]) => object +type Boolean = new (...args: unknown[]) => boolean +export type TypeKey = String | Number | Array | Object | Boolean diff --git a/node_modules/stimulus-store/dist/types/unsubscribeFunction.d.ts b/node_modules/stimulus-store/dist/types/unsubscribeFunction.d.ts new file mode 100644 index 0000000..bfee9b2 --- /dev/null +++ b/node_modules/stimulus-store/dist/types/unsubscribeFunction.d.ts @@ -0,0 +1 @@ +export declare type UnsubscribeFunction = () => void diff --git a/node_modules/stimulus-store/dist/types/updateMethod.d.ts b/node_modules/stimulus-store/dist/types/updateMethod.d.ts new file mode 100644 index 0000000..a12f966 --- /dev/null +++ b/node_modules/stimulus-store/dist/types/updateMethod.d.ts @@ -0,0 +1,3 @@ +import type { StoreValue } from './storeValue' + +export declare type UpdateMethod = (value: StoreValue) => void diff --git a/node_modules/stimulus-store/dist/utils/camelize.d.ts b/node_modules/stimulus-store/dist/utils/camelize.d.ts new file mode 100644 index 0000000..d91dfc4 --- /dev/null +++ b/node_modules/stimulus-store/dist/utils/camelize.d.ts @@ -0,0 +1 @@ +export declare function camelize(str: string, firstCharUppercase?: boolean): string; diff --git a/node_modules/stimulus-store/package.json b/node_modules/stimulus-store/package.json new file mode 100644 index 0000000..ea8414a --- /dev/null +++ b/node_modules/stimulus-store/package.json @@ -0,0 +1,92 @@ +{ + "name": "stimulus-store", + "version": "0.0.3", + "description": "Lightweight state management for Stimulus.js", + "main": "dist/bundle.cjs.js", + "module": "dist/bundle.esm.js", + "types": "dist/index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/omarluq/stimulus-store.git" + }, + "bugs": { + "url": "https://github.com/omarluq/stimulus-store/issues" + }, + "homepage": "https://github.com/omarluq/stimulus-store#readme", + "files": [ + "dist/**/*" + ], + "scripts": { + "build": "rollup -c --bundleConfigAsCjs", + "test": "vitest run --coverage", + "test:ui": "vitest --ui --coverage.enabled=true", + "lint": "biome lint .", + "lint:fix": "biome check --apply .", + "lint:fix:unsafe": "biome check --apply-unsafe .", + "format:check": "biome format .", + "format:write": "biome format --write .", + "size": "size-limit", + "changelog": "git-chglog -o docs/CHANGELOG.md", + "docs": "docsify serve docs", + "prepack": "cp docs/README.md . && cp docs/CHANGELOG.md . && cp docs/LICENSE.md . && cp -r dist/* .", + "postpack": "git clean -f -d" + }, + "keywords": [ + "stimulus", + "store", + "stimulusjs", + "state-management", + "javascript", + "frontend", + "web-development", + "client-side", + "data-store", + "mvc", + "stimulus-controller" + ], + "author": "Omar Luq ", + "contributors": [ + "Tomas Caraccia " + ], + "license": "MIT", + "devDependencies": { + "@biomejs/biome": "1.8.3", + "@commitlint/cli": "^19.0.3", + "@commitlint/config-conventional": "^19.0.3", + "@hotwired/stimulus": "^3.2.2", + "@rollup/plugin-commonjs": "^26.0.1", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.5", + "@size-limit/preset-small-lib": "^11.0.2", + "@size-limit/time": "^11.0.2", + "@types/node": "^20.10.0", + "@vitest/coverage-istanbul": "^1.6.0", + "@vitest/ui": "^1.6.0", + "all-contributors-cli": "^6.26.1", + "lefthook": "^1.6.1", + "rollup": "^4.5.1", + "rollup-plugin-analyzer": "^4.0.0", + "rollup-plugin-copy": "^3.5.0", + "rollup-plugin-sizes": "^1.0.6", + "size-limit": "^11.0.0", + "ts-node": "^10.9.1", + "tslib": "^2.6.2", + "typescript": "^5.2.2", + "vitest": "1.6.0" + }, + "size-limit": [ + { + "path": "./dist/bundle.cjs.js", + "limit": "1.2 KB" + }, + { + "path": "./dist/bundle.esm.js", + "limit": "1.2 KB" + }, + { + "path": "./dist/bundle.umd.js", + "limit": "1.25 KB" + } + ] +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..0df31ec --- /dev/null +++ b/package-lock.json @@ -0,0 +1,18 @@ +{ + "name": "Specification", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "stimulus-store": "^0.0.3" + } + }, + "node_modules/stimulus-store": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/stimulus-store/-/stimulus-store-0.0.3.tgz", + "integrity": "sha512-SQGdf2BZpItO0g1jW1vwwA9ZRvlymoQJQe9r8pfTkZ+NsPgkXR5uO8y8Ue+tQDZa8DSAD3RZ1Io2YuDVnBygJQ==", + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..24b8c3b --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "stimulus-store": "^0.0.3" + } +}