Repository: sagiegurari/node-go-require Branch: master Commit: a616371a1aff Files: 33 Total size: 45.5 KB Directory structure: gitextract_n9o6lp7q/ ├── .editorconfig ├── .eslintrc.js ├── .gitattributes ├── .github/ │ ├── CONTRIBUTING.md │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ └── feature_request.md │ ├── dependabot.yml │ └── workflows/ │ ├── ci.yml │ └── codeql-analysis.yml ├── .gitignore ├── .jsbeautifyrc ├── .npmignore ├── .stylelintrc.json ├── LICENSE ├── README.md ├── docs/ │ ├── CHANGELOG.md │ └── api.md ├── inch.json ├── index.js ├── lib/ │ ├── go-loader.js │ └── node-go-require.js ├── package.json └── test/ ├── helpers/ │ ├── helper.js │ ├── main/ │ │ ├── error.go │ │ ├── main.go │ │ ├── pet.go │ │ └── vertex.go │ ├── pet-helper.js │ ├── pet.js │ └── vertex.js └── spec/ ├── go-loader-spec.js ├── index-spec.js └── node-go-require-spec.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true indent_style = space indent_size = 4 [*.json] indent_size = 2 ================================================ FILE: .eslintrc.js ================================================ module.exports = { 'env': { 'node': true, 'commonjs': true, 'es2021': true, 'mocha': true }, 'extends': 'eslint:recommended', 'parserOptions': { 'ecmaVersion': 13 }, 'rules': { 'indent': [ 'error', 4 ], 'linebreak-style': [ 'error', 'unix' ], 'quotes': [ 'error', 'single' ], 'semi': [ 'error', 'always' ] } }; ================================================ FILE: .gitattributes ================================================ * text eol=lf ================================================ FILE: .github/CONTRIBUTING.md ================================================ # Contribution Guidelines ## Issues Found a bug? Got a question? Want some enhancement?
First place to go is the repository issues section, and I'll try to help as much as possible. ## Pull Requests Fixed a bug or just want to provided additional functionality?
Simply fork this repository, implement your changes and create a pull request.
Few guidelines regarding pull requests: * This repository is integrated with github actions for continuous integration.
Your pull request build must pass (the build will run automatically).
You can run the following command locally to ensure the build will pass: ````sh npm test ```` * This library is using multiple code inspection tools to validate certain level of standards.
The configuration is part of the repository and you can set your favorite IDE using that configuration.
You can run the following command locally to ensure the code inspection passes: ````sh npm run lint ```` * There are many automatic unit tests as part of the library which provide full coverage of the functionality.
Any fix/enhancement must come with a set of tests to ensure it's working well. ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug Report about: Create a report to help us improve title: '' labels: '' assignees: sagiegurari --- ### Describe The Bug ### To Reproduce ### Error Stack ```console The error stack trace ``` ### Code Sample ```js // paste code here ``` ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature Request about: Suggest an idea for this project title: '' labels: '' assignees: sagiegurari --- ### Feature Description ### Describe The Solution You'd Like ### Code Sample ```js // paste code here ``` ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: npm directory: "/" schedule: interval: daily time: '03:00' open-pull-requests-limit: 99 ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: [push, pull_request] env: CLICOLOR_FORCE: 1 ACTIONS_ALLOW_UNSECURE_COMMANDS: true jobs: ci: name: CI runs-on: ubuntu-latest strategy: fail-fast: false matrix: node-version: ['12.x', '14.x'] steps: - name: Set GOPATH run: | echo "##[set-env name=GOPATH;]$(dirname $GITHUB_WORKSPACE)" echo "##[add-path]$(dirname $GITHUB_WORKSPACE)/bin" echo "##[add-path]$(dirname $GITHUB_WORKSPACE)/bin/windows_386" shell: bash - name: Install Go uses: actions/setup-go@v2 with: go-version: 1.17.x - name: Set GO Version run: | echo "##[set-env name=GOPHERJS_GOROOT;]$(go env GOROOT)" shell: bash - name: Install gopherjs run: go get -u github.com/gopherjs/gopherjs - name: Checkout uses: actions/checkout@v2 - name: Install node.js uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} - name: Install Dependencies run: npm install - name: Run CI run: npm test - name: Coveralls uses: coverallsapp/github-action@master with: github-token: ${{ secrets.GITHUB_TOKEN }} path-to-lcov: './coverage/lcov.info' ================================================ FILE: .github/workflows/codeql-analysis.yml ================================================ name: "CodeQL" on: push: pull_request: schedule: - cron: '0 23 * * 5' jobs: analyse: name: Analyse runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 with: # We must fetch at least the immediate parents so that if this is # a pull request then we can checkout the head. fetch-depth: 2 # If this run was triggered by a pull request event, then checkout # the head of the pull request instead of the merge commit. - run: git checkout HEAD^2 if: ${{ github.event_name == 'pull_request' }} # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v1 with: languages: javascript # Override language selection by uncommenting this and choosing your languages # with: # languages: go, javascript, csharp, python, cpp, java # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v1 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v1 ================================================ FILE: .gitignore ================================================ target .temp node_modules bower_components npm-debug.log package-lock.json .nyc_output coverage ================================================ FILE: .jsbeautifyrc ================================================ { "js": { "indent_size": 4, "indent_char": " ", "eol": "\n", "indent_level": 0, "indent_with_tabs": false, "preserve_newlines": true, "max_preserve_newlines": 2, "space_in_paren": false, "jslint_happy": true, "space_after_anon_function": true, "brace_style": "collapse", "break_chained_methods": false, "keep_array_indentation": true, "unescape_strings": false, "wrap_line_length": 0, "end_with_newline": true, "comma_first": false, "eval_code": false, "keep_function_indentation": false, "space_before_conditional": true, "good_stuff": true }, "css": { "indent_size": 2, "indent_char": " ", "indent_with_tabs": false, "eol": "\n", "end_with_newline": true, "selector_separator_newline": false, "newline_between_rules": true }, "html": { "indent_size": 4, "indent_char": " ", "indent_with_tabs": false, "eol": "\n", "end_with_newline": true, "preserve_newlines": true, "max_preserve_newlines": 2, "indent_inner_html": true, "brace_style": "collapse", "indent_scripts": "normal", "wrap_line_length": 0, "wrap_attributes": "auto", "wrap_attributes_indent_size": 4 } } ================================================ FILE: .npmignore ================================================ target .temp .nyc_output .config coverage bower_components .github test example ================================================ FILE: .stylelintrc.json ================================================ { "extends": "stylelint-config-standard" } ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # node-go-require [![NPM Version](http://img.shields.io/npm/v/node-go-require.svg?style=flat)](https://www.npmjs.org/package/node-go-require) [![CI](https://github.com/sagiegurari/node-go-require/workflows/CI/badge.svg?branch=master)](https://github.com/sagiegurari/node-go-require/actions) [![Coverage Status](https://coveralls.io/repos/sagiegurari/node-go-require/badge.svg)](https://coveralls.io/r/sagiegurari/node-go-require) [![Known Vulnerabilities](https://snyk.io/test/github/sagiegurari/node-go-require/badge.svg)](https://snyk.io/test/github/sagiegurari/node-go-require) [![Inline docs](http://inch-ci.org/github/sagiegurari/node-go-require.svg?branch=master)](http://inch-ci.org/github/sagiegurari/node-go-require) [![License](https://img.shields.io/npm/l/node-go-require.svg?style=flat)](https://github.com/sagiegurari/node-go-require/blob/master/LICENSE) [![Total Downloads](https://img.shields.io/npm/dt/node-go-require.svg?style=flat)](https://www.npmjs.org/package/node-go-require) > Load google go script as any javascript modules under nodeJS runtime. * [Overview](#overview) * [Usage](#usage) * [Installation](#installation) * [Limitations](#limitations) * [API Documentation](docs/api.md) * [Contributing](.github/CONTRIBUTING.md) * [Release History](#history) * [License](#license) ## Overview Go is an open source programming language that makes it easy to build simple, reliable, and efficient software. See [golang.org](https://golang.org/) for more information. ## Usage In order to use google go scripts under node, you need to first require this library as follows ```js require('node-go-require'); ``` Now you can require your google go files like any other javascript files, for example: ```js var petGo = require('./pet.go'); var pet = petGo.pet.New('my pet'); console.log(pet.Name()); pet.SetName('new name...'); console.log(pet.Name()); ``` In your go file, instead of doing module.exports as in any JS file, use the gopherjs solution for exporting objects/functions. Do not export to the global namespace, instead export to the module namespace. For example: ```go js.Module.Get("exports").Set("pet", map[string]interface{}{ "New": New, }) ``` Full example (GO): ```go package main import "github.com/gopherjs/gopherjs/js" type Pet struct { name string } func New(name string) *js.Object { return js.MakeWrapper(&Pet{name}) } func (p *Pet) Name() string { return p.name } func (p *Pet) SetName(name string) { p.name = name } func main() { js.Module.Get("exports").Set("pet", map[string]interface{}{ "New": New, }) } ``` Full example (JavaScript): ```js require('node-go-require'); var petGo = require('./pet.go'); var pet = petGo.pet.New('my pet'); console.log(pet.Name()); pet.SetName('new name...'); console.log(pet.Name()); ``` In order to generate minified javascript code, first set the following environment variable: ```sh NODE_GO_REQUIRE_MINIFY=TRUE ``` ## Installation In order to use this library, just run the following npm install command: ```sh npm install --save node-go-require ``` Apart of installing the NPM modules, you will need to setup the following: * Install Google Go - [installation guide](https://golang.org/doc/install) (make sure that GOPATH env variable is defined) * Install gopherjs - [gopherjs](https://github.com/gopherjs/gopherjs) by running ```sh go get -u github.com/gopherjs/gopherjs ``` ## Limitations The Google Go to javascript conversion is done by gopherjs and there are some limitations of running the gopherjs generated code under node runtime. To see exact limitations please see gopherjs project at: [gopherjs](https://github.com/gopherjs/gopherjs) ## API Documentation See full docs at: [API Docs](docs/api.md) ## Contributing See [contributing guide](.github/CONTRIBUTING.md) ## Release History | Date | Version | Description | | ----------- | ------- | ----------- | | 2020-05-13 | v2.0.0 | Migrate to github actions and upgrade minimal node version | | 2019-02-08 | v1.1.5 | Maintenance | | 2018-01-22 | v1.1.0 | Removed shelljs dependency and raised minimum node.js version to 0.12 | | 2017-02-07 | v1.0.25 | Ability to generate minified js code | | 2016-07-26 | v0.1.2 | Add integration test via docker | | 2015-02-14 | v0.0.16 | Modified tests and examples due to changes in gopherjs API | | 2015-02-09 | v0.0.15 | Grunt cleanups. | | 2015-02-06 | v0.0.14 | Doc changes | | 2015-02-05 | v0.0.13 | Fix continues integrations | | 2015-02-05 | v0.0.12 | Minor internal quality changes | | 2014-12-30 | v0.0.11 | Doc changes | | 2014-12-07 | v0.0.10 | Minor internal changes | | 2014-12-03 | v0.0.9 | No need to modify generated code | | 2014-12-03 | v0.0.8 | Simplified code generation modification | | 2014-12-02 | v0.0.7 | Mock gopherjs calls for continues integration tests. | | 2014-12-02 | v0.0.3 | Initial release. | ## License Developed by Sagie Gur-Ari and licensed under the Apache 2 open source license. ================================================ FILE: docs/CHANGELOG.md ================================================ | Date | Version | Description | | ----------- | ------- | ----------- | | 2020-05-13 | v2.0.0 | Migrate to github actions and upgrade minimal node version | | 2019-02-08 | v1.1.5 | Maintenance | | 2018-01-22 | v1.1.0 | Removed shelljs dependency and raised minimum node.js version to 0.12 | | 2017-02-07 | v1.0.25 | Ability to generate minified js code | | 2016-07-26 | v0.1.2 | Add integration test via docker | | 2015-02-14 | v0.0.16 | Modified tests and examples due to changes in gopherjs API | | 2015-02-09 | v0.0.15 | Grunt cleanups. | | 2015-02-06 | v0.0.14 | Doc changes | | 2015-02-05 | v0.0.13 | Fix continues integrations | | 2015-02-05 | v0.0.12 | Minor internal quality changes | | 2014-12-30 | v0.0.11 | Doc changes | | 2014-12-07 | v0.0.10 | Minor internal changes | | 2014-12-03 | v0.0.9 | No need to modify generated code | | 2014-12-03 | v0.0.8 | Simplified code generation modification | | 2014-12-02 | v0.0.7 | Mock gopherjs calls for continues integration tests. | | 2014-12-02 | v0.0.3 | Initial release. | ================================================ FILE: docs/api.md ================================================ ## Classes
GoLoader
## Objects
NodeGoRequire : object

