peachsim 0.1.2410 → 0.1.2411

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 (111) hide show
  1. package/README.md +2 -5
  2. package/cli/internal-child-contract.ts +0 -1
  3. package/cli/internal-child.ts +0 -6
  4. package/cli/outbound-endpoints.ts +0 -23
  5. package/dist-lib/agent-daemon-client.cjs +1 -1
  6. package/dist-lib/agent-events.cjs +1 -1
  7. package/dist-lib/attached-projects.cjs +1 -1
  8. package/dist-lib/auth/shared-session.cjs +1 -1
  9. package/dist-lib/backend-origin.cjs +1 -1
  10. package/dist-lib/beta.cjs +1 -1
  11. package/dist-lib/beta.mjs +1 -1
  12. package/dist-lib/bridge-constants.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.cjs +1 -1
  14. package/dist-lib/bridge-contract-input.mjs +1 -1
  15. package/dist-lib/bridge-contract.cjs +1 -1
  16. package/dist-lib/bridge-contract.mjs +1 -1
  17. package/dist-lib/bundle-channel.cjs +10279 -4163
  18. package/dist-lib/capture-contract.cjs +1 -1
  19. package/dist-lib/capture-contract.mjs +1 -1
  20. package/dist-lib/cloud-contract.cjs +1 -1
  21. package/dist-lib/cloud-contract.mjs +1 -1
  22. package/dist-lib/cloud-test-args.cjs +1 -1
  23. package/dist-lib/cloud-test-args.mjs +1 -1
  24. package/dist-lib/cloud.cjs +1 -1
  25. package/dist-lib/cloud.mjs +1 -1
  26. package/dist-lib/config.cjs +1 -1
  27. package/dist-lib/config.mjs +1 -1
  28. package/dist-lib/detox/index.cjs +1 -1
  29. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  30. package/dist-lib/expo-swift-bundle.cjs +11551 -5435
  31. package/dist-lib/expo-swift-metadata.cjs +1 -1
  32. package/dist-lib/expo-swift-metadata.mjs +1 -1
  33. package/dist-lib/home-paths.cjs +1 -1
  34. package/dist-lib/host/bridge-host.cjs +12798 -6682
  35. package/dist-lib/host/fetch-proxy-handler.cjs +924 -150
  36. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  37. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  38. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  39. package/dist-lib/host/websocket-proxy.cjs +1 -1
  40. package/dist-lib/index.cjs +1011 -237
  41. package/dist-lib/jump-to-source-babel.cjs +1 -1
  42. package/dist-lib/jump-to-source-native.cjs +1 -1
  43. package/dist-lib/kotlin-host.cjs +1 -1
  44. package/dist-lib/menu.cjs +1 -1
  45. package/dist-lib/menu.mjs +1 -1
  46. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  47. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  48. package/dist-lib/metro-production-bundle.cjs +1 -1
  49. package/dist-lib/metro-production-bundle.mjs +1 -1
  50. package/dist-lib/metro.cjs +927 -153
  51. package/dist-lib/native-app-identity-project.cjs +2 -2
  52. package/dist-lib/native-app-identity-project.mjs +2 -2
  53. package/dist-lib/native-app-identity.cjs +1 -1
  54. package/dist-lib/native-app-identity.mjs +1 -1
  55. package/dist-lib/native-firebase-metadata.cjs +1 -1
  56. package/dist-lib/native-firebase-metadata.mjs +1 -1
  57. package/dist-lib/pdfium-raster.cjs +1 -1
  58. package/dist-lib/pdfium-raster.mjs +1 -1
  59. package/dist-lib/plist.cjs +1 -1
  60. package/dist-lib/plist.mjs +1 -1
  61. package/dist-lib/profiles.cjs +1 -1
  62. package/dist-lib/public-brand.cjs +1 -1
  63. package/dist-lib/public-origins-lib-esm.json +24 -24
  64. package/dist-lib/public-origins-lib.json +124 -104
  65. package/dist-lib/react-native-host-modules.cjs +1 -1
  66. package/dist-lib/react-native-host-modules.mjs +1 -1
  67. package/dist-lib/reap-browser.cjs +1 -1
  68. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  69. package/dist-lib/sdk.cjs +1 -1
  70. package/dist-lib/sdk.mjs +1 -1
  71. package/dist-lib/skills.cjs +13905 -7789
  72. package/dist-lib/swift-compile.cjs +62 -14
  73. package/dist-lib/swift-compile.mjs +62 -13
  74. package/dist-lib/swift-package.cjs +1 -1
  75. package/dist-lib/swift-package.mjs +1 -1
  76. package/dist-lib/swift-submit.cjs +1 -1
  77. package/dist-lib/swift-submit.mjs +1 -1
  78. package/dist-lib/swift-toolchain.cjs +1 -1
  79. package/dist-lib/swift.cjs +1 -1
  80. package/dist-lib/vite-swift.cjs +76 -19
  81. package/dist-lib/vite.cjs +3100 -2326
  82. package/dist-lib/worklet-executable.cjs +1 -1
  83. package/dist-lib/worklet-executable.mjs +1 -1
  84. package/kotlin/sdk.tar.gz +0 -0
  85. package/package.json +3 -3
  86. package/sdk/ios/System/Library/Frameworks/AuthenticationServices.framework/Headers/ASWebAuthenticationSession.h +1 -1
  87. package/sdk/ios/System/Library/Frameworks/Photos.framework/Headers/PHAsset.h +1 -1
  88. package/sdk/ios/System/Library/Frameworks/Photos.framework/Headers/PHAssetResource.h +1 -1
  89. package/sdk/ios/System/Library/Frameworks/Photos.framework/Headers/PHChange.h +1 -1
  90. package/sdk/ios/System/Library/Frameworks/Photos.framework/Headers/PHFetchOptions.h +1 -1
  91. package/sdk/ios/System/Library/Frameworks/Photos.framework/Headers/PHFetchResult.h +1 -1
  92. package/sdk/ios/System/Library/Frameworks/Photos.framework/Headers/PHImageManager.h +2 -2
  93. package/sdk/ios/System/Library/Frameworks/Photos.framework/Headers/PHObject.h +1 -1
  94. package/sdk/ios/System/Library/Frameworks/Photos.framework/Headers/PHPhotoLibrary.h +2 -2
  95. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIDevice.h +1 -1
  96. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIVibrancyEffect.h +1 -1
  97. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIVisualEffectView.h +1 -1
  98. package/sdk/ios/System/Library/Frameworks/UIKitActivity.framework/Headers/UIKitActivity.h +1 -1
  99. package/src/nitro-adapter.lock.json +262 -262
  100. package/src/nitro-superset.lock.json +4 -4
  101. package/src/podspec-cocoapods.ts +934 -0
  102. package/src/podspec-prism.ts +66 -0
  103. package/src/podspec-ruby-stdlib.ts +1121 -0
  104. package/src/podspec-ruby.ts +5175 -0
  105. package/src/podspec-sources.ts +25 -112
  106. package/src/swift-compile.ts +70 -12
  107. package/src/swift-distribution.lock.json +9 -8
  108. package/src/swift-host.ts +14 -4
  109. package/src/turbo-runtime.lock.json +19 -19
  110. package/cli/drivers/linux-cocoapods.lock.json +0 -303
  111. package/cli/drivers/linux-cocoapods.ts +0 -99
