typesmith 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 10fff6f59a2e2a38c398ca7154838659ffcab5a130d5b7644159450ff688a3cc
4
+ data.tar.gz: 9d820c71444edb283e78796c73a54431a1b9cf7d0f557f1428223f18f6b9151b
5
+ SHA512:
6
+ metadata.gz: c27e6f6c3b12407ebb14bcd471deeb84e0ad8cfdbea9252e7f74737f28c30b955b45e10786a83da2e66eb31741692dbdf043f0eba5431c41ca5c642404f7eb28
7
+ data.tar.gz: 8aec63fc264dc4a2947ca2024b111ef310dac7730dfa1142feb20144c4654bb19ac5b8d36a53b19f0316b2f6e0f02d178c59a04fcadde62e3bdce547df39ff92
data/.rubocop.yml ADDED
@@ -0,0 +1,8 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+
4
+ Style/StringLiterals:
5
+ EnforcedStyle: double_quotes
6
+
7
+ Style/StringLiteralsInInterpolation:
8
+ EnforcedStyle: double_quotes
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-08-04
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 John Panos
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,222 @@
1
+ # Typesmith
2
+
3
+ Typesmith is a Ruby gem that provides a simple and flexible way to define and validate data structures in your Ruby applications. It's particularly useful for creating type-safe parameter objects and data transfer objects (DTOs) in Rails applications. Additionally, Typesmith includes a powerful generator that can automatically create corresponding TypeScript types for your frontend, ensuring type consistency across your full-stack application.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'typesmith'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install typesmith
20
+
21
+ ## Usage
22
+
23
+ Typesmith allows you to define structured data objects with type checking. Here's a basic example:
24
+
25
+ ```ruby
26
+ class UserParams < Typesmith::Definition
27
+ property :name, type: :string
28
+ property :age, type: :number
29
+ property :email, type: :string
30
+ property :is_active, type: :boolean
31
+ end
32
+
33
+ user_params = UserParams.new(
34
+ name: "John Doe",
35
+ age: 30,
36
+ email: "john@example.com",
37
+ is_active: true
38
+ )
39
+
40
+ puts user_params.name # Output: John Doe
41
+ puts user_params.age # Output: 30
42
+ ```
43
+
44
+ ### Nested Structures
45
+
46
+ You can also define nested structures:
47
+
48
+ ```ruby
49
+ class AddressParams < Typesmith::Definition
50
+ property :street, type: :string
51
+ property :city, type: :string
52
+ property :country, type: :string
53
+ end
54
+
55
+ class UserWithAddressParams < Typesmith::Definition
56
+ property :name, type: :string
57
+ property :address, type: AddressParams
58
+ end
59
+
60
+ user_params = UserWithAddressParams.new(
61
+ name: "Jane Doe",
62
+ address: {
63
+ street: "123 Main St",
64
+ city: "Anytown",
65
+ country: "USA"
66
+ }
67
+ )
68
+
69
+ puts user_params.address.city # Output: Anytown
70
+ ```
71
+
72
+ ### Optional Properties
73
+
74
+ You can make properties optional:
75
+
76
+ ```ruby
77
+ class OptionalParams < Typesmith::Definition
78
+ property :required_field, type: :string
79
+ property :optional_field, type: :string, optional: true
80
+ end
81
+
82
+ params = OptionalParams.new(required_field: "Hello")
83
+ puts params.optional_field # Output: nil
84
+ ```
85
+
86
+ ### Array Properties
87
+
88
+ You can define properties that are arrays of a specific type:
89
+
90
+ ```ruby
91
+ class ArrayParams < Typesmith::Definition
92
+ property :tags, type: [:string]
93
+ end
94
+
95
+ params = ArrayParams.new(tags: ["ruby", "rails", "typesmith"])
96
+ puts params.tags # Output: ["ruby", "rails", "typesmith"]
97
+ ```
98
+
99
+ ### Using in Controllers
100
+
101
+ Typesmith is particularly useful in Rails controllers for validating and structuring incoming parameters:
102
+
103
+ ```ruby
104
+ class UsersController < ApplicationController
105
+ def create
106
+ user_params = UserParams.new(params.require(:user).permit!)
107
+ User.create!(user_params.attributes)
108
+ render json: { status: 'success' }
109
+ rescue Typesmith::BaseProperty::InvalidTypeError => e
110
+ render json: { error: e.message }, status: :unprocessable_entity
111
+ end
112
+ end
113
+ ```
114
+
115
+ ## TypeScript Generator
116
+
117
+ One of Typesmith's most powerful features is its ability to automatically generate TypeScript type definitions that correspond to your Ruby definitions. This ensures type consistency between your backend and frontend, reducing errors and improving developer productivity.
118
+
119
+ ### Generating TypeScript Types
120
+
121
+ To generate TypeScript types from your Typesmith definitions, you can use the Typesmith generator. Here's how to use it:
122
+
123
+ 1. Define your Typesmith classes in Ruby:
124
+
125
+ ```ruby
126
+ class UserParams < Typesmith::Definition
127
+ property :name, type: :string
128
+ property :age, type: :number
129
+ property :email, type: :string
130
+ property :is_active, type: :boolean
131
+ end
132
+
133
+ class AddressParams < Typesmith::Definition
134
+ property :street, type: :string
135
+ property :city, type: :string
136
+ property :country, type: :string
137
+ end
138
+
139
+ class UserWithAddressParams < Typesmith::Definition
140
+ property :name, type: :string
141
+ property :address, type: AddressParams
142
+ end
143
+ ```
144
+
145
+ 2. Run the Typesmith generator:
146
+
147
+ ```
148
+ $ rails generate typesmith:typescript
149
+ ```
150
+
151
+ This command will scan your Ruby files for Typesmith definitions and generate corresponding TypeScript types in the `app/javascript/types/__generated__` directory.
152
+
153
+ ### Generated TypeScript Types
154
+
155
+ For the above Ruby definitions, Typesmith will generate the following TypeScript types:
156
+
157
+ ```typescript
158
+ // app/javascript/types/__generated__/user_params.ts
159
+ export interface UserParams {
160
+ name: string;
161
+ age: number;
162
+ email: string;
163
+ isActive: boolean;
164
+ }
165
+
166
+ // app/javascript/types/__generated__/address_params.ts
167
+ export interface AddressParams {
168
+ street: string;
169
+ city: string;
170
+ country: string;
171
+ }
172
+
173
+ // app/javascript/types/__generated__/user_with_address_params.ts
174
+ import { AddressParams } from './address_params';
175
+
176
+ export interface UserWithAddressParams {
177
+ name: string;
178
+ address: AddressParams;
179
+ }
180
+ ```
181
+
182
+ ### Using Generated Types in Frontend
183
+
184
+ You can now use these generated types in your TypeScript frontend code:
185
+
186
+ ```typescript
187
+ import { UserWithAddressParams } from '../types/__generated__/user_with_address_params';
188
+
189
+ const user: UserWithAddressParams = {
190
+ name: "Jane Doe",
191
+ address: {
192
+ street: "123 Main St",
193
+ city: "Anytown",
194
+ country: "USA"
195
+ }
196
+ };
197
+
198
+ // TypeScript will enforce type checking based on the generated definitions
199
+ ```
200
+
201
+ ### Keeping Types in Sync
202
+
203
+ It's recommended to run the Typesmith generator as part of your continuous integration (CI) process to ensure that your TypeScript types are always in sync with your Ruby definitions. You can add a step in your CI pipeline to run the generator and fail the build if there are any uncommitted changes to the generated files.
204
+
205
+
206
+ ## Development
207
+
208
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
209
+
210
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
211
+
212
+ ## Contributing
213
+
214
+ Bug reports and pull requests are welcome on GitHub at https://github.com/johnpanos/typesmith. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/johnpanos/typesmith/blob/main/CODE_OF_CONDUCT.md).
215
+
216
+ ## License
217
+
218
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
219
+
220
+ ## Code of Conduct
221
+
222
+ Everyone interacting in the Typesmith project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/johnpanos/typesmith/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Typesmith
4
+ class ArrayProperty < SimpleProperty
5
+ def to_typescript
6
+ "#{camelized_name}#{optional_suffix}: #{get_type_string(type)}[];"
7
+ end
8
+
9
+ def process_value(value)
10
+ value.map { |v| super(v) }
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Typesmith
4
+ class BaseProperty
5
+ class InvalidTypeError < StandardError; end
6
+ PRIMITIVE_TYPES = %i[string number boolean any null undefined void never unknown object Date].freeze
7
+
8
+ attr_reader :name, :optional
9
+
10
+ def initialize(name, optional: false)
11
+ @name = name
12
+ @optional = optional
13
+ end
14
+
15
+ def to_typescript
16
+ raise NotImplementedError, "Subclasses must implement to_typescript"
17
+ end
18
+
19
+ def process_value(value)
20
+ value
21
+ end
22
+
23
+ protected
24
+
25
+ def optional_suffix
26
+ optional ? "?" : ""
27
+ end
28
+
29
+ def camelized_name
30
+ name.to_s.camelize(:lower)
31
+ end
32
+
33
+ def get_type_string(type)
34
+ case type
35
+ when Class
36
+ type < Definition ? type.typescript_type_name : type.to_s
37
+ when Array
38
+ "#{get_type_string(type.first)}[]"
39
+ when Hash
40
+ key_type, value_type = type.first
41
+ "{ [key: #{get_type_string(key_type)}]: #{get_type_string(value_type)} }"
42
+ else
43
+ type.to_s
44
+ end
45
+ end
46
+
47
+ def self.validate_type(type)
48
+ return if PRIMITIVE_TYPES.include?(type) || type.is_a?(Class) && type < Definition
49
+
50
+ case type
51
+ when Array
52
+ validate_type(type.first)
53
+ when Hash
54
+ key_type, value_type = type.first
55
+ validate_type(key_type)
56
+ validate_type(value_type)
57
+ else
58
+ raise InvalidTypeError, "Invalid type: #{type}. Must be a primitive type or a Definition subclass."
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/string/inflections"
4
+ require "active_support/core_ext/hash/keys"
5
+
6
+ module Typesmith
7
+ class Definition
8
+ class Error < StandardError; end
9
+ class UndefinedAttributeError < Error; end
10
+
11
+ class << self
12
+ def property(name, type: nil, optional: false, &block)
13
+ properties[name] = case type
14
+ when Array
15
+ ArrayProperty.new(name, type.first, optional: optional)
16
+ when Hash
17
+ IndexedProperty.new(name, type.keys.first, type.values.first, optional: optional)
18
+ when nil
19
+ block ? NestedProperty.new(name, block, optional: optional) : SimpleProperty.new(name, :any, optional: optional)
20
+ else
21
+ SimpleProperty.new(name, type, optional: optional)
22
+ end
23
+ end
24
+
25
+ def properties
26
+ @properties ||= {}
27
+ end
28
+
29
+ def to_typescript
30
+ generate_typescript_type(name.demodulize, properties)
31
+ end
32
+
33
+ def typescript_type_name
34
+ name.demodulize
35
+ end
36
+
37
+ private
38
+
39
+ def generate_typescript_type(name, props)
40
+ [
41
+ "export interface #{name} {",
42
+ generate_properties(props, 1),
43
+ "}"
44
+ ].join("\n")
45
+ end
46
+
47
+ def generate_properties(props, indent_level = 0)
48
+ props.map do |_, prop|
49
+ lines = prop.to_typescript.split("\n")
50
+ lines.map { |line| " " * indent_level + line }.join("\n")
51
+ end.join("\n")
52
+ end
53
+ end
54
+
55
+ attr_reader :attributes
56
+
57
+ def properties
58
+ self.class.properties
59
+ end
60
+
61
+ def initialize(attributes = {})
62
+ @attributes = {}
63
+ process_attributes(attributes.deep_symbolize_keys)
64
+ validate_required_attributes
65
+ end
66
+
67
+ def to_json(*_args)
68
+ @attributes
69
+ end
70
+
71
+ def as_json(*_args)
72
+ @attributes
73
+ end
74
+
75
+ private
76
+
77
+ def process_attributes(attrs)
78
+ undefined_attrs = attrs.keys - properties.keys
79
+ raise UndefinedAttributeError, "Undefined attributes: #{undefined_attrs.join(", ")}" if undefined_attrs.any?
80
+
81
+ properties.each do |key, prop|
82
+ if attrs.key?(key)
83
+ @attributes[key] = prop.process_value(attrs[key])
84
+ define_singleton_method(key) { @attributes[key] }
85
+ else
86
+ define_singleton_method(key) { nil }
87
+ end
88
+ end
89
+ end
90
+
91
+ def validate_required_attributes
92
+ missing_attrs = properties.reject { |_, v| v.optional }.keys - @attributes.keys
93
+ raise ArgumentError, "Missing required attributes: #{missing_attrs.join(", ")}" if missing_attrs.any?
94
+ end
95
+
96
+ def camelize_keys(hash)
97
+ hash.deep_transform_keys { |key| key.to_s.camelize(:lower) }
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/core_ext"
5
+ require "active_support/core_ext/string/inflections"
6
+
7
+ module Typesmith
8
+ class Generator
9
+ BASE_OUTPUT_DIR = File.join("app", "javascript", "types", "__generated__")
10
+
11
+ def self.generate_all
12
+ new.generate_all
13
+ end
14
+
15
+ def generate_all
16
+ definition_classes = ObjectSpace.each_object(Class).select { |klass| klass < Definition }.filter(&:name)
17
+ generated_files = definition_classes.map { |klass| generate_typescript_file(klass) }
18
+ generate_index_files(generated_files)
19
+
20
+ puts "TypeScript types and index files have been generated in the '#{BASE_OUTPUT_DIR}' directory"
21
+ end
22
+
23
+ private
24
+
25
+ def generate_typescript_file(klass)
26
+ module_path = klass.name.underscore
27
+ directory = File.join(BASE_OUTPUT_DIR, File.dirname(module_path))
28
+ FileUtils.mkdir_p(directory)
29
+
30
+ file_name = "#{File.basename(module_path)}.ts"
31
+ content = generate_imports(klass)
32
+ content += klass.to_typescript
33
+
34
+ full_path = File.join(directory, file_name)
35
+ File.write(full_path, content)
36
+ puts "Generated type for #{klass.name} in #{full_path}"
37
+
38
+ { path: full_path, type_name: klass.typescript_type_name }
39
+ end
40
+
41
+ def generate_imports(klass)
42
+ imports = Set.new
43
+
44
+ klass.properties.each_value do |prop|
45
+ add_import_for_property(imports, prop)
46
+ end
47
+
48
+ import_statements = imports.map do |type|
49
+ relative_path = calculate_relative_path(klass.name, type.name)
50
+ "import { #{type.typescript_type_name} } from '#{relative_path}';"
51
+ end
52
+
53
+ if import_statements.present?
54
+ "#{import_statements.join("\n")}\n\n"
55
+ else
56
+ ""
57
+ end
58
+ end
59
+
60
+ def add_import_for_property(imports, prop)
61
+ case prop
62
+ when SimpleProperty, ArrayProperty
63
+ add_import_for_type(imports, prop.type)
64
+ when IndexedProperty
65
+ add_import_for_type(imports, prop.value_type)
66
+ when NestedProperty
67
+ nested_class = Class.new(Definition)
68
+ nested_class.class_eval(&prop.block)
69
+ nested_class.properties.each_value do |nested_prop|
70
+ add_import_for_property(imports, nested_prop)
71
+ end
72
+ end
73
+ end
74
+
75
+ def add_import_for_type(imports, type)
76
+ case type
77
+ when Class
78
+ imports.add(type) if type < Definition
79
+ when Array
80
+ add_import_for_type(imports, type.first)
81
+ when Hash
82
+ add_import_for_type(imports, type.values.first)
83
+ end
84
+ end
85
+
86
+ def calculate_relative_path(from_class, to_class)
87
+ from_parts = from_class.underscore.split("/")
88
+ to_parts = to_class.underscore.split("/")
89
+
90
+ from_dir = from_parts[0..-2]
91
+ to_dir = to_parts[0..-2]
92
+
93
+ common_prefix_length = 0
94
+ from_dir.zip(to_dir).each do |from, to|
95
+ break if from != to
96
+
97
+ common_prefix_length += 1
98
+ end
99
+
100
+ up_levels = from_dir.length - common_prefix_length
101
+ down_path = to_dir[common_prefix_length..]
102
+
103
+ relative_path = [".."] * up_levels + down_path + [to_parts.last]
104
+ "./#{relative_path.join("/")}"
105
+ end
106
+
107
+ def generate_index_files(generated_files)
108
+ directories = generated_files.map { |file| File.dirname(file[:path]) }.uniq
109
+
110
+ directories.each do |directory|
111
+ files_in_directory = generated_files.select { |file| File.dirname(file[:path]) == directory }
112
+
113
+ index_content = files_in_directory.map do |file|
114
+ file_name = File.basename(file[:path], ".ts")
115
+ "export { #{file[:type_name]} } from './#{file_name}';"
116
+ end.join("\n")
117
+
118
+ index_path = File.join(directory, "index.ts")
119
+ File.write(index_path, index_content)
120
+ puts "Generated index file in #{index_path}"
121
+ end
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Typesmith
4
+ class IndexedProperty < BaseProperty
5
+ attr_reader :key_type, :value_type
6
+
7
+ def initialize(name, key_type, value_type, optional: false)
8
+ super(name, optional: optional)
9
+ @key_type = key_type
10
+ @value_type = value_type
11
+ self.class.validate_type(key_type)
12
+ self.class.validate_type(value_type)
13
+ end
14
+
15
+ def to_typescript
16
+ "#{camelized_name}#{optional_suffix}: { [key: #{get_type_string(key_type)}]: #{get_type_string(value_type)} };"
17
+ end
18
+
19
+ def process_value(value)
20
+ value.transform_values do |v|
21
+ if value_type.is_a?(Array)
22
+ v.map { |item| SimpleProperty.new(nil, value_type.first).process_value(item) }
23
+ else
24
+ SimpleProperty.new(nil, value_type).process_value(v)
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Typesmith
4
+ class NestedProperty < BaseProperty
5
+ attr_reader :block
6
+
7
+ def initialize(name, block, optional: false)
8
+ super(name, optional: optional)
9
+ @block = block
10
+ end
11
+
12
+ def to_typescript
13
+ nested_class = Class.new(Definition)
14
+ nested_class.class_eval(&block)
15
+ [
16
+ "#{camelized_name}#{optional_suffix}: {",
17
+ nested_class.send(:generate_properties, nested_class.properties).split("\n").map do |line|
18
+ " #{line}"
19
+ end.join("\n"),
20
+ "};"
21
+ ].join("\n")
22
+ end
23
+
24
+ def process_value(value)
25
+ nested_class = Class.new(Definition)
26
+ nested_class.class_eval(&block)
27
+ nested_class.new(value).attributes
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Typesmith
4
+ class SimpleProperty < BaseProperty
5
+ attr_reader :type
6
+
7
+ def initialize(name, type, optional: false)
8
+ super(name, optional: optional)
9
+ @type = type
10
+ self.class.validate_type(type)
11
+ end
12
+
13
+ def to_typescript
14
+ "#{camelized_name}#{optional_suffix}: #{get_type_string(type)};"
15
+ end
16
+
17
+ def process_value(value)
18
+ if type.is_a?(Class) && type < Definition
19
+ type.new(value).attributes
20
+ else
21
+ value
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Typesmith
4
+ VERSION = "0.1.0"
5
+ end
data/lib/typesmith.rb ADDED
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "zeitwerk"
4
+ require "active_support"
5
+ require "active_support/core_ext"
6
+
7
+ module Typesmith
8
+ class Error < StandardError; end
9
+ class << self
10
+ attr_accessor :loader
11
+
12
+ def setup
13
+ self.loader = Zeitwerk::Loader.for_gem
14
+ loader.setup
15
+ end
16
+ end
17
+ end
18
+
19
+ Typesmith.setup
data/sig/typesmith.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Typesmith
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,62 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: typesmith
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - John Panos
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-08-05 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Write a longer description or delete this line.
14
+ email:
15
+ - johncpanos@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".rubocop.yml"
21
+ - CHANGELOG.md
22
+ - CODE_OF_CONDUCT.md
23
+ - LICENSE.txt
24
+ - README.md
25
+ - Rakefile
26
+ - lib/typesmith.rb
27
+ - lib/typesmith/array_property.rb
28
+ - lib/typesmith/base_property.rb
29
+ - lib/typesmith/definition.rb
30
+ - lib/typesmith/generator.rb
31
+ - lib/typesmith/indexed_property.rb
32
+ - lib/typesmith/nested_property.rb
33
+ - lib/typesmith/simple_property.rb
34
+ - lib/typesmith/version.rb
35
+ - sig/typesmith.rbs
36
+ homepage: https://johnpanos.com
37
+ licenses:
38
+ - MIT
39
+ metadata:
40
+ homepage_uri: https://johnpanos.com
41
+ source_code_uri: https://github.com/johnpanos/typesmith
42
+ changelog_uri: https://github.com/johnpanos/typesmith/blob/master/CHANGELOG.md
43
+ post_install_message:
44
+ rdoc_options: []
45
+ require_paths:
46
+ - lib
47
+ required_ruby_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: 3.0.0
52
+ required_rubygems_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '0'
57
+ requirements: []
58
+ rubygems_version: 3.4.10
59
+ signing_key:
60
+ specification_version: 4
61
+ summary: Write a short summary, because RubyGems requires one.
62
+ test_files: []