├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md ├── babel.config.js ├── express-js-mod ├── express-js-mod.js ├── helpers │ ├── Response.js │ ├── bodyParsers.js │ ├── messageTranslation.js │ └── parseQuery.js └── manifest.json ├── jest.config.js ├── package.json ├── spec ├── helpers │ └── parseQuery.spec.ts ├── index.spec.ts └── mockCallback.ts ├── src ├── express-js-mod.ts ├── helpers │ ├── Response.ts │ ├── bodyParsers.ts │ ├── messageTranslation.ts │ └── parseQuery.ts ├── manifest.json └── xs.d.ts ├── tsconfig.json ├── tslint.json └── yarn.lock /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: juniper-garden 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/**/* 2 | .expo/* 3 | npm-debug.* 4 | *.jks 5 | *.p8 6 | *.p12 7 | *.key 8 | *.mobileprovision 9 | *.orig.* 10 | web-build/ 11 | web-report/ 12 | 13 | # macOS 14 | .DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Express JS Mod 3 | This is a express like package for working in the [Moddable SDK](https://www.moddable.com/). 4 | This is not meant to be a 1-1 port, but it attempts to maintain the same interface 5 | we know from [express](https://expressjs.com/). 6 | 7 | ## Installation 8 | `git clone https://github.com/dashcraft/express-js-mod.git` or `git clone git@github.com:dashcraft/express-js-mod.git` 9 | `cd express-js-mod && yarn install` 10 | `yarn build` 11 | 12 | Copy the `/express-js-mod` folder into your moddable sdk project, 13 | then add the express-js-mod package to your projects manifest.json includes: 14 | 15 | `"./express-js-mod/manifest.json"` 16 | 17 | ## Usage 18 | First import the primary package 19 | `import Express from 'express-js-mod'` 20 | Afterwards, when the moddable sdk server has been created... 21 | `import { Server } from "http";` 22 | 23 | We can add routes and callbacks like... 24 | 25 | let app = new Express(Server) 26 | app.get('/home', function(req,res) { 27 | res.status(200) 28 | res.json({test: 'test'}) 29 | }) 30 | let port = 80 // 80 is the default anyways 31 | app.listen(port) 32 | 33 | We can send resources as responses in routes and callbacks like... 34 | 35 | let app = new Express(Server) 36 | app.get('/home', function(req,res) { 37 | res.sendResource(new Resource("index.html")) 38 | }) 39 | let port = 80 // 80 is the default port 40 | app.listen(port) 41 | 42 | ## Todo 43 | 44 | - [ ] Tests, tests, more tests 45 | - [x] Query Params 46 | - [x] Inbound Data Handling 47 | - [ ] Post route test 48 | - [ ] Put/Patch route test 49 | - [ ] Delete route test 50 | - [ ] Support Hash of Routes using app.route() 51 | - [ ] Inbound Chunked Buffer handling 52 | - [ ] Outbound Chunked Buffer handling 53 | - [x] res.sendResource() 54 | - [ ] mime-types 55 | - [ ] buffers 56 | - [ ] Event Streams 57 | - [ ] Add fallback route support 58 | - [ ] Add regex route matching support 59 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | ["@babel/preset-env", { targets: { node: "current" } }], 4 | "@babel/preset-typescript", 5 | ], 6 | }; 7 | -------------------------------------------------------------------------------- /express-js-mod/express-js-mod.js: -------------------------------------------------------------------------------- 1 | import { MessageValue } from "helpers/messageTranslation"; 2 | import Response from "helpers/Response"; 3 | import parseQuery from 'helpers/parseQuery'; 4 | import { parseJson } from "helpers/bodyParsers"; 5 | const validMethods = Object.freeze(["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]); 6 | const Default404 = Object.freeze({ headers: Object.freeze(["Content-type", "text/html"]), body: "Resource Not Found", status: 404 }); 7 | const bodyParseMap = Object.freeze({ 8 | 'application/json': parseJson, 9 | 'application/text+html': (data) => data, 10 | 'application/text': (data) => data, 11 | 'application/html': (data) => data, 12 | 'text/html': (data) => data, 13 | }); 14 | export default class Express { 15 | serverInstance; 16 | server; 17 | defaultPort = 80; 18 | routes = { 19 | get: new Map(), 20 | post: new Map(), 21 | put: new Map(), 22 | patch: new Map(), 23 | delete: new Map(), 24 | }; 25 | constructor(ModdableHttpServer) { 26 | this.serverInstance = this.curriedServer(ModdableHttpServer); 27 | } 28 | createResponse = () => { 29 | return new Response(); 30 | }; 31 | curriedServer = (Server) => { 32 | return (port) => { 33 | return new Server({ port: port || this.defaultPort }); 34 | }; 35 | }; 36 | listen(port) { 37 | let server = this.serverInstance(port); 38 | this.server = server; 39 | let self = this; 40 | server.callback = function instantiateRoute(message, val1, val2) { 41 | switch (message) { 42 | case MessageValue.error: 43 | break; 44 | case MessageValue.connection: 45 | this.inboundRequest = { 46 | state: 'status', 47 | headers: {}, 48 | path: null, 49 | httpMethod: null, 50 | data: null 51 | }; 52 | this.outboundResponse = self.createResponse(); 53 | break; 54 | case MessageValue.status: 55 | let parsed = parseQuery(val1); 56 | this.inboundRequest.path = parsed.path; 57 | this.inboundRequest.params = parsed.search; 58 | this.inboundRequest.rawQuery = parsed.query; 59 | this.inboundRequest.location = parsed.relative; 60 | this.inboundRequest.httpMethod = val2.toLowerCase(); 61 | this.inboundRequest.state = 'headers'; 62 | break; 63 | case MessageValue.header: 64 | if (!val1 || !val2) 65 | break; 66 | this.inboundRequest.headers[`${val1}`] = val2; 67 | break; 68 | case MessageValue.headersComplete: 69 | this.inboundRequest.state = "fragment"; 70 | return String; 71 | case MessageValue.requestFragment: 72 | break; 73 | case MessageValue.requestComplete: 74 | if (!bodyParseMap[this.inboundRequest.headers["content-type"]]) { 75 | this.inboundRequest.data = val1; 76 | } 77 | else { 78 | this.inboundRequest.data = bodyParseMap[this.inboundRequest.headers["content-type"]](val1); 79 | } 80 | this.inboundRequest.state = "done"; 81 | break; 82 | case MessageValue.prepareResponse: 83 | const req = this.inboundRequest; 84 | const res = this.outboundResponse; 85 | const route = self.routes[req.httpMethod].get(req.path); 86 | if (!route) 87 | return Default404; 88 | const handlerCb = route.cb; 89 | if (!handlerCb) 90 | return Default404; 91 | // Do stuff here with routes 92 | let result = () => { 93 | handlerCb(req, res); 94 | return res.build(); 95 | }; 96 | return result(); 97 | case MessageValue.responseFragment: 98 | // do stuff here with chunked data 99 | if (this.outboundResponse.hasChunkResponse) { 100 | return this.outboundResponse.sendChunkResource(val1); 101 | } 102 | break; 103 | case MessageValue.responseComplete: 104 | // do stuff here with posts 105 | this.socket.close(); 106 | break; 107 | } 108 | }; 109 | } 110 | get = (path, cb) => this.addRoute('get')(path, cb); 111 | post = (path, cb) => this.addRoute('post')(path, cb); 112 | put = (path, cb) => this.addRoute('put')(path, cb); 113 | patch = (path, cb) => this.addRoute('patch')(path, cb); 114 | delete = (path, cb) => this.addRoute('delete')(path, cb); 115 | addRoute = (method) => { 116 | const valid = validMethods.find(m => m.toLowerCase() === method); 117 | if (!valid) 118 | throw new Error('That HTTP method is not valid.'); 119 | return (path, cb) => { 120 | if (!path || !cb) 121 | throw new Error('Path or callback was not given'); 122 | let routeExist = this.routes[method].get(`${path}`); 123 | if (routeExist) 124 | throw new Error('The defined route already exists'); 125 | this.routes[method].set(path, Object.freeze({ cb })); 126 | }; 127 | }; 128 | get allRoutes() { 129 | return this.routes; 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /express-js-mod/helpers/Response.js: -------------------------------------------------------------------------------- 1 | export default class Response { 2 | headers = []; 3 | requestStatus = 201; 4 | body = ''; 5 | data = null; 6 | position; 7 | status(status) { 8 | this.requestStatus = status; 9 | } 10 | json(obj) { 11 | try { 12 | this.body = JSON.stringify(obj); 13 | this.headers.push('Content-Type'); 14 | this.headers.push('application/json'); 15 | } 16 | catch (err) { 17 | trace('INVALID JSON DATA'); 18 | throw new Error('INVALID JSON DATA'); 19 | } 20 | } 21 | sendResource(resource, contentType) { 22 | try { 23 | this.headers.push('Content-Type'); 24 | this.headers.push(contentType); 25 | this.data = resource; 26 | this.position = 0; 27 | return { 28 | headers: [ 29 | "Content-type", this.headers, 30 | "Content-length", this.data.byteLength, 31 | ], 32 | status: this.requestStatus, 33 | body: true, 34 | }; 35 | } 36 | catch (err) { 37 | return { 38 | status: 404, 39 | headers: [ 40 | "Content-type", "text/plain", 41 | ], 42 | body: "file not found", 43 | }; 44 | } 45 | } 46 | get hasChunkResponse() { 47 | return this.data; 48 | } 49 | sendChunkResource(value) { 50 | if (this.position >= this.data.byteLength) 51 | return; 52 | const chunk = this.data.slice(this.position, this.position + value); 53 | this.position += chunk.byteLength; 54 | return chunk; 55 | } 56 | build() { 57 | return { 58 | headers: this.headers, 59 | status: this.requestStatus, 60 | body: this.body 61 | }; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /express-js-mod/helpers/bodyParsers.js: -------------------------------------------------------------------------------- 1 | export function parseJson(data) { 2 | try { 3 | return JSON.parse(data); 4 | } 5 | catch (err) { 6 | throw new Error("INVALID JSON IN REQUEST BODY"); 7 | } 8 | } 9 | export function parseText(data) { 10 | return data; 11 | } 12 | -------------------------------------------------------------------------------- /express-js-mod/helpers/messageTranslation.js: -------------------------------------------------------------------------------- 1 | export const MessageTranslations = Object.freeze({ 2 | [-1]: "error", 3 | 1: "connection", 4 | 2: "status", 5 | 3: "header", 6 | 4: "headersComplete", 7 | 5: "requestFragment", 8 | 6: "requestComplete", 9 | 8: "prepareResponse", 10 | 9: "responseFragment", 11 | 10: "responseComplete" 12 | }); 13 | export const MessageValue = Object.freeze({ 14 | "error": -1, 15 | "connection": 1, 16 | "status": 2, 17 | "header": 3, 18 | "headersComplete": 4, 19 | "requestFragment": 5, 20 | "requestComplete": 6, 21 | "prepareResponse": 8, 22 | "responseFragment": 9, 23 | "responseComplete": 10 24 | }); 25 | -------------------------------------------------------------------------------- /express-js-mod/helpers/parseQuery.js: -------------------------------------------------------------------------------- 1 | // https://blog.stevenlevithan.com/archives/parseuri 2 | // MIT License 3 | // https://blog.stevenlevithan.com/ 4 | // https://github.com/slevithan 5 | function parseQuery(str) { 6 | let o = parseQuery.options, m = new RegExp(/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/).exec(str), uri = {}, i = 14; 7 | while (i--) 8 | uri[o.key[i]] = m[i] || ""; 9 | uri['search'] = {}; 10 | uri[o.key[12]].replace(new RegExp(/(?:^|&)([^&=]*)=?([^&]*)/g), function ($0, $1, $2) { 11 | if ($1) 12 | uri['search'][$1] = $2; 13 | }); 14 | return uri; 15 | } 16 | ; 17 | parseQuery.options = Object.freeze({ 18 | strictMode: false, 19 | key: Object.freeze(["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"]) 20 | }); 21 | Object.freeze(parseQuery); 22 | export default parseQuery; 23 | -------------------------------------------------------------------------------- /express-js-mod/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "preload": [ 3 | "helpers/*", 4 | "express-js-mod", 5 | "http" 6 | ], 7 | "modules": { 8 | "*": [ 9 | "./*" 10 | ], 11 | "helpers/*": "./helpers/*" 12 | } 13 | } -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // For a detailed explanation regarding each configuration property, visit: 2 | // https://jestjs.io/docs/en/configuration.html 3 | 4 | module.exports = { 5 | // All imported modules in your tests should be mocked automatically 6 | // automock: false, 7 | 8 | // Stop running tests after `n` failures 9 | // bail: 0, 10 | 11 | // Respect "browser" field in package.json when resolving modules 12 | // browser: false, 13 | 14 | // The directory where Jest should store its cached dependency information 15 | // cacheDirectory: "C:\\Users\\danie\\AppData\\Local\\Temp\\jest", 16 | 17 | // Automatically clear mock calls and instances between every test 18 | clearMocks: true, 19 | 20 | // Indicates whether the coverage information should be collected while executing the test 21 | // collectCoverage: false, 22 | 23 | // An array of glob patterns indicating a set of files for which coverage information should be collected 24 | // collectCoverageFrom: null, 25 | 26 | // The directory where Jest should output its coverage files 27 | coverageDirectory: "coverage", 28 | 29 | // An array of regexp pattern strings used to skip coverage collection 30 | // coveragePathIgnorePatterns: [ 31 | // "\\\\node_modules\\\\" 32 | // ], 33 | 34 | // A list of reporter names that Jest uses when writing coverage reports 35 | // coverageReporters: [ 36 | // "json", 37 | // "text", 38 | // "lcov", 39 | // "clover" 40 | // ], 41 | 42 | // An object that configures minimum threshold enforcement for coverage results 43 | // coverageThreshold: null, 44 | 45 | // A path to a custom dependency extractor 46 | // dependencyExtractor: null, 47 | 48 | // Make calling deprecated APIs throw helpful error messages 49 | // errorOnDeprecated: false, 50 | 51 | // Force coverage collection from ignored files usin a array of glob patterns 52 | // forceCoverageMatch: [], 53 | 54 | // A path to a module which exports an async function that is triggered once before all test suites 55 | // globalSetup: null, 56 | 57 | // A path to a module which exports an async function that is triggered once after all test suites 58 | // globalTeardown: null, 59 | 60 | // A set of global variables that need to be available in all test environments 61 | // globals: {}, 62 | 63 | // An array of directory names to be searched recursively up from the requiring module's location 64 | // moduleDirectories: [ 65 | // "node_modules" 66 | // ], 67 | 68 | // An array of file extensions your modules use 69 | // moduleFileExtensions: [ 70 | // "js", 71 | // "json", 72 | // "jsx", 73 | // "ts", 74 | // "tsx", 75 | // "node" 76 | // ], 77 | 78 | // A map from regular expressions to module names that allow to stub out resources with a single module 79 | moduleNameMapper: { 80 | "^helpers/(.*)$": "/src/helpers/$1", 81 | }, 82 | 83 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 84 | // modulePathIgnorePatterns: [], 85 | 86 | // Activates notifications for test results 87 | // notify: false, 88 | 89 | // An enum that specifies notification mode. Requires { notify: true } 90 | // notifyMode: "failure-change", 91 | 92 | // A preset that is used as a base for Jest's configuration 93 | // preset: null, 94 | 95 | // Run tests from one or more projects 96 | // projects: null, 97 | 98 | // Use this configuration option to add custom reporters to Jest 99 | // reporters: undefined, 100 | 101 | // Automatically reset mock state between every test 102 | // resetMocks: false, 103 | 104 | // Reset the module registry before running each individual test 105 | // resetModules: false, 106 | 107 | // A path to a custom resolver 108 | // resolver: null, 109 | 110 | // Automatically restore mock state between every test 111 | // restoreMocks: false, 112 | 113 | // The root directory that Jest should scan for tests and modules within 114 | // rootDir: null, 115 | 116 | // A list of paths to directories that Jest should use to search for files in 117 | // roots: [ 118 | // "" 119 | // ], 120 | 121 | // Allows you to use a custom runner instead of Jest's default test runner 122 | // runner: "jest-runner", 123 | 124 | // The paths to modules that run some code to configure or set up the testing environment before each test 125 | // setupFiles: [], 126 | 127 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 128 | // setupFilesAfterEnv: [], 129 | 130 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 131 | // snapshotSerializers: [], 132 | 133 | // The test environment that will be used for testing 134 | testEnvironment: "node", 135 | 136 | // Options that will be passed to the testEnvironment 137 | // testEnvironmentOptions: {}, 138 | 139 | // Adds a location field to test results 140 | // testLocationInResults: false, 141 | 142 | // The glob patterns Jest uses to detect test files 143 | // testMatch: [ 144 | // "**/__tests__/**/*.[jt]s?(x)", 145 | // "**/?(*.)+(spec|test).[tj]s?(x)" 146 | // ], 147 | 148 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 149 | // testPathIgnorePatterns: [ 150 | // "\\\\node_modules\\\\" 151 | // ], 152 | 153 | // The regexp pattern or array of patterns that Jest uses to detect test files 154 | // testRegex: [], 155 | 156 | // This option allows the use of a custom results processor 157 | // testResultsProcessor: null, 158 | 159 | // This option allows use of a custom test runner 160 | // testRunner: "jasmine2", 161 | 162 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href 163 | // testURL: "http://localhost", 164 | 165 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" 166 | // timers: "real", 167 | 168 | // A map from regular expressions to paths to transformers 169 | // transform: null, 170 | 171 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 172 | // transformIgnorePatterns: [ 173 | // "\\\\node_modules\\\\" 174 | // ], 175 | 176 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 177 | // unmockedModulePathPatterns: undefined, 178 | 179 | // Indicates whether each individual test should be reported during the run 180 | // verbose: null, 181 | 182 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 183 | // watchPathIgnorePatterns: [], 184 | 185 | // Whether to use watchman for file crawling 186 | // watchman: true, 187 | }; 188 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-js-mod", 3 | "version": "1.0.5", 4 | "description": "An express like router for moddable sdk and XS javascript engine", 5 | "main": "./express-js-mod/express-js-mod.js", 6 | "keywords": "moddable,xs,express,embedded,iot", 7 | "homepage": "https://github.com/dashcraft/express-js-mod", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/dashcraft/express-js-mod" 11 | }, 12 | "scripts": { 13 | "build": "tsc --build", 14 | "clean": "tsc --build --clean", 15 | "test": "jest", 16 | "postbuild": "cpy ./src/*.json ./express-js-mod" 17 | }, 18 | "author": "Daniel Ashcraft (https://www.ofashandfire.com)", 19 | "license": "GPLv2", 20 | "devDependencies": { 21 | "@babel/core": "^7.14.3", 22 | "@babel/preset-env": "^7.14.4", 23 | "@babel/preset-typescript": "^7.13.0", 24 | "@types/jest": "^26.0.23", 25 | "@vercel/ncc": "^0.28.6", 26 | "babel-cli": "^6.26.0", 27 | "babel-jest": "^27.0.2", 28 | "cpy": "^8.1.2", 29 | "cpy-cli": "^3.1.1", 30 | "jest": "^27.0.4", 31 | "ts-loader": "^9.2.2", 32 | "typescript": "^4.3.2", 33 | "webpack": "^5.38.1", 34 | "webpack-cli": "^4.7.0" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /spec/helpers/parseQuery.spec.ts: -------------------------------------------------------------------------------- 1 | import parseQuery from '../../src/helpers/parseQuery'; 2 | 3 | describe("Parse Query func unit tests", () => { 4 | it('Should parse out query params from path', () => { 5 | let path = "moddable.com/test?id=1&name=cool_name" 6 | let parsed = parseQuery(path) 7 | expect(parsed.relative).toBe("moddable.com/test?id=1&name=cool_name") 8 | expect(parsed.path).toBe("moddable.com/test") 9 | expect(parsed.search.id).toBe("1") 10 | expect(parsed.search.name).toBe("cool_name") 11 | }) 12 | }) -------------------------------------------------------------------------------- /spec/index.spec.ts: -------------------------------------------------------------------------------- 1 | import Express, { HttpServer } from '../src/express-js-mod'; 2 | 3 | 4 | describe('Unit Tests for Express', () => { 5 | it('Should build a class fine', () => { 6 | const errorPayload = { 7 | message: -1 8 | } 9 | 10 | class MockServer implements HttpServer{ 11 | port?: Number 12 | constructor(port?: Number){ 13 | this.port = port 14 | } 15 | close = jest.fn(() => true) 16 | callback = jest.fn(() => errorPayload) 17 | } 18 | 19 | let express = new Express(MockServer) 20 | 21 | expect(express).toBeTruthy() 22 | }) 23 | 24 | describe('Route methods', () => { 25 | let express 26 | beforeAll(() => { 27 | const errorPayload = { 28 | message: -1 29 | } 30 | 31 | class MockServer implements HttpServer{ 32 | port?: Number 33 | constructor(port?: Number){ 34 | this.port = port 35 | } 36 | close = jest.fn(() => true) 37 | callback = jest.fn(() => errorPayload) 38 | } 39 | 40 | express = new Express(MockServer) 41 | }) 42 | 43 | it('Should build a class fine', () => { 44 | let fakeCbOne = jest.fn() 45 | let fakeCbTwo = jest.fn() 46 | express.get('/path', fakeCbOne) 47 | express.get('/hello', fakeCbTwo) 48 | 49 | expect(express.allRoutes.get.size).toBe(2) 50 | express.allRoutes.get.get('/path').cb() 51 | expect(fakeCbOne).toHaveBeenCalledTimes(1) 52 | 53 | express.allRoutes.get.get('/hello').cb() 54 | expect(fakeCbTwo).toHaveBeenCalledTimes(1) 55 | }) 56 | 57 | it('Should build a class fine', () => { 58 | let fakeCbOne = jest.fn() 59 | let fakeCbTwo = jest.fn() 60 | 61 | express.post('/path', fakeCbOne) 62 | express.post('/hello', fakeCbTwo) 63 | 64 | expect(express.allRoutes.get.size).toBe(2) 65 | express.allRoutes.post.get('/path').cb() 66 | expect(fakeCbOne).toHaveBeenCalledTimes(1) 67 | express.allRoutes.post.get('/hello').cb() 68 | expect(fakeCbTwo).toHaveBeenCalledTimes(1) 69 | }) 70 | it('Should blow up trying to add a route with invalid http method', () => { 71 | expect(() => express.addRoute('cool')).toThrow(Error) 72 | expect(() => express.addRoute('cool')('/path', jest.fn)).toThrow(Error) 73 | }) 74 | 75 | it('Should blow up adding a route without a path or cb', () => { 76 | expect(() => express.addRoute('post')(null, jest.fn)).toThrow(Error) 77 | expect(() => express.addRoute('get')('test', null)).toThrow(Error) 78 | }) 79 | }) 80 | 81 | 82 | }) -------------------------------------------------------------------------------- /spec/mockCallback.ts: -------------------------------------------------------------------------------- 1 | const socketWrite = [ 2 | {message: "", val1: "", val2:""}, 3 | {message: "", val1: "", val2:""}, 4 | {message: "", val1: "", val2:""}, 5 | {message: "", val1: "", val2:""}, 6 | {message: "", val1: "", val2:""}, 7 | {message: "", val1: "", val2:""}, 8 | {message: "", val1: "", val2:""}, 9 | {message: "", val1: "", val2:""}, 10 | {message: "", val1: "", val2:""}, 11 | {message: "", val1: "", val2:""}, 12 | {message: "", val1: "", val2:""} 13 | ] 14 | 15 | export default socketWrite -------------------------------------------------------------------------------- /src/express-js-mod.ts: -------------------------------------------------------------------------------- 1 | import { MessageValue } from "helpers/messageTranslation"; 2 | import Response from "helpers/Response"; 3 | import parseQuery from 'helpers/parseQuery' 4 | import { parseJson } from "helpers/bodyParsers"; 5 | 6 | const validMethods:ReadonlyArray = Object.freeze(["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]) 7 | 8 | interface RouteMap { 9 | [key:string] : Route; 10 | } 11 | 12 | interface Route { 13 | [key:string]: any 14 | } 15 | 16 | const Default404: Readonly<{}> = Object.freeze({ headers: Object.freeze(["Content-type", "text/html"]), body: "Resource Not Found", status: 404 }) 17 | 18 | const bodyParseMap: any = Object.freeze({ 19 | 'application/json': parseJson, 20 | 'application/text+html': (data:string) => data, 21 | 'application/text': (data:string) => data, 22 | 'application/html': (data:string) => data, 23 | 'text/html': (data:string) => data, 24 | }) 25 | 26 | export interface HttpServer { 27 | port?: Number 28 | close: () => any 29 | callback: (message?: Number, path?: String, method?: String) => any; 30 | error?: Number 31 | connection?: Number, 32 | status?: Number, 33 | header?: Number, 34 | headersComplete?: Number, 35 | requestFragment?: Number, 36 | requestComplete?: Number, 37 | prepareResponse?: Number, 38 | responseFragment?: Number, 39 | responseComplete?: Number 40 | } 41 | 42 | export default class Express { 43 | private serverInstance: any; 44 | server: HttpServer | undefined; 45 | defaultPort: Number = 80; 46 | private routes: RouteMap = { 47 | get: new Map(), 48 | post: new Map(), 49 | put: new Map(), 50 | patch: new Map(), 51 | delete: new Map(), 52 | } 53 | constructor(ModdableHttpServer: any) { 54 | this.serverInstance = this.curriedServer(ModdableHttpServer) 55 | } 56 | 57 | createResponse = () => { 58 | return new Response() 59 | } 60 | 61 | curriedServer = (Server: any) => { 62 | return (port: Number) => { 63 | return new Server({port: port || this.defaultPort}) 64 | } 65 | } 66 | 67 | listen(port?: Number) { 68 | let server = this.serverInstance(port) 69 | this.server = server 70 | let self = this 71 | server.callback = function instantiateRoute(message:any, val1:any, val2:any) { 72 | switch (message) { 73 | case MessageValue.error: 74 | break; 75 | case MessageValue.connection: 76 | this.inboundRequest = { 77 | state: 'status', 78 | headers: {}, 79 | path: null, 80 | httpMethod: null, 81 | data: null 82 | } 83 | this.outboundResponse = self.createResponse() 84 | break; 85 | case MessageValue.status: 86 | let parsed = parseQuery(val1) 87 | this.inboundRequest.path = parsed.path 88 | this.inboundRequest.params = parsed.search 89 | this.inboundRequest.rawQuery = parsed.query 90 | this.inboundRequest.location = parsed.relative 91 | this.inboundRequest.httpMethod = val2.toLowerCase() 92 | this.inboundRequest.state = 'headers' 93 | break; 94 | case MessageValue.header: 95 | if(!val1 || !val2) break 96 | this.inboundRequest.headers[`${val1}`] = val2 97 | break; 98 | case MessageValue.headersComplete: 99 | this.inboundRequest.state = "fragment" 100 | return String; 101 | case MessageValue.requestFragment: 102 | break; 103 | case MessageValue.requestComplete: 104 | if(!bodyParseMap[this.inboundRequest.headers["content-type"]]) { 105 | this.inboundRequest.data = val1 106 | } else { 107 | this.inboundRequest.data = bodyParseMap[this.inboundRequest.headers["content-type"]](val1) 108 | } 109 | this.inboundRequest.state = "done" 110 | break; 111 | case MessageValue.prepareResponse: 112 | const req = this.inboundRequest 113 | const res = this.outboundResponse 114 | const route = self.routes[req.httpMethod].get(req.path) 115 | if(!route) return Default404 116 | const handlerCb = route.cb 117 | if(!handlerCb) return Default404; 118 | // Do stuff here with routes 119 | let result = () => { 120 | handlerCb(req, res) 121 | return res.build() 122 | } 123 | return result() 124 | case MessageValue.responseFragment: 125 | // do stuff here with chunked data 126 | if (this.outboundResponse.hasChunkResponse) { 127 | return this.outboundResponse.sendChunkResource(val1) 128 | } 129 | break; 130 | case MessageValue.responseComplete: 131 | // do stuff here with posts 132 | this.socket.close(); 133 | break; 134 | } 135 | }; 136 | } 137 | get = (path: String, cb: () => any) => this.addRoute('get')(path,cb) 138 | 139 | post = (path: String, cb: () => any) => this.addRoute('post')(path,cb) 140 | 141 | put = (path: String, cb: () => any) => this.addRoute('put')(path,cb) 142 | 143 | patch = (path: String, cb: () => any) => this.addRoute('patch')(path,cb) 144 | 145 | delete = (path: String, cb: () => any) => this.addRoute('delete')(path,cb) 146 | 147 | addRoute = (method: string): any => { 148 | const valid = validMethods.find(m => m.toLowerCase() === method) 149 | if(!valid) throw new Error('That HTTP method is not valid.') 150 | return (path: string, cb: () => void) => { 151 | if(!path || !cb) throw new Error('Path or callback was not given') 152 | let routeExist = this.routes[method].get(`${path}`) 153 | if(routeExist) throw new Error('The defined route already exists') 154 | this.routes[method].set(path, Object.freeze({cb})) 155 | } 156 | } 157 | 158 | get allRoutes () { 159 | return this.routes 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/helpers/Response.ts: -------------------------------------------------------------------------------- 1 | export default class Response { 2 | headers: string[] = []; 3 | requestStatus: Number = 201; 4 | body: string = '' 5 | data: any = null; 6 | position: any; 7 | status(status: Number){ 8 | this.requestStatus = status 9 | } 10 | 11 | json(obj: any) { 12 | try { 13 | this.body = JSON.stringify(obj) 14 | this.headers.push('Content-Type'); 15 | this.headers.push('application/json') 16 | } catch(err) { 17 | trace('INVALID JSON DATA') 18 | throw new Error('INVALID JSON DATA') 19 | } 20 | } 21 | 22 | sendResource(resource:any, contentType: string){ 23 | try { 24 | this.headers.push('Content-Type'); 25 | this.headers.push(contentType) 26 | this.data = resource; 27 | this.position = 0; 28 | return { 29 | headers: [ 30 | "Content-type", this.headers, 31 | "Content-length", this.data.byteLength, 32 | ], 33 | status: this.requestStatus, 34 | body: true, 35 | }; 36 | } catch(err) { 37 | return { 38 | status: 404, 39 | headers: [ 40 | "Content-type", "text/plain", 41 | ], 42 | body: "file not found", 43 | }; 44 | } 45 | } 46 | 47 | get hasChunkResponse(){ 48 | return this.data 49 | } 50 | 51 | sendChunkResource(value: any) { 52 | if (this.position >= this.data.byteLength) 53 | return; 54 | const chunk = this.data.slice(this.position, this.position + value); 55 | this.position += chunk.byteLength; 56 | return chunk; 57 | } 58 | 59 | build(){ 60 | return { 61 | headers: this.headers, 62 | status: this.requestStatus, 63 | body: this.body 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /src/helpers/bodyParsers.ts: -------------------------------------------------------------------------------- 1 | export function parseJson(data: string) { 2 | try { 3 | return JSON.parse(data) 4 | } catch (err) { 5 | throw new Error("INVALID JSON IN REQUEST BODY") 6 | } 7 | } 8 | 9 | export function parseText(data: string) { 10 | return data 11 | } -------------------------------------------------------------------------------- /src/helpers/messageTranslation.ts: -------------------------------------------------------------------------------- 1 | export const MessageTranslations: Readonly = Object.freeze({ 2 | [-1]: "error", 3 | 1: "connection", 4 | 2: "status", 5 | 3: "header", 6 | 4: "headersComplete", 7 | 5: "requestFragment", 8 | 6: "requestComplete", 9 | 8: "prepareResponse", 10 | 9: "responseFragment", 11 | 10: "responseComplete" 12 | }) 13 | 14 | 15 | export const MessageValue: Readonly = Object.freeze({ 16 | "error" : -1, 17 | "connection" : 1, 18 | "status" : 2, 19 | "header" : 3, 20 | "headersComplete" : 4, 21 | "requestFragment" : 5, 22 | "requestComplete" : 6, 23 | "prepareResponse" : 8, 24 | "responseFragment" : 9, 25 | "responseComplete" : 10 26 | }) 27 | -------------------------------------------------------------------------------- /src/helpers/parseQuery.ts: -------------------------------------------------------------------------------- 1 | // https://blog.stevenlevithan.com/archives/parseuri 2 | // MIT License 3 | // https://blog.stevenlevithan.com/ 4 | // https://github.com/slevithan 5 | 6 | function parseQuery (str:string) { 7 | let o:any = parseQuery.options, 8 | m:any = new RegExp(/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/).exec(str), 9 | uri:any = {}, 10 | i:any = 14; 11 | 12 | while (i--) uri[o.key[i]] = m[i] || ""; 13 | 14 | uri['search'] = {}; 15 | uri[o.key[12]].replace(new RegExp(/(?:^|&)([^&=]*)=?([^&]*)/g), function ($0:any, $1:any, $2:any) { 16 | if ($1) uri['search'][$1] = $2; 17 | }); 18 | 19 | return uri; 20 | }; 21 | 22 | parseQuery.options = Object.freeze({ 23 | strictMode: false, 24 | key: Object.freeze(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]) 25 | }); 26 | 27 | Object.freeze(parseQuery) 28 | 29 | export default parseQuery -------------------------------------------------------------------------------- /src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "preload": [ 3 | "helpers/*", 4 | "express-js-mod", 5 | "http" 6 | ], 7 | "modules": { 8 | "*": [ 9 | "./*" 10 | ], 11 | "helpers/*": "./helpers/*" 12 | } 13 | } -------------------------------------------------------------------------------- /src/xs.d.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020 Moddable Tech, Inc 3 | * 4 | * This file is part of the Moddable SDK Tools. 5 | * 6 | * The Moddable SDK Tools is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * The Moddable SDK Tools is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with the Moddable SDK Tools. If not, see . 18 | * 19 | */ 20 | 21 | interface Trace { 22 | (...log: (string | number | boolean)[]):void; 23 | left(log: string | ArrayBuffer, conversation?: string):void; 24 | center(log: string | ArrayBuffer, conversation?: string):void; 25 | right(log: string | ArrayBuffer, conversation?: string):void; 26 | } 27 | declare const trace:Trace; 28 | 29 | declare class HostBuffer { 30 | readonly byteLength: number 31 | private brand: boolean; 32 | } 33 | 34 | interface ObjectConstructor { 35 | freeze(obj: T, freeze?: boolean | number): Readonly; 36 | } 37 | 38 | interface JSON { 39 | parse(text: string, reviver?: string[]): any; 40 | } 41 | 42 | interface StringConstructor { 43 | fromArrayBuffer(buffer: ArrayBuffer): string; 44 | } 45 | 46 | interface ArrayBufferConstructor { 47 | fromString(string: string): ArrayBuffer; 48 | } 49 | 50 | interface ArrayBuffer { 51 | concat(...buffers: ArrayBuffer[]): ArrayBuffer; 52 | } 53 | 54 | interface BigIntConstructor { 55 | bitLength(value: BigInt): number 56 | fromArrayBuffer(buffer: ArrayBuffer): BigInt 57 | } 58 | 59 | interface Uint8ArrayConstructor { 60 | new(buffer: HostBuffer, byteOffset?: number, length?: number): Uint8Array 61 | } 62 | 63 | interface Uint8ClampedArrayConstructor { 64 | new(buffer: HostBuffer, byteOffset?: number, length?: number): Uint8ClampedArrayConstructor 65 | } 66 | 67 | interface Uint16ArrayConstructor { 68 | new(buffer: HostBuffer, byteOffset?: number, length?: number): Uint16Array 69 | } 70 | 71 | interface Uint32ArrayConstructor { 72 | new(buffer: HostBuffer, byteOffset?: number, length?: number): Uint32Array 73 | } 74 | 75 | interface Int8ArrayConstructor { 76 | new(buffer: HostBuffer, byteOffset?: number, length?: number): Int8Array 77 | } 78 | 79 | interface Int16ArrayConstructor { 80 | new(buffer: HostBuffer, byteOffset?: number, length?: number): Int16Array 81 | } 82 | 83 | interface Int32ArrayConstructor { 84 | new(buffer: HostBuffer, byteOffset?: number, length?: number): Uint32Array 85 | } 86 | 87 | interface Float32ArrayConstructor { 88 | new(buffer: HostBuffer, byteOffset?: number, length?: number): Float32Array 89 | } 90 | 91 | interface Float64ArrayConstructor { 92 | new(buffer: HostBuffer, byteOffset?: number, length?: number): Float64Array 93 | } 94 | 95 | interface BigInt64ArrayConstructor { 96 | new(buffer: HostBuffer, byteOffset?: number, length?: number): BigInt64ArrayConstructor 97 | } 98 | 99 | interface BigUint64ArrayConstructor { 100 | new(buffer: HostBuffer, byteOffset?: number, length?: number): BigUint64ArrayConstructor 101 | } 102 | 103 | // Compartment? -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "assets": ["./src/manifest.json"], 3 | "include": [ 4 | "src/**/*" 5 | ], 6 | "exclude": ["node_modules", "**/*.spec.ts", "./src/interfaces/**/*.ts"], 7 | "compilerOptions": { 8 | "skipLibCheck": true, 9 | /* Basic Options */ 10 | // "incremental": true, /* Enable incremental compilation */ 11 | "target": "ESNEXT", 12 | // "lib": [], /* Specify library files to be included in the compilation. */ 13 | // "allowJs": true, /* Allow javascript files to be compiled. */ 14 | // "checkJs": true, /* Report errors in .js files. */ 15 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 16 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 17 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 18 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 19 | // "outFile": "./dist.js", /* Concatenate and emit output to single file. */ 20 | "outDir": "./express-js-mod", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 21 | // "composite": true, /* Enable project compilation */ 22 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 23 | // "removeComments": true, /* Do not emit comments to output. */ 24 | // "noEmit": true, /* Do not emit outputs. */ 25 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 26 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 27 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 28 | 29 | /* Strict Type-Checking Options */ 30 | "strict": true, /* Enable all strict type-checking options. */ 31 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 32 | // "strictNullChecks": true, /* Enable strict null checks. */ 33 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 34 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 35 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 36 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 37 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 38 | 39 | /* Additional Checks */ 40 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 41 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 42 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 43 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 44 | 45 | /* Module Resolution Options */ 46 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 47 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 48 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 49 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 50 | // "typeRoots": [], /* List of folders to include type definitions from. */ 51 | // "types": [], /* Type declaration files to be included in compilation. */ 52 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 53 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 54 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 55 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 56 | 57 | /* Source Map Options */ 58 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 59 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 60 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 61 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 62 | 63 | /* Experimental Options */ 64 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 65 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 66 | 67 | /* Advanced Options */ 68 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultSeverity": "error", 3 | "extends": [ 4 | "tslint:recommended" 5 | ], 6 | "jsRules": {}, 7 | "rules": { 8 | "eofline": false 9 | }, 10 | "rulesDirectory": [] 11 | } --------------------------------------------------------------------------------