@@ -0,0 +1,1121 @@
1
+ // the slice of Ruby's core and standard library podspecs and React Native's
2
+ // pod helpers read: files, directories, JSON, ENV, Pathname, versions. it reads
3
+ // the disk and never writes it.
4
+ import { createHash } from 'node:crypto'
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import {
9
+ type Call,
10
+ type Interpreter,
11
+ type Value,
12
+ equal,
13
+ hashKey,
14
+ RFloat,
15
+ RHash,
16
+ RModule,
17
+ RObject,
18
+ RString,
19
+ RSymbol,
20
+ RubyVersion,
21
+ str,
22
+ sym,
23
+ toInspect,
24
+ truthy,
25
+ UnsupportedRuby,
26
+ } from './podspec-ruby'
27
+
28
+ function text(interp: Interpreter, value: Value | undefined): string {
29
+ if (value instanceof RString) return value.s
30
+ if (value instanceof RSymbol) return value.name
31
+ if (value instanceof RObject && typeof value.data === 'string') return value.data
32
+ return interp.raise(
33
+ 'TypeError',
34
+ `no implicit conversion of ${toInspect(interp, value ?? null)} into String`,
35
+ )
36
+ }
37
+
38
+ function expandHome(p: string): string {
39
+ return p === '~' || p.startsWith('~/') ? path.join(os.homedir(), p.slice(1)) : p
40
+ }
41
+
42
+ /** Ruby's File.join: one separator between parts, nested arrays flattened. */
43
+ function joinPaths(parts: string[]): string {
44
+ let out = ''
45
+ parts.forEach((part, index) => {
46
+ if (index === 0) {
47
+ out = part
48
+ return
49
+ }
50
+ const left = out.endsWith('/')
51
+ const right = part.startsWith('/')
52
+ out =
53
+ left && right ? out + part.slice(1) : left || right ? out + part : `${out}/${part}`
54
+ })
55
+ return out
56
+ }
57
+
58
+ function rubyBasename(p: string, suffix?: string): string {
59
+ if (p === '/') return '/'
60
+ let base = path.posix.basename(p)
61
+ if (suffix === '.*') {
62
+ const dot = base.lastIndexOf('.')
63
+ if (dot > 0) base = base.slice(0, dot)
64
+ } else if (suffix && base.endsWith(suffix) && base !== suffix)
65
+ base = base.slice(0, -suffix.length)
66
+ return base
67
+ }
68
+
69
+ function rubyExtname(p: string): string {
70
+ const base = path.posix.basename(p)
71
+ const dot = base.lastIndexOf('.')
72
+ if (dot <= 0 || dot === base.length - 1) return ''
73
+ return base.slice(dot)
74
+ }
75
+
76
+ function expandBraces(pattern: string): string[] {
77
+ const open = pattern.indexOf('{')
78
+ if (open < 0) return [pattern]
79
+ let depth = 0
80
+ let close = -1
81
+ const commas: number[] = []
82
+ for (let i = open; i < pattern.length; i++) {
83
+ const c = pattern[i]
84
+ if (c === '\\') i++
85
+ else if (c === '{') depth++
86
+ else if (c === '}' && --depth === 0) {
87
+ close = i
88
+ break
89
+ } else if (c === ',' && depth === 1) commas.push(i)
90
+ }
91
+ if (close < 0) return [pattern]
92
+ const bounds = [open, ...commas, close]
93
+ const options = bounds
94
+ .slice(0, -1)
95
+ .map((start, i) => pattern.slice(start + 1, bounds[i + 1]))
96
+ return options.flatMap((option) =>
97
+ expandBraces(pattern.slice(0, open) + option + pattern.slice(close + 1)),
98
+ )
99
+ }
100
+
101
+ function segmentMatcher(segment: string, dotMatch: boolean): RegExp {
102
+ let source = ''
103
+ for (let i = 0; i < segment.length; i++) {
104
+ const c = segment[i]!
105
+ if (c === '*') source += '[^/]*'
106
+ else if (c === '?') source += '[^/]'
107
+ else if (c === '{') source += '(?:'
108
+ else if (c === '}') source += ')'
109
+ else if (c === ',') source += '|'
110
+ else if (c === '[') {
111
+ const end = segment.indexOf(']', i + 1)
112
+ if (end < 0) source += '\\['
113
+ else {
114
+ source += `[${segment
115
+ .slice(i + 1, end)
116
+ .replace(/^!/, '^')
117
+ .replace(/\\/g, '\\\\')}]`
118
+ i = end
119
+ }
120
+ } else if (c === '\\')
121
+ source += (segment[++i] ?? '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
122
+ else source += c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
123
+ }
124
+ return new RegExp(`^${dotMatch || segment.startsWith('.') ? '' : '(?!\\.)'}${source}$`)
125
+ }
126
+
127
+ /** Dir.glob for one pattern, relative to `base`, in Ruby 3's order: a depth-first walk over sorted entries. */
128
+ export function rubyGlob(pattern: string, base: string, dotMatch = false): string[] {
129
+ const all: string[] = []
130
+ // braces stay inside a segment's matcher unless one spans a separator
131
+ const expansions = /\{[^}]*\/[^}]*\}/.test(pattern) ? expandBraces(pattern) : [pattern]
132
+ for (const expanded of expansions) {
133
+ const results: string[] = []
134
+ const absolute = path.isAbsolute(expanded)
135
+ const segments = expanded.split('/').filter((s, i) => s !== '' || i === 0)
136
+ const walk = (dir: string, shown: string, index: number) => {
137
+ if (index === segments.length) {
138
+ results.push(shown)
139
+ return
140
+ }
141
+ const segment = segments[index]!
142
+ const join = (name: string) =>
143
+ shown === '' ? name : shown.endsWith('/') ? shown + name : `${shown}/${name}`
144
+ if (segment === '' && index === 0) {
145
+ walk('/', '/', index + 1)
146
+ return
147
+ }
148
+ if (segment === '**') {
149
+ walk(dir, shown, index + 1)
150
+ let entries: fs.Dirent[]
151
+ try {
152
+ entries = fs.readdirSync(dir, { withFileTypes: true })
153
+ } catch {
154
+ return
155
+ }
156
+ for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
157
+ if (!dotMatch && entry.name.startsWith('.')) continue
158
+ if (entry.isDirectory())
159
+ walk(path.join(dir, entry.name), join(entry.name), index)
160
+ }
161
+ return
162
+ }
163
+ if (!/[*?[{\\]/.test(segment)) {
164
+ const next = path.join(dir, segment)
165
+ if (index === segments.length - 1 ? fs.existsSync(next) : isDirectory(next))
166
+ walk(next, join(segment), index + 1)
167
+ return
168
+ }
169
+ const matcher = segmentMatcher(segment, dotMatch)
170
+ let names: string[]
171
+ try {
172
+ names = fs.readdirSync(dir).sort()
173
+ } catch {
174
+ return
175
+ }
176
+ for (const name of names) {
177
+ if (!matcher.test(name)) continue
178
+ const next = path.join(dir, name)
179
+ if (index < segments.length - 1 && !isDirectory(next)) continue
180
+ walk(next, join(name), index + 1)
181
+ }
182
+ }
183
+ walk(absolute ? '/' : base, '', absolute ? 1 : 0)
184
+ if (absolute)
185
+ for (let i = 0; i < results.length; i++)
186
+ if (!results[i]!.startsWith('/')) results[i] = `/${results[i]}`
187
+ all.push(
188
+ ...[...new Set(results)].sort((a, b) => {
189
+ const x = a.split('/')
190
+ const y = b.split('/')
191
+ for (let i = 0; i < Math.min(x.length, y.length); i++)
192
+ if (x[i] !== y[i]) return x[i]! < y[i]! ? -1 : 1
193
+ return x.length - y.length
194
+ }),
195
+ )
196
+ }
197
+ return [...new Set(all)]
198
+ }
199
+
200
+ function isDirectory(p: string): boolean {
201
+ try {
202
+ return fs.statSync(p).isDirectory()
203
+ } catch {
204
+ return false
205
+ }
206
+ }
207
+
208
+ export function fromJson(value: unknown): Value {
209
+ if (value === null || value === undefined) return null
210
+ if (typeof value === 'string') return str(value)
211
+ if (typeof value === 'number')
212
+ return Number.isInteger(value) ? value : new RFloat(value)
213
+ if (typeof value === 'boolean') return value
214
+ if (Array.isArray(value)) return value.map(fromJson)
215
+ if (typeof value === 'object')
216
+ return RHash.from(Object.entries(value).map(([k, v]) => [str(k), fromJson(v)]))
217
+ return null
218
+ }
219
+
220
+ export function toJson(interp: Interpreter, value: Value): unknown {
221
+ if (value === null || typeof value === 'boolean' || typeof value === 'number')
222
+ return value
223
+ if (value instanceof RFloat) return value.v
224
+ if (value instanceof RString) return value.s
225
+ if (value instanceof RSymbol) return value.name
226
+ if (Array.isArray(value)) return value.map((v) => toJson(interp, v))
227
+ if (value instanceof RHash)
228
+ return Object.fromEntries(
229
+ value.entries().map(([k, v]) => [interp.toS(k), toJson(interp, v)]),
230
+ )
231
+ return interp.toS(value)
232
+ }
233
+
234
+ function symbolizeKeys(value: Value): Value {
235
+ if (Array.isArray(value)) return value.map(symbolizeKeys)
236
+ if (value instanceof RHash)
237
+ return RHash.from(
238
+ value
239
+ .entries()
240
+ .map(([k, v]) => [k instanceof RString ? sym(k.s) : k, symbolizeKeys(v)]),
241
+ )
242
+ return value
243
+ }
244
+
245
+ const segment = (s: number | string): Value => (typeof s === 'number' ? s : str(s))
246
+
247
+ export function makeVersion(interp: Interpreter, cls: RModule, value: Value): RObject {
248
+ const version = new RObject(cls)
249
+ const raw =
250
+ value instanceof RObject && value.data instanceof RubyVersion
251
+ ? value.data.text
252
+ : interp.toS(value)
253
+ version.data = new RubyVersion(raw.trim().replace(/-/g, '.pre.'))
254
+ return version
255
+ }
256
+
257
+ /** Gem::Version's instance methods on `cls`. */
258
+ export function defineVersionClass(interp: Interpreter, cls: RModule) {
259
+ const data = (c: Call) => {
260
+ if (c.self instanceof RObject && c.self.data instanceof RubyVersion)
261
+ return c.self.data
262
+ throw new UnsupportedRuby(`${cls.name} without a version`)
263
+ }
264
+ const other = (c: Call) => {
265
+ const v = c.args[0] ?? null
266
+ if (v instanceof RObject && v.data instanceof RubyVersion) return v.data
267
+ if (v instanceof RString) return new RubyVersion(v.s)
268
+ return null
269
+ }
270
+ interp.defineNative(
271
+ cls,
272
+ 'new',
273
+ (c) => makeVersion(interp, cls, c.args[0] ?? null),
274
+ true,
275
+ )
276
+ interp.defineNative(
277
+ cls,
278
+ 'create',
279
+ (c) => (c.args[0] === null ? null : makeVersion(interp, cls, c.args[0] ?? null)),
280
+ true,
281
+ )
282
+ interp.defineNative(
283
+ cls,
284
+ 'correct?',
285
+ (c) =>
286
+ /^\s*[0-9]+(\.[0-9a-zA-Z]+)*(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?\s*$/.test(
287
+ interp.toS(c.args[0] ?? null),
288
+ ),
289
+ true,
290
+ )
291
+ interp.defineNative(cls, 'to_s', (c) => str(data(c).text))
292
+ interp.defineNative(cls, 'version', (c) => str(data(c).text))
293
+ interp.defineNative(cls, 'inspect', (c) => str(`#<${cls.name} "${data(c).text}">`))
294
+ interp.defineNative(cls, 'segments', (c) =>
295
+ [...data(c).segments].map((s) => (typeof s === 'number' ? s : str(s))),
296
+ )
297
+ interp.defineNative(cls, 'major', (c) => segment(data(c).segments[0] ?? 0))
298
+ interp.defineNative(cls, 'minor', (c) => segment(data(c).segments[1] ?? 0))
299
+ interp.defineNative(cls, 'patch', (c) => segment(data(c).segments[2] ?? 0))
300
+ interp.defineNative(cls, 'prerelease?', (c) =>
301
+ data(c).segments.some((s) => typeof s === 'string'),
302
+ )
303
+ interp.defineNative(cls, 'release', (c) => {
304
+ const segments = data(c).segments
305
+ const end = segments.findIndex((s) => typeof s === 'string')
306
+ return makeVersion(
307
+ interp,
308
+ cls,
309
+ str((end < 0 ? segments : segments.slice(0, end)).join('.')),
310
+ )
311
+ })
312
+ interp.defineNative(cls, 'hash', (c) =>
313
+ Number.parseInt(
314
+ createHash('sha1').update(data(c).text).digest('hex').slice(0, 12),
315
+ 16,
316
+ ),
317
+ )
318
+ interp.defineNative(cls, 'eql?', (c) => {
319
+ const o = c.args[0]
320
+ return (
321
+ o instanceof RObject &&
322
+ o.data instanceof RubyVersion &&
323
+ o.data.text === data(c).text
324
+ )
325
+ })
326
+ interp.defineNative(cls, '<=>', (c) => {
327
+ const o = other(c)
328
+ return o ? data(c).compare(o) : null
329
+ })
330
+ for (const op of ['<', '<=', '>', '>=', '==', '!='] as const)
331
+ interp.defineNative(cls, op, (c) => {
332
+ const o = other(c)
333
+ if (!o) {
334
+ if (op === '==') return false
335
+ if (op === '!=') return true
336
+ interp.raise(
337
+ 'ArgumentError',
338
+ `comparison of ${cls.name} with ${toInspect(interp, c.args[0] ?? null)} failed`,
339
+ )
340
+ }
341
+ const r = data(c).compare(o)
342
+ return op === '<'
343
+ ? r < 0
344
+ : op === '<='
345
+ ? r <= 0
346
+ : op === '>'
347
+ ? r > 0
348
+ : op === '>='
349
+ ? r >= 0
350
+ : op === '=='
351
+ ? r === 0
352
+ : r !== 0
353
+ })
354
+ }
355
+
356
+ /** Gem::Requirement's satisfaction rule for one requirement string. */
357
+ export function requirementSatisfied(requirement: string, version: RubyVersion): boolean {
358
+ const m = /^\s*(=|!=|>|<|>=|<=|~>)?\s*(\S+)\s*$/.exec(requirement)
359
+ if (!m) throw new UnsupportedRuby(`requirement ${requirement}`)
360
+ const target = new RubyVersion(m[2]!)
361
+ const c = version.compare(target)
362
+ switch (m[1] ?? '=') {
363
+ case '=':
364
+ return c === 0
365
+ case '!=':
366
+ return c !== 0
367
+ case '>':
368
+ return c > 0
369
+ case '<':
370
+ return c < 0
371
+ case '>=':
372
+ return c >= 0
373
+ case '<=':
374
+ return c <= 0
375
+ default: {
376
+ const segments = target.segments.filter((s) => typeof s === 'number')
377
+ const upper = [...segments.slice(0, Math.max(1, segments.length - 1))]
378
+ upper[upper.length - 1] = Number(upper[upper.length - 1]) + 1
379
+ return c >= 0 && version.compare(new RubyVersion(upper.join('.'))) < 0
380
+ }
381
+ }
382
+ }
383
+
384
+ export function installStdlib(interp: Interpreter) {
385
+ const host = interp.host
386
+ const object = interp.object
387
+ const def = (module: RModule, name: string, fn: (c: Call) => Value) =>
388
+ interp.defineNative(module, name, fn, true)
389
+ const resolve = (p: string) => path.resolve(host.cwd, expandHome(p))
390
+ const exists = (c: Call) => fs.existsSync(resolve(text(interp, c.args[0])))
391
+
392
+ // File
393
+ const file = interp.defineModule('File', object, true, interp.classes.IO ?? object)
394
+ file.consts.set('SEPARATOR', new RString('/', true))
395
+ file.consts.set('ALT_SEPARATOR', null)
396
+ file.consts.set('FNM_PATHNAME', 2)
397
+ file.consts.set('FNM_DOTMATCH', 4)
398
+ file.consts.set('FNM_EXTGLOB', 16)
399
+ file.consts.set('FNM_CASEFOLD', 8)
400
+ def(file, 'exist?', exists)
401
+ def(file, 'exists?', exists)
402
+ def(file, 'file?', (c) => {
403
+ try {
404
+ return fs.statSync(resolve(text(interp, c.args[0]))).isFile()
405
+ } catch {
406
+ return false
407
+ }
408
+ })
409
+ def(file, 'directory?', (c) => isDirectory(resolve(text(interp, c.args[0]))))
410
+ def(file, 'symlink?', (c) => {
411
+ try {
412
+ return fs.lstatSync(resolve(text(interp, c.args[0]))).isSymbolicLink()
413
+ } catch {
414
+ return false
415
+ }
416
+ })
417
+ def(file, 'readable?', exists)
418
+ def(file, 'executable?', (c) => {
419
+ try {
420
+ fs.accessSync(resolve(text(interp, c.args[0])), fs.constants.X_OK)
421
+ return true
422
+ } catch {
423
+ return false
424
+ }
425
+ })
426
+ def(file, 'size', (c) => fs.statSync(resolve(text(interp, c.args[0]))).size)
427
+ def(file, 'join', (c) =>
428
+ str(
429
+ joinPaths(
430
+ c.args.flatMap(function flat(v: Value): string[] {
431
+ return Array.isArray(v) ? v.flatMap(flat) : [text(interp, v)]
432
+ }),
433
+ ),
434
+ ),
435
+ )
436
+ def(file, 'basename', (c) =>
437
+ str(
438
+ rubyBasename(
439
+ text(interp, c.args[0]),
440
+ c.args[1] === undefined ? undefined : text(interp, c.args[1]),
441
+ ),
442
+ ),
443
+ )
444
+ def(file, 'path', (c) => str(text(interp, c.args[0])))
445
+ def(file, 'dirname', (c) => str(path.posix.dirname(text(interp, c.args[0]))))
446
+ def(file, 'extname', (c) => str(rubyExtname(text(interp, c.args[0]))))
447
+ def(file, 'split', (c) => {
448
+ const p = text(interp, c.args[0])
449
+ return [str(path.posix.dirname(p)), str(rubyBasename(p))]
450
+ })
451
+ def(file, 'expand_path', (c) => {
452
+ const base =
453
+ c.args[1] === undefined || c.args[1] === null
454
+ ? host.cwd
455
+ : path.resolve(host.cwd, expandHome(text(interp, c.args[1])))
456
+ return str(path.resolve(base, expandHome(text(interp, c.args[0]))))
457
+ })
458
+ def(file, 'absolute_path', (c) => {
459
+ const base =
460
+ c.args[1] === undefined || c.args[1] === null
461
+ ? host.cwd
462
+ : path.resolve(host.cwd, text(interp, c.args[1]))
463
+ return str(path.resolve(base, text(interp, c.args[0])))
464
+ })
465
+ def(file, 'absolute_path?', (c) => text(interp, c.args[0]).startsWith('/'))
466
+ def(file, 'realpath', (c) => {
467
+ const base =
468
+ c.args[1] === undefined || c.args[1] === null
469
+ ? host.cwd
470
+ : path.resolve(host.cwd, text(interp, c.args[1]))
471
+ const target = path.resolve(base, text(interp, c.args[0]))
472
+ if (!fs.existsSync(target))
473
+ interp.raise(
474
+ 'Errno::ENOENT',
475
+ `No such file or directory @ realpath_rec - ${target}`,
476
+ )
477
+ return str(fs.realpathSync(target))
478
+ })
479
+ const read = (c: Call) => {
480
+ const target = resolve(text(interp, c.args[0]))
481
+ if (!fs.existsSync(target))
482
+ interp.raise(
483
+ 'Errno::ENOENT',
484
+ `No such file or directory @ rb_sysopen - ${text(interp, c.args[0])}`,
485
+ )
486
+ return fs.readFileSync(target, 'utf8')
487
+ }
488
+ def(file, 'read', (c) => str(read(c)))
489
+ def(file, 'readlines', (c) =>
490
+ (read(c).match(/[^\n]*\n|[^\n]+$/g) ?? []).map((line) =>
491
+ str(truthy(c.kw?.get(sym('chomp')) ?? null) ? line.replace(/\n$/, '') : line),
492
+ ),
493
+ )
494
+ def(file, 'foreach', (c) => {
495
+ for (const line of read(c).match(/[^\n]*\n|[^\n]+$/g) ?? [])
496
+ interp.callProc(c.block!, [str(line)])
497
+ return null
498
+ })
499
+ def(file, 'open', (c) => {
500
+ const mode =
501
+ c.args[1] === undefined || c.args[1] instanceof RHash
502
+ ? 'r'
503
+ : text(interp, c.args[1])
504
+ if (!mode.startsWith('r'))
505
+ throw new UnsupportedRuby(
506
+ `File.open(${toInspect(interp, c.args[0] ?? null)}, ${mode}) writes a file`,
507
+ )
508
+ const handle = new RObject(file)
509
+ handle.data = new FileHandle(read(c))
510
+ return c.block ? interp.callProc(c.block, [handle]) : handle
511
+ })
512
+ def(file, 'fnmatch', (c) =>
513
+ fnmatch(
514
+ text(interp, c.args[0]),
515
+ text(interp, c.args[1]),
516
+ typeof c.args[2] === 'number' ? c.args[2] : 0,
517
+ ),
518
+ )
519
+ def(file, 'fnmatch?', (c) =>
520
+ fnmatch(
521
+ text(interp, c.args[0]),
522
+ text(interp, c.args[1]),
523
+ typeof c.args[2] === 'number' ? c.args[2] : 0,
524
+ ),
525
+ )
526
+ def(file, 'mtime', () => {
527
+ throw new UnsupportedRuby('File.mtime')
528
+ })
529
+ // a podspec may rewrite its own package, as some copy vendored sources in while CocoaPods evaluates them
530
+ const writable = (value: Value | undefined, what: string) => {
531
+ const target = resolve(text(interp, value))
532
+ if (!host.writable.some((root) => target === root || target.startsWith(`${root}/`)))
533
+ throw new UnsupportedRuby(`${what} writes ${target} outside the podspec's package`)
534
+ return target
535
+ }
536
+ def(file, 'write', (c) => {
537
+ const content = text(interp, c.args[1])
538
+ fs.writeFileSync(writable(c.args[0], 'File.write'), content)
539
+ return Buffer.byteLength(content)
540
+ })
541
+ for (const name of ['delete', 'unlink'])
542
+ def(file, name, (c) => {
543
+ for (const target of c.args) fs.rmSync(writable(target, `File.${name}`))
544
+ return c.args.length
545
+ })
546
+ const handleData = (c: Call) => {
547
+ if (c.self instanceof RObject && c.self.data instanceof FileHandle) return c.self.data
548
+ throw new UnsupportedRuby('a File method on a closed file')
549
+ }
550
+ interp.defineNative(file, 'read', (c) => str(handleData(c).rest()))
551
+ interp.defineNative(file, 'readlines', (c) =>
552
+ (
553
+ handleData(c)
554
+ .rest()
555
+ .match(/[^\n]*\n|[^\n]+$/g) ?? []
556
+ ).map(str),
557
+ )
558
+ interp.defineNative(file, 'each_line', (c) => {
559
+ for (const line of handleData(c)
560
+ .rest()
561
+ .match(/[^\n]*\n|[^\n]+$/g) ?? [])
562
+ interp.callProc(c.block!, [str(line)])
563
+ return c.self
564
+ })
565
+ interp.defineNative(file, 'close', () => null)
566
+
567
+ // Dir
568
+ const dir = interp.defineModule('Dir', object, true)
569
+ def(dir, 'pwd', () => str(host.cwd))
570
+ def(dir, 'getwd', () => str(host.cwd))
571
+ def(dir, 'home', () => str(os.homedir()))
572
+ def(dir, 'exist?', (c) => isDirectory(resolve(text(interp, c.args[0]))))
573
+ def(dir, 'exists?', (c) => isDirectory(resolve(text(interp, c.args[0]))))
574
+ def(dir, 'chdir', (c) => {
575
+ const previous = host.cwd
576
+ host.cwd = c.args[0] === undefined ? os.homedir() : resolve(text(interp, c.args[0]))
577
+ if (!c.block) return 0
578
+ try {
579
+ return interp.callProc(c.block, [str(host.cwd)])
580
+ } finally {
581
+ host.cwd = previous
582
+ }
583
+ })
584
+ const glob = (c: Call) => {
585
+ const patterns = (Array.isArray(c.args[0]) ? c.args[0] : [c.args[0] ?? null]).map(
586
+ (p) => text(interp, p),
587
+ )
588
+ const flags = typeof c.args[1] === 'number' ? c.args[1] : 0
589
+ const baseValue = c.kw?.get(sym('base'))
590
+ const base =
591
+ baseValue === undefined || baseValue === null
592
+ ? host.cwd
593
+ : resolve(text(interp, baseValue))
594
+ const found = patterns.flatMap((p) => rubyGlob(p, base, (flags & 4) !== 0)).map(str)
595
+ if (c.block) {
596
+ interp.yieldEach(c.block, found)
597
+ return null
598
+ }
599
+ return found
600
+ }
601
+ def(dir, 'glob', glob)
602
+ def(dir, '[]', (c) =>
603
+ glob({ ...c, args: [c.args.filter((a) => !(a instanceof RHash))] }),
604
+ )
605
+ const children = (c: Call) => {
606
+ const target = resolve(text(interp, c.args[0]))
607
+ if (!isDirectory(target))
608
+ interp.raise(
609
+ 'Errno::ENOENT',
610
+ `No such file or directory @ dir_initialize - ${target}`,
611
+ )
612
+ return fs.readdirSync(target).sort()
613
+ }
614
+ def(dir, 'entries', (c) => ['.', '..', ...children(c)].map(str))
615
+ def(dir, 'children', (c) => children(c).map(str))
616
+ def(dir, 'each_child', (c) => {
617
+ interp.yieldEach(c.block!, children(c).map(str))
618
+ return null
619
+ })
620
+ def(dir, 'empty?', (c) => children(c).length === 0)
621
+ for (const name of ['mkdir', 'mktmpdir', 'rmdir', 'tmpdir'])
622
+ def(dir, name, () => {
623
+ throw new UnsupportedRuby(`Dir.${name} writes the disk`)
624
+ })
625
+
626
+ const fileUtils = interp.defineModule('FileUtils', object)
627
+ const targets = (value: Value | undefined, what: string) =>
628
+ (Array.isArray(value) ? value : [value ?? null]).map((v) => writable(v, what))
629
+ for (const name of ['mkdir_p', 'makedirs', 'mkdir'])
630
+ def(fileUtils, name, (c) => {
631
+ for (const target of targets(c.args[0], `FileUtils.${name}`))
632
+ fs.mkdirSync(target, { recursive: true })
633
+ return c.args[0] ?? null
634
+ })
635
+ for (const name of ['rm_rf', 'rm_r', 'rm_f', 'rm', 'remove_dir'])
636
+ def(fileUtils, name, (c) => {
637
+ for (const target of targets(c.args[0], `FileUtils.${name}`))
638
+ fs.rmSync(target, {
639
+ recursive: name !== 'rm' && name !== 'rm_f',
640
+ force: name !== 'rm',
641
+ })
642
+ return c.args[0] ?? null
643
+ })
644
+ for (const name of ['cp', 'cp_r', 'mv'])
645
+ def(fileUtils, name, (c) => {
646
+ const destination = writable(c.args[1], `FileUtils.${name}`)
647
+ for (const source of (Array.isArray(c.args[0])
648
+ ? c.args[0]
649
+ : [c.args[0] ?? null]
650
+ ).map((v) => resolve(text(interp, v)))) {
651
+ const target = isDirectory(destination)
652
+ ? path.join(destination, path.basename(source))
653
+ : destination
654
+ if (name === 'mv') fs.renameSync(writable(str(source), 'FileUtils.mv'), target)
655
+ else fs.cpSync(source, target, { recursive: name === 'cp_r' })
656
+ }
657
+ return null
658
+ })
659
+ for (const name of ['ln_s', 'ln_sf'])
660
+ def(fileUtils, name, (c) => {
661
+ const target = writable(c.args[1], `FileUtils.${name}`)
662
+ if (name === 'ln_sf') fs.rmSync(target, { force: true })
663
+ fs.symlinkSync(text(interp, c.args[0]), target)
664
+ return null
665
+ })
666
+ def(fileUtils, 'touch', (c) => {
667
+ for (const target of targets(c.args[0], 'FileUtils.touch')) {
668
+ const now = new Date()
669
+ if (fs.existsSync(target)) fs.utimesSync(target, now, now)
670
+ else fs.writeFileSync(target, '')
671
+ }
672
+ return c.args[0] ?? null
673
+ })
674
+ const open3 = interp.defineModule('Open3', object)
675
+ for (const name of ['capture2', 'capture2e', 'capture3'])
676
+ def(open3, name, (c) => {
677
+ const command = c.args
678
+ .filter((a) => !(a instanceof RHash))
679
+ .map((a) => text(interp, a))
680
+ .join(' ')
681
+ const result = host.shell(command, host.cwd)
682
+ const out = str(result.stdout)
683
+ const status = new RObject(interp.classes.ProcessStatus!)
684
+ status.data = result.status
685
+ return name === 'capture3' ? [out, str(''), status] : [out, status]
686
+ })
687
+
688
+ // JSON
689
+ const json = interp.defineModule('JSON', object)
690
+ const parserError = interp.defineModule(
691
+ 'ParserError',
692
+ json,
693
+ true,
694
+ interp.classes.StandardError!,
695
+ )
696
+ json.consts.set('JSONError', parserError)
697
+ def(json, 'parse', (c) => {
698
+ let parsed: unknown
699
+ try {
700
+ parsed = JSON.parse(text(interp, c.args[0]))
701
+ } catch (error) {
702
+ if (!(error instanceof SyntaxError)) throw error
703
+ const exception = interp.makeException(parserError, error.message)
704
+ return interp.raise(parserError.name, interp.toS(exception))
705
+ }
706
+ const value = fromJson(parsed)
707
+ return truthy(c.kw?.get(sym('symbolize_names')) ?? null)
708
+ ? symbolizeKeys(value)
709
+ : value
710
+ })
711
+ def(json, 'load', (c) => fromJson(JSON.parse(text(interp, c.args[0]))))
712
+ def(json, 'generate', (c) => str(JSON.stringify(toJson(interp, c.args[0] ?? null))))
713
+ def(json, 'dump', (c) => str(JSON.stringify(toJson(interp, c.args[0] ?? null))))
714
+ def(json, 'pretty_generate', (c) =>
715
+ str(JSON.stringify(toJson(interp, c.args[0] ?? null), null, 2)),
716
+ )
717
+ for (const cls of [interp.classes.Hash!, interp.classes.Array!, interp.classes.String!])
718
+ interp.defineNative(cls, 'to_json', (c) =>
719
+ str(JSON.stringify(toJson(interp, c.self))),
720
+ )
721
+
722
+ // ENV
723
+ const envClass = interp.defineModule('ENVClass', object, true)
724
+ const env = new RObject(envClass)
725
+ object.consts.set('ENV', env)
726
+ const envGet = (key: Value | undefined) => {
727
+ const value = host.env.get(text(interp, key))
728
+ return value === undefined ? null : new RString(value, true)
729
+ }
730
+ interp.defineNative(envClass, '[]', (c) => envGet(c.args[0]))
731
+ interp.defineNative(envClass, 'fetch', (c) => {
732
+ const value = envGet(c.args[0])
733
+ if (value !== null) return value
734
+ if (c.block) return interp.callProc(c.block, [c.args[0] ?? null])
735
+ if (c.args.length > 1) return c.args[1]!
736
+ return interp.raise(
737
+ 'KeyError',
738
+ `key not found: ${toInspect(interp, c.args[0] ?? null)}`,
739
+ )
740
+ })
741
+ interp.defineNative(envClass, '[]=', (c) => {
742
+ const key = text(interp, c.args[0])
743
+ const value = c.args[1] ?? null
744
+ if (value === null) host.env.delete(key)
745
+ else host.env.set(key, text(interp, value))
746
+ return value
747
+ })
748
+ interp.defineNative(envClass, 'store', (c) => {
749
+ host.env.set(text(interp, c.args[0]), text(interp, c.args[1]))
750
+ return c.args[1] ?? null
751
+ })
752
+ interp.defineNative(envClass, 'delete', (c) => {
753
+ const value = envGet(c.args[0])
754
+ host.env.delete(text(interp, c.args[0]))
755
+ return value
756
+ })
757
+ for (const name of ['key?', 'has_key?', 'include?', 'member?'])
758
+ interp.defineNative(envClass, name, (c) => host.env.has(text(interp, c.args[0])))
759
+ interp.defineNative(envClass, 'to_h', () =>
760
+ RHash.from([...host.env].map(([k, v]) => [str(k), str(v)])),
761
+ )
762
+ interp.defineNative(envClass, 'to_hash', () =>
763
+ RHash.from([...host.env].map(([k, v]) => [str(k), str(v)])),
764
+ )
765
+ interp.defineNative(envClass, 'keys', () => [...host.env.keys()].map(str))
766
+ interp.defineNative(envClass, 'each', (c) => {
767
+ for (const [k, v] of host.env) interp.callProc(c.block!, [str(k), str(v)])
768
+ return env
769
+ })
770
+ interp.defineNative(envClass, 'inspect', () => str('ENV'))
771
+
772
+ // Pathname
773
+ const pathname = interp.defineModule('Pathname', object, true)
774
+ const pathOf = (c: Call) => {
775
+ if (c.self instanceof RObject && typeof c.self.data === 'string') return c.self.data
776
+ throw new UnsupportedRuby('Pathname without a path')
777
+ }
778
+ const makePath = (p: string) => {
779
+ const value = new RObject(pathname)
780
+ value.data = p
781
+ return value
782
+ }
783
+ const cleanpath = (p: string) => {
784
+ if (p === '') return '.'
785
+ const normalized = path.posix.normalize(p)
786
+ return normalized.length > 1 ? normalized.replace(/\/$/, '') : normalized
787
+ }
788
+ const plus = (a: string, b: string) => (b.startsWith('/') ? b : cleanpath(`${a}/${b}`))
789
+ def(pathname, 'new', (c) => makePath(text(interp, c.args[0])))
790
+ def(pathname, 'pwd', () => makePath(host.cwd))
791
+ def(pathname, 'glob', (c) => {
792
+ const found = (Array.isArray(c.args[0]) ? c.args[0] : [c.args[0] ?? null])
793
+ .flatMap((p) => rubyGlob(text(interp, p), host.cwd))
794
+ .map(makePath)
795
+ return found
796
+ })
797
+ interp.defineNative(interp.kernel, 'Pathname', (c) => makePath(text(interp, c.args[0])))
798
+ interp.defineNative(pathname, 'to_s', (c) => str(pathOf(c)))
799
+ interp.defineNative(pathname, 'to_path', (c) => str(pathOf(c)))
800
+ interp.defineNative(pathname, 'to_str', (c) => str(pathOf(c)))
801
+ interp.defineNative(pathname, 'inspect', (c) => str(`#<Pathname:${pathOf(c)}>`))
802
+ interp.defineNative(pathname, '+', (c) =>
803
+ makePath(plus(pathOf(c), text(interp, c.args[0]))),
804
+ )
805
+ interp.defineNative(pathname, '/', (c) =>
806
+ makePath(plus(pathOf(c), text(interp, c.args[0]))),
807
+ )
808
+ interp.defineNative(pathname, 'join', (c) =>
809
+ makePath(c.args.reduce<string>((acc, a) => plus(acc, text(interp, a)), pathOf(c))),
810
+ )
811
+ interp.defineNative(pathname, 'dirname', (c) => makePath(path.posix.dirname(pathOf(c))))
812
+ interp.defineNative(pathname, 'parent', (c) => makePath(plus(pathOf(c), '..')))
813
+ interp.defineNative(pathname, 'basename', (c) =>
814
+ makePath(
815
+ rubyBasename(
816
+ pathOf(c),
817
+ c.args[0] === undefined ? undefined : text(interp, c.args[0]),
818
+ ),
819
+ ),
820
+ )
821
+ interp.defineNative(pathname, 'extname', (c) => str(rubyExtname(pathOf(c))))
822
+ interp.defineNative(pathname, 'sub_ext', (c) => {
823
+ const p = pathOf(c)
824
+ const ext = rubyExtname(p)
825
+ return makePath(p.slice(0, p.length - ext.length) + text(interp, c.args[0]))
826
+ })
827
+ interp.defineNative(pathname, 'cleanpath', (c) => makePath(cleanpath(pathOf(c))))
828
+ interp.defineNative(pathname, 'expand_path', (c) =>
829
+ makePath(
830
+ path.resolve(
831
+ c.args[0] === undefined ? host.cwd : resolve(text(interp, c.args[0])),
832
+ expandHome(pathOf(c)),
833
+ ),
834
+ ),
835
+ )
836
+ interp.defineNative(pathname, 'realpath', (c) =>
837
+ makePath(fs.realpathSync(resolve(pathOf(c)))),
838
+ )
839
+ interp.defineNative(pathname, 'absolute?', (c) => pathOf(c).startsWith('/'))
840
+ interp.defineNative(pathname, 'relative?', (c) => !pathOf(c).startsWith('/'))
841
+ interp.defineNative(pathname, 'exist?', (c) => fs.existsSync(resolve(pathOf(c))))
842
+ interp.defineNative(
843
+ pathname,
844
+ 'file?',
845
+ (c) => fs.existsSync(resolve(pathOf(c))) && fs.statSync(resolve(pathOf(c))).isFile(),
846
+ )
847
+ interp.defineNative(pathname, 'directory?', (c) => isDirectory(resolve(pathOf(c))))
848
+ interp.defineNative(pathname, 'read', (c) =>
849
+ str(fs.readFileSync(resolve(pathOf(c)), 'utf8')),
850
+ )
851
+ interp.defineNative(pathname, 'children', (c) =>
852
+ fs
853
+ .readdirSync(resolve(pathOf(c)))
854
+ .sort()
855
+ .map((name) => makePath(plus(pathOf(c), name))),
856
+ )
857
+ interp.defineNative(pathname, 'relative_path_from', (c) => {
858
+ const from = text(interp, c.args[0])
859
+ const relative = path.posix.relative(cleanpath(from), cleanpath(pathOf(c)))
860
+ return makePath(relative === '' ? '.' : relative)
861
+ })
862
+ interp.defineNative(pathname, '==', (c) => equal(interp, c.self, c.args[0] ?? null))
863
+ interp.defineNative(pathname, 'eql?', (c) => equal(interp, c.self, c.args[0] ?? null))
864
+ interp.defineNative(pathname, 'hash', (c) => hashKey(str(pathOf(c))).length)
865
+ interp.defineNative(pathname, '<=>', (c) => {
866
+ const a = pathOf(c)
867
+ const b = text(interp, c.args[0])
868
+ return a < b ? -1 : a > b ? 1 : 0
869
+ })
870
+
871
+ // Gem
872
+ const gem = interp.defineModule('Gem', object)
873
+ defineVersionClass(interp, interp.defineModule('Version', gem, true))
874
+ const requirement = interp.defineModule('Requirement', gem, true)
875
+ def(requirement, 'new', (c) => {
876
+ const value = new RObject(requirement)
877
+ value.data = new GemRequirement(
878
+ c.args.flatMap((a) => (Array.isArray(a) ? a : [a])).map((a) => text(interp, a)),
879
+ )
880
+ return value
881
+ })
882
+ interp.defineNative(requirement, 'satisfied_by?', (c) => {
883
+ const version = c.args[0]
884
+ if (
885
+ !(c.self instanceof RObject && c.self.data instanceof GemRequirement) ||
886
+ !(version instanceof RObject && version.data instanceof RubyVersion)
887
+ )
888
+ throw new UnsupportedRuby('Gem::Requirement#satisfied_by? without a version')
889
+ const v = version.data
890
+ return c.self.data.requirements.every((r) => requirementSatisfied(r, v))
891
+ })
892
+ def(gem, 'win_platform?', () => false)
893
+ def(gem, 'loaded_specs', () => new RHash())
894
+
895
+ // Time, Set, Digest, Shellwords, Process
896
+ const time = interp.classes.Time!
897
+ const now = () => {
898
+ const value = new RObject(time)
899
+ value.data = new TimeValue(Date.now())
900
+ return value
901
+ }
902
+ def(time, 'now', now)
903
+ const timeOf = (c: Call) =>
904
+ c.self instanceof RObject && c.self.data instanceof TimeValue ? c.self.data.ms : 0
905
+ interp.defineNative(time, 'to_i', (c) => Math.floor(timeOf(c) / 1000))
906
+ interp.defineNative(time, 'to_f', (c) => new RFloat(timeOf(c) / 1000))
907
+ interp.defineNative(time, '-', (c) => {
908
+ const other = c.args[0]
909
+ return new RFloat(
910
+ (timeOf(c) -
911
+ (other instanceof RObject && other.data instanceof TimeValue
912
+ ? other.data.ms
913
+ : 0)) /
914
+ 1000,
915
+ )
916
+ })
917
+ interp.defineNative(time, 'year', (c) => new Date(timeOf(c)).getFullYear())
918
+
919
+ const set = interp.defineModule('Set', object, true)
920
+ set.includes.push(interp.enumerable)
921
+ const setItems = (c: Call) => {
922
+ if (c.self instanceof RObject && c.self.data instanceof SetData) return c.self.data
923
+ throw new UnsupportedRuby('Set without items')
924
+ }
925
+ const makeSet = (items: Value[]) => {
926
+ const value = new RObject(set)
927
+ const data = new SetData()
928
+ for (const item of items) data.add(item)
929
+ value.data = data
930
+ return value
931
+ }
932
+ def(set, 'new', (c) =>
933
+ makeSet(
934
+ c.args[0] === undefined || c.args[0] === null
935
+ ? []
936
+ : interp.toArrayForSplat(c.args[0], null, c.node),
937
+ ),
938
+ )
939
+ def(set, '[]', (c) => makeSet(c.args))
940
+ interp.defineNative(set, 'each', (c) => {
941
+ interp.yieldEach(c.block!, setItems(c).values())
942
+ return c.self
943
+ })
944
+ for (const name of ['<<', 'add'])
945
+ interp.defineNative(set, name, (c) => {
946
+ setItems(c).add(c.args[0] ?? null)
947
+ return c.self
948
+ })
949
+ interp.defineNative(set, 'add?', (c) =>
950
+ setItems(c).add(c.args[0] ?? null) ? c.self : null,
951
+ )
952
+ interp.defineNative(set, 'merge', (c) => {
953
+ for (const item of interp.toArrayForSplat(c.args[0] ?? null, null, c.node))
954
+ setItems(c).add(item)
955
+ return c.self
956
+ })
957
+ for (const name of ['include?', 'member?', '==='])
958
+ interp.defineNative(set, name, (c) => setItems(c).has(c.args[0] ?? null))
959
+ interp.defineNative(set, 'delete', (c) => {
960
+ setItems(c).delete(c.args[0] ?? null)
961
+ return c.self
962
+ })
963
+ interp.defineNative(set, 'to_a', (c) => setItems(c).values())
964
+ interp.defineNative(set, 'size', (c) => setItems(c).items.size)
965
+ interp.defineNative(set, 'length', (c) => setItems(c).items.size)
966
+ interp.defineNative(set, 'empty?', (c) => setItems(c).items.size === 0)
967
+ interp.defineNative(set, 'to_set', (c) => c.self)
968
+ interp.defineNative(set, '|', (c) =>
969
+ makeSet([
970
+ ...setItems(c).values(),
971
+ ...interp.toArrayForSplat(c.args[0] ?? null, null, c.node),
972
+ ]),
973
+ )
974
+ interp.defineNative(set, '+', (c) =>
975
+ makeSet([
976
+ ...setItems(c).values(),
977
+ ...interp.toArrayForSplat(c.args[0] ?? null, null, c.node),
978
+ ]),
979
+ )
980
+ interp.defineNative(set, '-', (c) => {
981
+ const remove = makeSet(interp.toArrayForSplat(c.args[0] ?? null, null, c.node))
982
+ const data = remove.data
983
+ return makeSet(
984
+ setItems(c)
985
+ .values()
986
+ .filter((v) => !(data instanceof SetData && data.has(v))),
987
+ )
988
+ })
989
+ interp.defineNative(interp.classes.Array!, 'to_set', (c) =>
990
+ makeSet(Array.isArray(c.self) ? c.self : []),
991
+ )
992
+
993
+ const digest = interp.defineModule('Digest', object)
994
+ for (const [name, algorithm] of [
995
+ ['MD5', 'md5'],
996
+ ['SHA1', 'sha1'],
997
+ ['SHA256', 'sha256'],
998
+ ] as const) {
999
+ const cls = interp.defineModule(name, digest, true)
1000
+ def(cls, 'hexdigest', (c) =>
1001
+ str(createHash(algorithm).update(text(interp, c.args[0])).digest('hex')),
1002
+ )
1003
+ def(cls, 'file', (c) => {
1004
+ const value = new RObject(cls)
1005
+ value.data = createHash(algorithm)
1006
+ .update(fs.readFileSync(resolve(text(interp, c.args[0]))))
1007
+ .digest('hex')
1008
+ return value
1009
+ })
1010
+ interp.defineNative(cls, 'hexdigest', (c) =>
1011
+ str(
1012
+ c.self instanceof RObject && typeof c.self.data === 'string' ? c.self.data : '',
1013
+ ),
1014
+ )
1015
+ }
1016
+
1017
+ const shellwords = interp.defineModule('Shellwords', object)
1018
+ const escape = (s: string) =>
1019
+ s === '' ? "''" : s.replace(/[^A-Za-z0-9_\-.,:+/@\n]/g, '\\$&').replace(/\n/g, "'\n'")
1020
+ def(shellwords, 'escape', (c) => str(escape(text(interp, c.args[0]))))
1021
+ def(shellwords, 'shellescape', (c) => str(escape(text(interp, c.args[0]))))
1022
+ def(shellwords, 'join', (c) =>
1023
+ str(
1024
+ (Array.isArray(c.args[0]) ? c.args[0] : [])
1025
+ .map((a) => escape(text(interp, a)))
1026
+ .join(' '),
1027
+ ),
1028
+ )
1029
+ interp.defineNative(interp.classes.Array!, 'shelljoin', (c) =>
1030
+ str(
1031
+ (Array.isArray(c.self) ? c.self : []).map((a) => escape(text(interp, a))).join(' '),
1032
+ ),
1033
+ )
1034
+
1035
+ const processModule = interp.defineModule('Process', object)
1036
+ processModule.consts.set('Status', interp.classes.ProcessStatus!)
1037
+ def(processModule, 'pid', () => process.pid)
1038
+ interp.defineNative(
1039
+ interp.classes.ProcessStatus!,
1040
+ 'success?',
1041
+ (c) => c.self instanceof RObject && c.self.data === 0,
1042
+ )
1043
+ interp.defineNative(interp.classes.ProcessStatus!, 'exitstatus', (c) =>
1044
+ c.self instanceof RObject && typeof c.self.data === 'number' ? c.self.data : 0,
1045
+ )
1046
+
1047
+ const etc = interp.defineModule('Etc', object)
1048
+ def(etc, 'nprocessors', () => os.cpus().length)
1049
+ const rbConfig = interp.defineModule('RbConfig', object)
1050
+ rbConfig.consts.set(
1051
+ 'CONFIG',
1052
+ RHash.from([
1053
+ [str('host_os'), str('darwin')],
1054
+ [str('ruby_version'), str('3.3.0')],
1055
+ ]),
1056
+ )
1057
+ }
1058
+
1059
+ class FileHandle {
1060
+ private offset = 0
1061
+ constructor(readonly content: string) {}
1062
+ rest(): string {
1063
+ const out = this.content.slice(this.offset)
1064
+ this.offset = this.content.length
1065
+ return out
1066
+ }
1067
+ }
1068
+
1069
+ class GemRequirement {
1070
+ constructor(readonly requirements: string[]) {}
1071
+ }
1072
+
1073
+ class TimeValue {
1074
+ constructor(readonly ms: number) {}
1075
+ }
1076
+
1077
+ class SetData {
1078
+ items = new Map<string, Value>()
1079
+ add(value: Value): boolean {
1080
+ const key = hashKey(value)
1081
+ if (this.items.has(key)) return false
1082
+ this.items.set(key, value)
1083
+ return true
1084
+ }
1085
+ has(value: Value) {
1086
+ return this.items.has(hashKey(value))
1087
+ }
1088
+ delete(value: Value) {
1089
+ this.items.delete(hashKey(value))
1090
+ }
1091
+ values(): Value[] {
1092
+ return [...this.items.values()]
1093
+ }
1094
+ }
1095
+
1096
+ function fnmatch(pattern: string, subject: string, flags: number): boolean {
1097
+ const pathname = (flags & 2) !== 0
1098
+ const dotMatch = (flags & 4) !== 0
1099
+ const extglob = (flags & 16) !== 0
1100
+ const casefold = (flags & 8) !== 0
1101
+ return (extglob ? expandBraces(pattern) : [pattern]).some((p) => {
1102
+ let source = ''
1103
+ for (let i = 0; i < p.length; i++) {
1104
+ const c = p[i]!
1105
+ if (c === '*' && p[i + 1] === '*' && pathname && p[i + 2] === '/') {
1106
+ source += `(?:${dotMatch ? '' : '(?!\\.)'}[^/]*/)*`
1107
+ i += 2
1108
+ } else if (c === '*') source += pathname ? '[^/]*' : '.*'
1109
+ else if (c === '?') source += pathname ? '[^/]' : '.'
1110
+ else if (c === '[') {
1111
+ const end = p.indexOf(']', i + 1)
1112
+ source += end < 0 ? '\\[' : `[${p.slice(i + 1, end).replace(/^!/, '^')}]`
1113
+ if (end >= 0) i = end
1114
+ } else if (c === '\\')
1115
+ source += (p[++i] ?? '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1116
+ else source += c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1117
+ }
1118
+ const leadingDot = !dotMatch && subject.startsWith('.') && !p.startsWith('.')
1119
+ return !leadingDot && new RegExp(`^${source}$`, casefold ? 'is' : 's').test(subject)
1120
+ })
1121
+ }