field_struct 0.15.0 → 1.0.0.pre1

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.
Files changed (70) hide show
  1. checksums.yaml +4 -4
  2. data/.claude-plugin/marketplace.json +13 -0
  3. data/.claude-plugin/plugin.json +9 -0
  4. data/AGENTS.md +47 -54
  5. data/CHANGELOG.md +53 -640
  6. data/LICENSE.txt +21 -0
  7. data/README.md +33 -628
  8. data/USAGE.md +771 -715
  9. data/docs/getting_started.md +139 -325
  10. data/lib/field_struct/base.rb +241 -1149
  11. data/lib/field_struct/class_macros.rb +163 -0
  12. data/lib/field_struct/describer.rb +167 -0
  13. data/lib/field_struct/errors.rb +182 -62
  14. data/lib/field_struct/exceptions.rb +40 -0
  15. data/lib/field_struct/field.rb +69 -135
  16. data/lib/field_struct/field_builder.rb +110 -0
  17. data/lib/field_struct/field_checks.rb +50 -0
  18. data/lib/field_struct/introspection.rb +199 -0
  19. data/lib/field_struct/json_codec.rb +240 -0
  20. data/lib/field_struct/metadata.rb +65 -260
  21. data/lib/field_struct/model_name.rb +27 -27
  22. data/lib/field_struct/option_checker.rb +121 -0
  23. data/lib/field_struct/partial.rb +49 -0
  24. data/lib/field_struct/presence.rb +45 -0
  25. data/lib/field_struct/rbs.rb +151 -271
  26. data/lib/field_struct/registered_option.rb +113 -0
  27. data/lib/field_struct/registry.rb +40 -50
  28. data/lib/field_struct/restrictions.rb +90 -0
  29. data/lib/field_struct/scaffold.rb +274 -301
  30. data/lib/field_struct/suggestion.rb +33 -0
  31. data/lib/field_struct/types/array.rb +147 -126
  32. data/lib/field_struct/types/base.rb +113 -124
  33. data/lib/field_struct/types/big_decimal.rb +59 -55
  34. data/lib/field_struct/types/binary.rb +18 -25
  35. data/lib/field_struct/types/boolean.rb +74 -97
  36. data/lib/field_struct/types/builtin.rb +32 -0
  37. data/lib/field_struct/types/date.rb +23 -137
  38. data/lib/field_struct/types/datetime.rb +30 -139
  39. data/lib/field_struct/types/element_options.rb +51 -0
  40. data/lib/field_struct/types/email.rb +27 -38
  41. data/lib/field_struct/types/float.rb +58 -56
  42. data/lib/field_struct/types/format_presets.rb +30 -0
  43. data/lib/field_struct/types/hash.rb +144 -0
  44. data/lib/field_struct/types/immutable_string.rb +16 -9
  45. data/lib/field_struct/types/integer.rb +74 -102
  46. data/lib/field_struct/types/nested.rb +57 -58
  47. data/lib/field_struct/types/preset_resolver.rb +9 -24
  48. data/lib/field_struct/types/rfc3339_format.rb +70 -153
  49. data/lib/field_struct/types/string.rb +48 -46
  50. data/lib/field_struct/types/symbol.rb +23 -20
  51. data/lib/field_struct/types/temporal.rb +232 -0
  52. data/lib/field_struct/types/time.rb +32 -145
  53. data/lib/field_struct/types/union.rb +111 -65
  54. data/lib/field_struct/types/union_pick.rb +139 -0
  55. data/lib/field_struct/types/url.rb +24 -35
  56. data/lib/field_struct/types/uuid.rb +24 -35
  57. data/lib/field_struct/types/value.rb +14 -9
  58. data/lib/field_struct/types/zone.rb +118 -0
  59. data/lib/field_struct/version.rb +3 -3
  60. data/lib/field_struct.rb +102 -122
  61. data/sig/field_struct.rbs +1180 -2300
  62. data/sig/manifest.yaml +6 -0
  63. data/skills/field-struct/SKILL.md +73 -159
  64. metadata +37 -28
  65. data/CODE_OF_CONDUCT.md +0 -132
  66. data/UPGRADING.md +0 -743
  67. data/lib/field_struct/error.rb +0 -48
  68. data/lib/field_struct/types/temporal_parser.rb +0 -93
  69. data/lib/field_struct/types/time_format_resolver.rb +0 -54
  70. data/lib/field_struct/types/zone_option.rb +0 -267
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Types
5
+ # How a union picks a struct member for a Hash: the ordered scan (FS-B83a) and the tag (FS-B83b). Internal.
6
+ module UnionPick
7
+ # Returned by {.scan} when every struct member raised.
8
+ NONE = Object.new.freeze
9
+
10
+ # Builds each struct member in order; stops at the first valid one with no unknown keys, else keeps the best.
11
+ #
12
+ # @param structs [Array<FieldStruct::Types::Nested>]
13
+ # @param hash [Hash]
14
+ # @param rescuable [Array<Class>] the exceptions that put a member out of the scan
15
+ # @return [FieldStruct::Base, Object] the pick, or {NONE}
16
+ def self.scan(structs, hash, rescuable)
17
+ best = NONE
18
+ best_rank = nil
19
+ structs.each do |member|
20
+ built = member.coerce(hash)
21
+ rank = rank_of(built, unknown_keys(member.struct_class, hash))
22
+ return built if rank == [0, 0]
23
+
24
+ next unless best_rank.nil? || (rank <=> best_rank).negative?
25
+
26
+ best = built
27
+ best_rank = rank
28
+ rescue *rescuable
29
+ next
30
+ end
31
+ best
32
+ end
33
+
34
+ # [0, unknown keys] for a valid struct, [1, message count] for an invalid one; lower is better.
35
+ def self.rank_of(built, unknown)
36
+ errors = built.errors
37
+ errors.empty? ? [0, unknown] : [1, errors.to_h.sum { |_field, messages| messages.size }]
38
+ end
39
+
40
+ def self.unknown_keys(struct_class, hash)
41
+ hash.each_key.count { |key| !((key.is_a?(::Symbol) || key.is_a?(::String)) && struct_class.metadata[key]) }
42
+ end
43
+
44
+ private_class_method :rank_of, :unknown_keys
45
+
46
+ # A union's +discriminator:+, checked at declaration and used to pick by tag.
47
+ class Discriminator
48
+ KEYS = %i[field map default].freeze
49
+ private_constant :KEYS
50
+
51
+ # @param declared [Symbol, Hash] the field's +discriminator:+
52
+ # @param members [Array<FieldStruct::Types::Base>] the union's member instances
53
+ # @return [Discriminator]
54
+ # @raise [ArgumentError] for each mistake in FS-B83b's table
55
+ def self.build(declared, members)
56
+ field, map, default = parts(declared)
57
+ structs = members.map { |member| struct_member(member) }
58
+ structs.each { |member| member_field(member, field) }
59
+ tags = map ? mapped(map, structs) : enum_tags(structs, field)
60
+ new(field, tags, default && member_for(default, structs, 'default:'))
61
+ end
62
+
63
+ def self.parts(declared)
64
+ return [declared, nil, nil] if declared.is_a?(::Symbol)
65
+ return declared.values_at(*KEYS) if declared.keys.all? { |key| KEYS.include?(key) } && declared[:field].is_a?(::Symbol)
66
+
67
+ raise ::ArgumentError, "discriminator: takes field:, map: and default:, got #{declared.inspect}"
68
+ end
69
+
70
+ def self.struct_member(member)
71
+ return member if member.is_a?(Nested)
72
+
73
+ raise ::ArgumentError, "discriminator: needs every union member to be a FieldStruct class, got #{member.class.short_name}"
74
+ end
75
+
76
+ def self.member_field(member, field)
77
+ declared = member.struct_class.metadata[field]
78
+ return declared if declared
79
+
80
+ raise ::ArgumentError, "discriminator: #{field.inspect} is not a field of #{member.struct_class.display_name}"
81
+ end
82
+
83
+ def self.mapped(map, structs)
84
+ map.each_with_object({}) { |(tag, klass), tags| tags[tag.to_s] = member_for(klass, structs, 'map:') }
85
+ end
86
+
87
+ def self.member_for(klass, structs, label)
88
+ found = structs.find { |member| member.struct_class.equal?(klass) }
89
+ return found if found
90
+
91
+ name = klass.is_a?(::Class) ? klass.display_name : klass.inspect
92
+ raise ::ArgumentError, "discriminator: #{label} names #{name}, which is not a member of this union"
93
+ end
94
+
95
+ def self.enum_tags(structs, field)
96
+ structs.each_with_object({}) do |member, tags|
97
+ enum = member_field(member, field).options[:enum]
98
+ name = member.struct_class.display_name
99
+ raise ::ArgumentError, "discriminator: #{field.inspect} on #{name} needs enum: (or give the union a map:)" unless enum
100
+
101
+ enum.each { |tag| claim(tags, tag.to_s, member, field) }
102
+ end
103
+ end
104
+
105
+ def self.claim(tags, tag, member, field)
106
+ if tags.key?(tag)
107
+ raise ::ArgumentError, "discriminator: #{field.inspect} tag #{tag.inspect} names both " \
108
+ "#{tags[tag].struct_class.display_name} and #{member.struct_class.display_name}"
109
+ end
110
+ tags[tag] = member
111
+ end
112
+
113
+ private_class_method :parts, :struct_member, :member_field, :mapped, :member_for, :enum_tags, :claim
114
+
115
+ # @param field [Symbol]
116
+ # @param tags [Hash{String=>FieldStruct::Types::Nested}]
117
+ # @param default [FieldStruct::Types::Nested, nil]
118
+ def initialize(field, tags, default)
119
+ @field = field
120
+ @tags = tags.freeze
121
+ @default = default
122
+ @expected = "expected one of #{tags.keys.join(', ')}"
123
+ freeze
124
+ end
125
+
126
+ # @param hash [Hash] the input
127
+ # @return [FieldStruct::Base] the member the tag names, built from +hash+
128
+ # @raise [TypeError] for a missing or unknown tag and no +default:+; the message lists the declared tags only
129
+ def pick(hash)
130
+ raw = hash.key?(@field) ? hash[@field] : hash[@field.name]
131
+ member = (@tags[raw.to_s] unless raw.nil?) || @default
132
+ return member.coerce(hash) if member
133
+
134
+ raise ::TypeError, "union discriminator #{@field} #{raw.nil? ? 'is missing' : 'names no member'} (#{@expected})"
135
+ end
136
+ end
137
+ end
138
+ end
139
+ end
@@ -1,45 +1,34 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'string'
4
-
5
3
  module FieldStruct