Extends the require capabilities to allow loading of google go script files as JS files.

## GoLoader **Kind**: global class **Access**: public **Author**: Sagie Gur-Ari * [GoLoader](#GoLoader) * [new GoLoader()](#new_GoLoader_new) * [#createGopherJSCommandArgs(goFile, [minify])](#GoLoader+createGopherJSCommandArgs) ⇒ String * [#runGopherJS(goFile, gopherjs, [minify])](#GoLoader+runGopherJS) ⇒ Object * [#runGoScript2JS(goFile, [options])](#GoLoader+runGoScript2JS) ⇒ String * [#loadGoScript(goFile, goModule, [options])](#GoLoader+loadGoScript) ⇒ Object ### new GoLoader() The GoLoader enables to load google go script files and to load them into the node runtime as JS files. ### GoLoader#createGopherJSCommandArgs(goFile, [minify]) ⇒ String Returns the gopher js command arguments. **Returns**: String - The command arguments **Access**: public | Param | Type | Default | Description | | --- | --- | --- | --- | | goFile | String | | The google go script file path | | [minify] | Boolean | false | True to minify the generated code | ### GoLoader#runGopherJS(goFile, gopherjs, [minify]) ⇒ Object Runs the gopherjs converter process. **Returns**: Object - The process execution output (see shelljs for more information) **Access**: public | Param | Type | Default | Description | | --- | --- | --- | --- | | goFile | String | | The google go script file path | | gopherjs | String | | The gopherjs executable file location | | [minify] | Boolean | false | True to minify the generated code | ### GoLoader#runGoScript2JS(goFile, [options]) ⇒ String Converts the provided go file into JS script text. **Returns**: String - The JS string of the converted go script **Access**: public | Param | Type | Default | Description | | --- | --- | --- | --- | | goFile | String | | The google go script file path | | [options] | Object | | Optional runtime options | | [options.minify] | Boolean | process.env.NODE_GO_REQUIRE_MINIFY | True to minify the generated code | ### GoLoader#loadGoScript(goFile, goModule, [options]) ⇒ Object Converts the provided google go file into JS script and loads it into the node runtime. **Returns**: Object - The JS module **Access**: public | Param | Type | Default | Description | | --- | --- | --- | --- | | goFile | String | | The go script file path | | goModule | Object | | The module for the go script | | [options] | Object | | Optional runtime options | | [options.minify] | Boolean | process.env.NODE_GO_REQUIRE_MINIFY | True to minify the generated code | ## NodeGoRequire : object Extends the require capabilities to allow loading of google go script files as JS files. **Kind**: global namespace **Author**: Sagie Gur-Ari **Example** In order to use google go scripts under node, you need to first require this library as follows ```js require('node-go-require'); ``` Now you can require your google go files like any other javascript files, for example: ```js const petGo = require('./pet.go'); const pet = petGo.pet.New('my pet'); console.log(pet.Name()); pet.SetName('new name...'); console.log(pet.Name()); ``` Go source: ```go package main import "github.com/gopherjs/gopherjs/js" type Pet struct { name string } func New(name string) *js.Object { return js.MakeWrapper(&Pet{name}) } func (p *Pet) Name() string { return p.name } func (p *Pet) SetName(name string) { p.name = name } func main() { js.Module.Get("exports").Set("pet", map[string]interface{}{ "New": New, }) } ``` * [NodeGoRequire](#NodeGoRequire) : object * [.goLoader](#NodeGoRequire.goLoader) : [GoLoader](#GoLoader) * [.requireGo(goModule, fileName)](#NodeGoRequire.requireGo) ### NodeGoRequire.goLoader : [GoLoader](#GoLoader) The GO loader instance. **Access**: public ### NodeGoRequire.requireGo(goModule, fileName) The node require implementation for google go scripts. **Access**: public | Param | Type | Description | | --- | --- | --- | | goModule | Object | The module for the go script | | fileName | String | The go script file name | ================================================ FILE: inch.json ================================================ { "files": { "included": [ "*.js", "lib/**/*.js", "tasks/**/*.js" ], "excluded": [ "**/Gruntfile.js", "**/.eslintrc.js", "**/stylelint.config.js" ] } } ================================================ FILE: index.js ================================================ 'use strict'; module.exports = require('./lib/node-go-require'); ================================================ FILE: lib/go-loader.js ================================================ 'use strict'; const fs = require('fs'); const path = require('path'); const childProcess = require('child_process'); const vm = require('vm'); const extend = require('node.extend'); /*jslint debug: true*/ /*eslint-disable no-empty-function*/ /** * The GoLoader enables to load google go script files and to load them into the * node runtime as JS files. * * @author Sagie Gur-Ari * @class GoLoader * @public */ function GoLoader() {} /*eslint-enable no-empty-function*/ /*jslint debug: false*/ /** * Returns the gopher js command arguments. * * @function * @memberof! GoLoader * @public * @param {String} goFile - The google go script file path * @param {Boolean} [minify=false] - True to minify the generated code * @returns {String} The command arguments */ GoLoader.prototype.createGopherJSCommandArgs = function (goFile, minify) { const args = [ 'build' ]; if (minify) { args.push('-m'); } args.push(goFile); return args; }; /** * Runs the gopherjs converter process. * * @function * @memberof! GoLoader * @public * @param {String} goFile - The google go script file path * @param {String} gopherjs - The gopherjs executable file location * @param {Boolean} [minify=false] - True to minify the generated code * @returns {Object} The process execution output (see shelljs for more information) */ GoLoader.prototype.runGopherJS = function (goFile, gopherjs, minify) { const args = this.createGopherJSCommandArgs(goFile, minify); /*eslint-disable no-sync*/ /*jslint stupid: true*/ return childProcess.spawnSync(gopherjs, args, { windowsHide: true }); }; /*jslint stupid: false*/ /*eslint-enable no-sync*/ /** * Converts the provided go file into JS script text. * * @function * @memberof! GoLoader * @public * @param {String} goFile - The google go script file path * @param {Object} [options] - Optional runtime options * @param {Boolean} [options.minify=process.env.NODE_GO_REQUIRE_MINIFY] - True to minify the generated code * @returns {String} The JS string of the converted go script */ GoLoader.prototype.runGoScript2JS = function (goFile, options) { options = options || {}; if (options.minify === undefined) { options.minify = (String(process.env.NODE_GO_REQUIRE_MINIFY).toLowerCase() === 'true'); } //get current working directory const cwd = process.cwd(); /*jslint nomen: true*/ const tempPath = path.join(__dirname, '../.temp'); /*jslint nomen: false*/ //get output JS file let jsFile = goFile.substring(0, goFile.length - 'go'.length) + 'js'; jsFile = path.basename(jsFile); const jsPath = path.join(tempPath, jsFile); /*eslint-disable no-sync*/ /*jslint stupid: true*/ //set to a temp folder if (!fs.existsSync(tempPath)) { fs.mkdirSync(tempPath); } else if (fs.existsSync(jsPath)) { fs.unlinkSync(jsPath); } process.chdir(tempPath); let gopherjs = 'gopherjs'; /*istanbul ignore next*/ if (process.env.GOPATH) { gopherjs = path.join(process.env.GOPATH, 'bin', gopherjs); } const output = this.runGopherJS(goFile, gopherjs, options.minify); process.chdir(cwd); if (output.status !== 0) { throw new Error('Failed to convert Go file to JS\n' + output.stdout + '\n' + output.stderr); } //read JS file return fs.readFileSync(jsPath, { encoding: 'utf8' }); }; /*jslint stupid: false*/ /*eslint-enable no-sync*/ /** * Converts the provided google go file into JS script and loads it into * the node runtime. * * @function * @memberof! GoLoader * @public * @param {String} goFile - The go script file path * @param {Object} goModule - The module for the go script * @param {Object} [options] - Optional runtime options * @param {Boolean} [options.minify=process.env.NODE_GO_REQUIRE_MINIFY] - True to minify the generated code * @returns {Object} The JS module */ GoLoader.prototype.loadGoScript = function (goFile, goModule, options) { const jsString = this.runGoScript2JS(goFile, options); /*jslint nomen: true*/ const context = extend({}, global, { root: global.root, module: goModule, require: goModule.require.bind(goModule), exports: goModule.exports, __filename: goFile + '.js', __dirname: path.resolve(goFile, '..') }); /*jslint nomen: false*/ context.global = context; return vm.runInNewContext(jsString, context, { filename: goFile + '.js' }); }; const goLoader = new GoLoader(); //singleton module.exports = goLoader; ================================================ FILE: lib/node-go-require.js ================================================ 'use strict'; /** * Extends the require capabilities to allow loading of google go * script files as JS files. * * @author Sagie Gur-Ari * @namespace NodeGoRequire * @example * In order to use google go scripts under node, you need to first require this library as follows * ```js * require('node-go-require'); * ``` * Now you can require your google go files like any other javascript files, for example: * ```js * const petGo = require('./pet.go'); * * const pet = petGo.pet.New('my pet'); * console.log(pet.Name()); * pet.SetName('new name...'); * console.log(pet.Name()); * ``` * Go source: * ```go * package main * * import "github.com/gopherjs/gopherjs/js" * * type Pet struct { * name string * } * * func New(name string) *js.Object { * return js.MakeWrapper(&Pet{name}) * } * * func (p *Pet) Name() string { * return p.name * } * * func (p *Pet) SetName(name string) { * p.name = name * } * * func main() { * js.Module.Get("exports").Set("pet", map[string]interface{}{ * "New": New, * }) * } * ``` */ const goLoader = require('./go-loader'); /** * The node require implementation for google go scripts. * * @function * @alias NodeGoRequire.requireGo * @memberof! NodeGoRequire * @public * @param {Object} goModule - The module for the go script * @param {String} fileName - The go script file name */ const requireGo = function (goModule, fileName) { goLoader.loadGoScript(fileName, goModule); }; //use go loader to return a JS module require.extensions['.go'] = requireGo; module.exports = { requireGo, /** * The GO loader instance. * * @member {GoLoader} * @alias NodeGoRequire.goLoader * @memberof! NodeGoRequire * @public */ goLoader }; ================================================ FILE: package.json ================================================ { "name": "node-go-require", "version": "2.0.0", "description": "Load Google GO files as any javascript modules under nodeJS runtime.", "author": { "name": "Sagie Gur-Ari", "email": "sagiegurari@gmail.com" }, "license": "Apache-2.0", "homepage": "http://github.com/sagiegurari/node-go-require", "repository": { "type": "git", "url": "http://github.com/sagiegurari/node-go-require.git" }, "bugs": { "url": "http://github.com/sagiegurari/node-go-require/issues" }, "keywords": [ "go", "require" ], "main": "index.js", "directories": { "lib": "lib", "test": "test/spec" }, "scripts": { "clean": "rm -Rf ./.nyc_output ./coverage", "format": "js-beautify --config ./.jsbeautifyrc --file ./*.js ./lib/**/*.js ./test/**/*.js", "lint-js": "eslint ./*.js ./lib/**/*.js ./test/**/*.js", "lint-css": "stylelint --allow-empty-input ./docs/**/*.css", "lint": "npm run lint-js && npm run lint-css", "jstest": "mocha --exit ./test/spec/**/*.js", "coverage": "nyc --reporter=html --reporter=text --reporter=lcovonly --check-coverage=true mocha --exit ./test/spec/**/*.js", "docs": "jsdoc2md lib/**/*.js > ./docs/api.md", "test": "npm run clean && npm run format && npm run lint && npm run docs && npm run coverage", "postpublish": "git fetch && git pull" }, "dependencies": { "node.extend": "^2" }, "devDependencies": { "chai": "^4", "eslint": "^8", "js-beautify": "^1", "jsdoc-to-markdown": "^8", "mocha": "^10", "nyc": "^15", "rimraf": "^4", "stylelint": "^13", "stylelint-config-standard": "^22" } } ================================================ FILE: test/helpers/helper.js ================================================ 'use strict'; const fs = require('fs'); const path = require('path'); const childProcess = require('child_process'); const chai = require('chai'); const assert = chai.assert; module.exports = { modifyTestLoader() { let gopherjs = 'gopherjs'; const isWin = (/^win/).test(process.platform); if (isWin) { gopherjs = `${gopherjs}.exe`; } if (process.env.GOPATH) { const goPath = process.env.GOPATH || ''; gopherjs = path.join(goPath, 'bin', gopherjs); } else { process.env.GOPATH = ''; } /*jslint stupid: true */ if ((!gopherjs) || (!fs.existsSync(gopherjs))) { console.log('Running tests without GO/gopherjs installed.'); childProcess.spawnSync = function (cmd, args) { assert.isTrue(cmd.indexOf('gopherjs') !== -1); const goFile = args[args.length - 1]; if (goFile.indexOf('error.go') !== -1) { return { status: 1, stdio: 'mock error' }; } /*jslint nomen: true */ let jsPath = path.join(__dirname, 'pet-helper.js'); /*jslint nomen: false */ let jsString = fs.readFileSync(jsPath, { encoding: 'utf8' }); //get output JS file const tempPath = '.'; let jsFile = goFile.substring(0, goFile.length - 'go'.length) + 'js'; jsFile = path.basename(jsFile); jsPath = path.join(tempPath, jsFile); if (args[1] === '-m') { jsString = jsString.split('\n').join(''); } fs.writeFileSync(jsPath, jsString, { encoding: 'utf8' }); return { status: 0 }; }; } /*jslint stupid: false */ } }; ================================================ FILE: test/helpers/main/error.go ================================================ package main import ( "github.com/gopherjs/gopherjs/js" ) type Pet struct { name string } func (p *Pet) Name() string { return p.name } func (p *Pet) SetName(newName string) { p.name = newName } func New(name string) *Pet { return &Pet{name} } func main() { error error error.... js.Module.Get("exports").Set("pet", map[string]interface{}{ "New": New, }) } ================================================ FILE: test/helpers/main/main.go ================================================ package main import "github.com/gopherjs/gopherjs/js" type Pet struct { name string } func New(name string) *js.Object { return js.MakeWrapper(&Pet{name}) } func (p *Pet) Name() string { return p.name } func (p *Pet) SetName(name string) { p.name = name } func main() { js.Module.Get("exports").Set("pet", map[string]interface{}{ "New": New, }) } ================================================ FILE: test/helpers/main/pet.go ================================================ package main import "github.com/gopherjs/gopherjs/js" type Pet struct { name string } func New(name string) *js.Object { return js.MakeWrapper(&Pet{name}) } func (p *Pet) Name() string { return p.name } func (p *Pet) SetName(name string) { p.name = name } func main() { js.Module.Get("exports").Set("pet", map[string]interface{}{ "New": New, }) } ================================================ FILE: test/helpers/main/vertex.go ================================================ package main import ( "github.com/gopherjs/gopherjs/js" "math" ) type Vertex struct { X, Y float64 } func (v *Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } func New(x float64, y float64) *Vertex { return &Vertex{x, y} } func NewJS(x float64, y float64) *js.Object { return js.MakeWrapper(New(x, y)) } func main() { js.Module.Get("exports").Set("vertex", map[string]interface{}{ "New": NewJS, }) } ================================================ FILE: test/helpers/pet-helper.js ================================================ 'use strict'; function Pet(name) { this.name = name; } Pet.prototype.Name = function () { return this.name; }; Pet.prototype.SetName = function (name) { this.name = name; }; module.exports = { pet: { New(name) { return new Pet(name); } } }; ================================================ FILE: test/helpers/pet.js ================================================ 'use strict'; require('../..'); const mainGo = require('./main/pet.go'); const pet = mainGo.pet.New('my pet'); console.log(pet.Name()); pet.SetName('new name...'); console.log(pet.Name()); ================================================ FILE: test/helpers/vertex.js ================================================ 'use strict'; require('../..'); const jsModule = require('./main/vertex.go'); const vertex = jsModule.vertex.New(2, 6); console.log(vertex.Abs()); ================================================ FILE: test/spec/go-loader-spec.js ================================================ 'use strict'; /*jslint stupid: true, nomen: true*/ const path = require('path'); const chai = require('chai'); const assert = chai.assert; const rimraf = require('rimraf'); const goLoader = require('../../lib/go-loader'); require('../helpers/helper').modifyTestLoader(); describe('Go Loader', function () { const tempPath = path.join(__dirname, '../../.temp'); rimraf.sync(tempPath); describe('runGoScript2JS', function () { it('simple', function () { this.timeout(90000); delete process.env.NODE_GO_REQUIRE_MINIFY; const goFile = path.resolve(__dirname, '../helpers/main/main.go'); const js = goLoader.runGoScript2JS(goFile); assert.isString(js); assert.isTrue(js.length > 0); }); it('minified', function () { this.timeout(180000); const goFile = path.resolve(__dirname, '../helpers/main/main.go'); process.env.NODE_GO_REQUIRE_MINIFY = 'FALSE'; const unminified = goLoader.runGoScript2JS(goFile); assert.isString(unminified); assert.isTrue(unminified.length > 0); process.env.NODE_GO_REQUIRE_MINIFY = 'TRUE'; const minified = goLoader.runGoScript2JS(goFile); assert.isString(minified); assert.isTrue(minified.length > 0); assert.isTrue(minified.length < unminified.length); }); it('options', function () { this.timeout(180000); const goFile = path.resolve(__dirname, '../helpers/main/main.go'); process.env.NODE_GO_REQUIRE_MINIFY = 'FALSE'; const minified = goLoader.runGoScript2JS(goFile, { minify: true //opposite of env }); assert.isString(minified); assert.isTrue(minified.length > 0); process.env.NODE_GO_REQUIRE_MINIFY = 'TRUE'; const unminified = goLoader.runGoScript2JS(goFile, { minify: false //opposite of env }); assert.isString(unminified); assert.isTrue(unminified.length > 0); assert.isTrue(minified.length < unminified.length); }); it('error', function () { this.timeout(90000); const goFile = path.resolve(__dirname, '../helpers/main/error.go'); try { const js = goLoader.runGoScript2JS(goFile); assert.notOk(js); } catch (error) { assert.isDefined(error); } }); }); describe('createGopherJSCommandArgs', function () { it('no minify', function () { const args = goLoader.createGopherJSCommandArgs('./test.go'); assert.deepEqual(args, [ 'build', './test.go' ]); }); it('minify false', function () { const args = goLoader.createGopherJSCommandArgs('./test.go', false); assert.deepEqual(args, [ 'build', './test.go' ]); }); it('minify true', function () { const args = goLoader.createGopherJSCommandArgs('./test.go', true); assert.deepEqual(args, [ 'build', '-m', './test.go' ]); }); }); }); ================================================ FILE: test/spec/index-spec.js ================================================ 'use strict'; const chai = require('chai'); const assert = chai.assert; require('../../'); describe('Index', function () { it('require setup', function () { assert.isFunction(require.extensions['.go']); }); }); ================================================ FILE: test/spec/node-go-require-spec.js ================================================ 'use strict'; /*jslint stupid: true, nomen: true*/ const path = require('path'); const chai = require('chai'); const assert = chai.assert; require('../../lib/node-go-require'); require('../helpers/helper').modifyTestLoader(); describe('Node Go', function () { it('require setup', function () { assert.isFunction(require.extensions['.go']); }); it('require', function () { this.timeout(90000); const goFile = path.resolve(__dirname, '../helpers/main/main.go'); const jsModule = require(goFile); const pet = jsModule.pet.New('my pet'); let output = pet.Name(); assert.equal('my pet', output); pet.SetName('new name'); output = pet.Name(); assert.equal('new name', output); }); });