6
4
  module Types
7
- # URL type — a {Types::String} that pre-fills the field's +format:+
8
- # option with a practical http(s) URL pattern. Same shape as
9
- # {Types::UUID}: bad-format input is a Phase 1 validation error,
10
- # not a coercion failure.
11
- #
12
- # The default pattern matches +http://+ and +https://+ URLs with a
13
- # non-empty host. It is intentionally pragmatic, not RFC 3986
14
- # exhaustive — users can override via +format: /.../+ if they need
15
- # different schemes or stricter host rules.
16
- class URL < FieldStruct::Types::String
17
- # Inherits +format:+ / +enum:+ from {Types::String}, advertising the
18
- # +:format+ presets this subtype resolves (see {.presets}).
19
- #
20
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
21
- def self.own_option_schema
22
- {format: option(type: [::Regexp, ::Symbol], presets: presets.keys)}
23
- end
5
+ # A String that must look like a URL (http and https unless a preset says otherwise).
6
+ class URL < String
7
+ # Named formats the +format:+ option accepts.
8
+ # @return [::Hash{::Symbol=>::Regexp}]
9
+ PRESETS = {
10
+ http: %r{\Ahttps?://[^\s/$.?#][^\s]*\z}i,
11
+ https_only: %r{\Ahttps://[^\s/$.?#][^\s]*\z}i,
12
+ any_scheme: %r{\A[a-z][a-z0-9+\-.]*://[^\s/$.?#][^\s]*\z}i
13
+ }.freeze
24
14
 
25
- # @return [Regexp] practical http(s) pattern; override per-field via +format:+
26
- def self.default_format
27
- %r{\Ahttps?://[^\s/$.?#][^\s]*\z}i
28
- end
15
+ extend FormatPresets
29
16
 
30
- # @return [Hash{::Symbol=>Regexp}] named presets for +format:+
31
- def self.presets
32
- {
33
- http: default_format,
34
- https_only: %r{\Ahttps://[^\s/$.?#][^\s]*\z}i,
35
- any_scheme: %r{\A[a-z][a-z0-9+\-.]*://[^\s/$.?#][^\s]*\z}i
36
- }
37
- end
17
+ class << self
18
+ # @return [::Hash{::Symbol=>::Regexp}] preset name to pattern
19
+ def presets
20
+ PRESETS
21
+ end
22
+
23
+ # @return [::Symbol] the preset used when a field declares no +format:+
24
+ def fallback_preset
25
+ :http
26
+ end
38
27
 
39
- # Resolve a Symbol +format:+ preset (see {.presets}) to its Regexp at
40
- # field-declaration time; a user-supplied Regexp passes through.
41
- def self.resolve_options(options)
42
- PresetResolver.call(options, :format, presets, label: ':url format')
28
+ # @return [::String] how preset errors name this type
29
+ def preset_caption
30
+ ':url'
31
+ end
43
32
  end
44
33
  end
45
34
  end
@@ -1,45 +1,34 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'string'
4
-
5
3
  module FieldStruct
6
4
  module Types
7
- # UUID type — a {Types::String} that pre-fills the field's +format:+
8
- # option with a canonical RFC-4122 pattern. Bad-format input becomes
9
- # a Phase 1-style validation error (+"is invalid"+); coercion itself
10
- # still just hands back the string.
11
- #
12
- # Users can override the pattern by passing +format: /.../+ on the
13
- # field declaration.
14
- class UUID < FieldStruct::Types::String
15
- # Inherits +format:+ / +enum:+ from {Types::String}, advertising the
16
- # +:format+ presets this subtype resolves (see {.presets}).
17
- #
18
- # @return [::Hash{::Symbol => ::Hash{::Symbol => Object}}]
19
- def self.own_option_schema
20
- {format: option(type: [::Regexp, ::Symbol], presets: presets.keys)}
21
- end
5
+ # A String that must look like a UUID (checked on assignment, not at coercion).
6
+ class UUID < String
7
+ # Named formats the +format:+ option accepts.
8
+ # @return [::Hash{::Symbol=>::Regexp}]
9
+ PRESETS = {
10
+ any_version: /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/i,
11
+ v4: /\A\h{8}-\h{4}-4\h{3}-[89ab]\h{3}-\h{12}\z/i,
12
+ v7: /\A\h{8}-\h{4}-7\h{3}-[89ab]\h{3}-\h{12}\z/i
13
+ }.freeze
22
14
 
23
- # Hex-digit-only canonical RFC-4122 form. Permits any version.
24
- #
25
- # @return [Regexp] applied at the field level when no +format:+ is given
26
- def self.default_format
27
- /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/i
28
- end
15
+ extend FormatPresets
29
16
 
30
- # @return [Hash{::Symbol=>Regexp}] named presets for +format:+
31
- def self.presets
32
- {
33
- any_version: default_format,
34
- v4: /\A\h{8}-\h{4}-4\h{3}-[89ab]\h{3}-\h{12}\z/i,
35
- v7: /\A\h{8}-\h{4}-7\h{3}-[89ab]\h{3}-\h{12}\z/i
36
- }
37
- end
17
+ class << self
18
+ # @return [::Hash{::Symbol=>::Regexp}] preset name to pattern
19
+ def presets
20
+ PRESETS
21
+ end
22
+
23
+ # @return [::Symbol] the preset used when a field declares no +format:+
24
+ def fallback_preset
25
+ :any_version
26
+ end
38
27
 
39
- # Resolve a Symbol +format:+ preset (see {.presets}) to its Regexp at
40
- # field-declaration time; a user-supplied Regexp passes through.
41
- def self.resolve_options(options)
42
- PresetResolver.call(options, :format, presets, label: ':uuid format')
28
+ # @return [::String] how preset errors name this type
29
+ def preset_caption
30
+ ':uuid'
31
+ end
43
32
  end
44
33
  end
45
34
  end
@@ -1,21 +1,26 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'base'
4
-
5
3
  module FieldStruct
6
4
  module Types
7
- # Value type. A no-coercion passthrough — whatever you give it comes
8
- # back unchanged. Useful as an escape hatch when you want a field
9
- # declaration to participate in metadata without committing to a
10
- # specific shape.
5
+ # No coercion at all: the escape hatch.
11
6
  class Value < Base
12
- # @param value [Object] anything — passthrough, no coercion
13
- # @return [Object] the value, unchanged
7
+ # @param value [::Object]
8
+ # @return [::Object] the input, untouched
14
9
  def coerce(value, **)
15
10
  value
16
11
  end
17
12
 
18
- # @return [Class] +Object+ — the broadest sensible class
13
+ # Internal: {#coerce} with the options as one Hash, no keyword splat (see Types::Base.positional_coerce?).
14
+ #
15
+ # @param value [::Object]
16
+ # @param _options [::Hash{::Symbol=>::Object}] unused: this type takes no options
17
+ # @return [::Object]
18
+ # @api private
19
+ def coerce_positional(value, _options)
20
+ coerce(value)
21
+ end
22
+
23
+ # @return [::Class]
19
24
  def ruby_type
20
25
  ::Object
21
26
  end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FieldStruct
4
+ module Types
5
+ # INTERNAL. A resolved +zone:+ declaration: UTC, a fixed offset or an IANA zone (tzinfo, required on first use).
6
+ # Hands back plain Time objects; they do not carry the zone (FS-B99).
7
+ class Zone
8
+ FIXED_OFFSET = /\A([+-])([01]\d|2[0-3]):([0-5]\d)\z/
9
+ RAILS_NAME = /[\s()&]/
10
+ SHAPE = 'an IANA name like "America/Denver", "UTC" or a UTC offset like "-06:00"'
11
+ GENERIC_HINT = 'Use an Area/Location name: abbreviations and aliases are refused ("MST" is a fixed -07:00 in the zone ' \
12
+ 'database, not Mountain time with DST), and an offset needs its colon.'
13
+ RAILS_HINT = 'Rails zone names are an ActiveSupport alias, not IANA names, and exist only when ActiveSupport is loaded: ' \
14
+ 'use the name it maps to (ActiveSupport::TimeZone::MAPPING[name]).'
15
+ UNKNOWN_HINT = 'The zone database has no zone by that name.'
16
+
17
+ @cache = {}
18
+ @lock = Mutex.new
19
+
20
+ class << self
21
+ # Declaration-time validation.
22
+ #
23
+ # @param name [::String]
24
+ # @param label [::String] the type's short name, used in the message
25
+ # @return [void]
26
+ # @raise [ArgumentError] when the name is not UTC, a "+-HH:MM" offset or a known IANA name
27
+ def check!(name, label)
28
+ return if name == 'UTC' || FIXED_OFFSET.match?(name)
29
+
30
+ hint = GENERIC_HINT
31
+ if name.include?('/') && !RAILS_NAME.match?(name)
32
+ return if iana_known?(name, label)
33
+
34
+ hint = UNKNOWN_HINT
35
+ elsif RAILS_NAME.match?(name)
36
+ hint = RAILS_HINT
37
+ end
38
+ raise ::ArgumentError, "zone: on #{label} expects #{SHAPE}, got #{name.inspect}. #{hint}"
39
+ end
40
+
41
+ # @param name [::String] a name that passed {.check!}
42
+ # @return [FieldStruct::Types::Zone] cached per name
43
+ def fetch(name)
44
+ @lock.synchronize { @cache[name] ||= new(name) }
45
+ end
46
+
47
+ private
48
+
49
+ def iana_known?(name, label)
50
+ require 'tzinfo'
51
+ TZInfo::Timezone.get(name)
52
+ true
53
+ rescue TZInfo::InvalidTimezoneIdentifier
54
+ false
55
+ rescue TZInfo::DataSourceNotFound
56
+ raise ::ArgumentError, "zone: on #{label} names #{name.inspect}, but no time zone data was found on this system. " \
57
+ 'Add the tzinfo-data gem to your Gemfile (or install the OS zoneinfo package).'
58
+ end
59
+ end
60
+
61
+ # @return [::String]
62
+ attr_reader :name
63
+
64
+ # @param name [::String]
65
+ def initialize(name)
66
+ @name = name
67
+ match = FIXED_OFFSET.match(name)
68
+ @fixed = if match
69
+ (match[1] == '-' ? -1 : 1) * ((match[2].to_i * 3600) + (match[3].to_i * 60))
70
+ end
71
+ @utc = name == 'UTC'
72
+ load_iana unless @utc || @fixed
73
+ end
74
+
75
+ # The wall clock in this zone as a Time with the zone's offset at that moment.
76
+ #
77
+ # @param wall [::Array<::Numeric>] year, month, day, hour, minute, second
78
+ # @return [::Time]
79
+ # @raise [ArgumentError] when a daylight-saving change skips that wall time
80
+ def time_at_local(*wall)
81
+ return ::Time.utc(*wall) if @utc
82
+ return ::Time.new(*wall, @fixed) if @fixed
83
+
84
+ periods = @tz.periods_for_local(::Time.utc(*wall))
85
+ raise ::ArgumentError, "names a local time that does not exist in #{name} (skipped by a daylight-saving change)" if periods.empty?
86
+
87
+ ::Time.new(*wall, (periods.find(&:dst?) || periods.first).observed_utc_offset)
88
+ end
89
+
90
+ # @param seconds [::Numeric] seconds since the epoch
91
+ # @return [::Time] that instant, shown at this zone's offset then
92
+ def time_at_epoch(seconds)
93
+ return ::Time.at(seconds).utc if @utc
94
+ return ::Time.at(seconds, in: @fixed) if @fixed
95
+
96
+ ::Time.at(seconds, in: @tz.period_for_utc(::Time.at(seconds).utc).observed_utc_offset)
97
+ end
98
+
99
+ # @return [::Time] midnight of that day here, or the first moment of the day if midnight is skipped
100
+ def start_of_day(year, mon, mday)
101
+ time_at_local(year, mon, mday, 0, 0, 0)
102
+ rescue ::ArgumentError
103
+ (1..23).each do |hour|
104
+ periods = @tz.periods_for_local(::Time.utc(year, mon, mday, hour, 0, 0))
105
+ return time_at_epoch(periods.last.starts_at.to_i) unless periods.empty?
106
+ end
107
+ raise
108
+ end
109
+
110
+ private
111
+
112
+ def load_iana
113
+ require 'tzinfo'
114
+ @tz = TZInfo::Timezone.get(name)
115
+ end
116
+ end
117
+ end
118
+ end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FieldStruct
4
- # The gem's semantic version.
5
- # @return [String]
6
- VERSION = '0.15.0'
4
+ # The gem version.
5
+ # @return [::String]
6
+ VERSION = '1.0.0.pre1'
7
7
  end