Class: Squared::Workspace::Project::Node

Inherits:
Git
  • Object
show all
Defined in:
lib/squared/workspace/project/node.rb

Constant Summary

Constants included from Common

Common::ARG, Common::PATH

Instance Attribute Summary

Attributes inherited from Base

#children, #dependfile, #exception, #group, #name, #parent, #path, #pipe, #project, #theme, #verbose, #workspace

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Git

#autostash, #branch, #checkout, #clean, #clone, #clone?, #commit, #diff, #enabled?, #fetch, #generate, #git, #log!, #ls_files, #ls_remote, #merge, #pull, #rebase, #reset, #restore, #rev_parse, #revbuild, #revbuild?, #show, #sparse_checkout, #stash, #status, #submodule, #switch, #tag

Methods inherited from Base

#<=>, #==, #add, #allref, #archive, #archive?, #as, #asdf, #basepath, #basepath!, #build, #build?, #chain, #clean, #clean?, #copy?, #dependname, #doc, #doc?, #empty?, #enabled?, #error, #event, #exclude?, #exist?, #first, #generate, #global, #global=, #global_set, #graph, #graph?, #has?, #inject, #inspect, #last, #lint, #lint?, #localname, #log, options, populate, #prereqs, #prereqs?, ref, #ref?, #rootpath, #run, #scope, #script?, #scriptdata, #scriptname, #series, subtasks, #task_include?, #test, #test?, to_s, #to_s, #to_sym, #unpack, #variable_set, #version=, #with

Methods included from Common::Format

emphasize, #enable_aixterm, #enable_drawing, message, raise_error

Constructor Details

#initialize(ts: 'tsconfig.json', asdf: 'nodejs', **kwargs) ⇒ Node

Returns a new instance of Node.



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/squared/workspace/project/node.rb', line 168

def initialize(*, ts: 'tsconfig.json', asdf: 'nodejs', **kwargs)
  super
  if @pass.include?(Node.ref)
    initialize_ref Node.ref
    initialize_logger kwargs[:log]
  else
    initialize_build(Node.ref, prod: prod?, **kwargs)
    initialize_env(**kwargs)
  end
  @dependname = 'package.json'
  dependfile_set [@dependname]
  serve_set kwargs[:serve]
  @tsfile = basepath! ts
  @pm = { __: kwargs[:init] }
end

Class Method Details

.aliasargsObject



136
137
138
# File 'lib/squared/workspace/project/node.rb', line 136

def aliasargs
  [ref, { refresh: :build }].freeze
end

.bannerargsObject



140
141
142
# File 'lib/squared/workspace/project/node.rb', line 140

def bannerargs
  %i[version dependfile].freeze
end

.batchargsObject



132
133
134
# File 'lib/squared/workspace/project/node.rb', line 132

def batchargs
  [ref, { refresh: %i[build copy] }].freeze
end

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


148
149
150
151
152
# File 'lib/squared/workspace/project/node.rb', line 148

def config?(val)
  return false unless (val = as_path(val))

  val.join('package.json').exist?
end

.prod?Boolean

Returns:

  • (Boolean)


144
145
146
# File 'lib/squared/workspace/project/node.rb', line 144

def prod?
  ENV['NODE_ENV'] == 'production'
end

.tasksObject



128
129
130
# File 'lib/squared/workspace/project/node.rb', line 128

def tasks
  %i[outdated update publish].freeze
end

Instance Method Details

#bump(flag, val = nil) ⇒ Object



1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
# File 'lib/squared/workspace/project/node.rb', line 1061

def bump(flag, val = nil)
  return unless val ||= sembump(version, flag)

  doc = dependfile.read
  if doc.sub!(/"version"\s*:\s*"#{version}"/, "\"version\": \"#{val}\"")
    unless dryrun?
      log.info "bump version #{version} to #{val.subhint(flag)}"
      on :first, :bump
      dependfile.write(doc)
    end
    if stdin?
      puts val
    elsif !silent?
      major = flag == :major
      emphasize("version: #{val}", title: name, border: borderstyle, sub: [
        headerstyle,
        opt_style(color(major ? :green : :yellow), /\A(version:)( )(\S+)(.*)\z/, 3),
        opt_style(theme[major ? :major : :active], /\A(version:)(.*)\z/)
      ])
    end
    unless dryrun?
      commit(:add, [dependname], pass: true)
      on :last, :bump
    end
  else
    raise_error 'version not found', hint: dependfile
  end
rescue => e
  on_error(e, dryrun: dryrun?)
end

#compose(target, opts = nil, script: false, args: nil, from: nil) ⇒ Object



1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'lib/squared/workspace/project/node.rb', line 1156

def compose(target, opts = nil, script: false, args: nil, from: nil, **)
  return unless target

  if script
    ret = session dependbin, 'run'
    raise_error "#{dependbin} run: #{target}", hint: from unless append_any(target, build: true)
    append_any opts if opts
    append_loglevel
    append_any(args, delim: true) if args
    ret
  else
    case target
    when String
      target
    when Hash
      append_hash(target, target: []).join(' ')
    when Enumerable
      target.to_a.join(' ')
    else
      raise_error TypeError, "unknown: #{target}", hint: 'compose'
    end
  end
end

#copy(from: 'build', into: 'node_modules', scope: nil, also: nil, create: nil, files: nil, workspace: false, link: false, force: false, override: false, sync: invoked_sync?('copy'), **kwargs) ⇒ Object



377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/squared/workspace/project/node.rb', line 377

def copy(from: 'build', into: 'node_modules', scope: nil, also: nil, create: nil, files: nil, workspace: false,
         link: false, force: false, override: false, sync: invoked_sync?('copy'), **kwargs)
  return if @copy == false

  glob = kwargs[:include]
  pass = kwargs[:exclude]
  if @copy && !override
    return super unless @copy.is_a?(Hash)

    from = @copy[:from] if @copy.key?(:from)
    into = @copy[:into] if @copy.key?(:into)
    files = @copy[:files] if @copy.key?(:files)
    workspace = @copy[:workspace] if @copy.key?(:workspace)
    link = @copy[:link] if @copy.key?(:link)
    force = @copy[:force] if @copy.key?(:force)
    scope = @copy[:scope] if @copy.key?(:scope)
    also = @copy[:also] if @copy.key?(:also)
    create = @copy[:create] if @copy.key?(:create)
    glob = @copy[:include] if @copy.key?(:include)
    pass = @copy[:exclude] if @copy.key?(:exclude)
  end
  items = []
  if build? && path != @workspace.home && @workspace.home?
    items << @workspace.home
    @workspace.rev_clear(@workspace.find(@workspace.home).name, sync: sync)
  end
  items.concat(as_a(also)) if also
  return if items.empty?

  on :first, :copy
  print_item unless @output[0] || silent? || task_invoked?(/^copy(?::#{Node.ref}|$)/)
  packed = false
  items.each do |dir|
    case dir
    when Pathname
      dest = dir
      @workspace.rev_clear(dest, sync: sync)
    when String
      dest = @workspace.rootpath(dir)
      @workspace.rev_clear(dest, sync: sync)
    when Symbol
      dest = if (proj = @workspace.find(name: dir))
               @workspace.rev_clear(proj.name, sync: sync)
               proj.path
             else
               log.warn message("copy project :#{dir}", hint: 'missing')
               nil
             end
    when Hash
      from = dir[:from] if dir.key?(:from)
      into = dir[:into] if dir.key?(:into)
      scope = dir[:scope] if dir.key?(:scope)
      link = dir[:link] if dir.key?(:link)
      force = dir[:force] if dir.key?(:force)
      dest = dir[:target]
      create = dir[:create]
      workspace = dir[:workspace]
      glob = dir[:include]
      pass = dir[:exclude]
      dest = items.first unless dest && dest != true
      @workspace.rev_clear(dest, sync: sync) unless dest == true
    when Project::Base
      dest = dir.path
      @workspace.rev_clear(dir.name, sync: sync)
    else
      raise_error TypeError, "unknown: #{dir}", hint: 'copy'
    end
    next unless from && dest&.directory?

    if from == :npm
      begin
        unless packed
          require 'open3'
          cmd = session_output 'npm', 'pack --dry-run --no-color', npmname
          files = pwd_set(cmd, from: :'npm:pack') do
            Open3.capture2e(cmd.to_s)
                 .first
                 .scan(/^npm notice \d+(?:\.\d+)?[a-z]+ (.+)$/i)
                 .map { |item| Pathname.new(item.first) }
                 .select(&:exist?)
          end.concat(Array(files))
          packed = true
        end
        base = dest.join(into, npmname)
        base.mkpath
        log.info "cp npm:#{npmname} #{base}"
        errors = 0
        subdir = files.each_with_object([]) do |file, out|
          s, d = file.is_a?(Array) ? file : [file] * 2
          dest = base + d
          target = dest.dirname
          unless out.include?(dirname = target.to_s)
            target.mkpath
            out << dirname
          end
          FileUtils.cp(basepath(s), dest, verbose: !silent?)
        rescue => e
          print_error(Logger::ERROR, e, subject: name)
          errors += 1
        end
      rescue => e
        on_error e, :copy
      else
        puts message(base, subdir.size, files.size - errors) unless silent?
      end
      next
    end
    glob = Array(glob || '**/*')
    target = []
    from = basepath from
    if workspace
      from.glob('*').each do |entry|
        next unless entry.directory?

        sub = if (proj = @workspace.find(entry))
                proj.packagename
              elsif (file = entry + dependname).exist?
                begin
                  doc = JSON.parse(file.read)
                  doc['name']
                rescue => e
                  print_error(Logger::ERROR, e, subject: proj.name)
                end
              end
        if sub
          target << [entry, dest.join(into, sub)]
        else
          log.debug message("#{dependname} in \"#{entry}\"", hint: 'missing')
        end
      end
    else
      target << [from, dest.join(into, scope || npmname)]
    end
    target.each do |src, to|
      glob.each { |val| log.info "cp #{from + val} #{to}" }
      copy_dir(src, to, glob, create: create, link: link, force: force, pass: pass, verbose: !silent?)
    rescue => e
      on_error e
    end
  end
  on :last, :copy
end

#depend(flag = nil, sync: invoked_sync?('depend', flag), packages: [], save: nil, exact: nil, omit: env('NPM_OMIT')) ⇒ Object



520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
# File 'lib/squared/workspace/project/node.rb', line 520

def depend(flag = nil, *, sync: invoked_sync?('depend', flag), packages: [], save: nil, exact: nil,
           omit: env('NPM_OMIT'), **)
  if @depend && !flag
    super
  elsif outdated?
    workspace.rev_clear(name, sync: sync)
    return update if !flag && (env('UPDATE') || env('NODE_UPDATE'))

    add = flag == :add
    if add
      remove, packages = packages.partition { |val| val.delete_prefix!('-') }
      remove.quote!
    end
    save, exact, omit = save if save.is_a?(Array)
    ws = env('NODE_WORKSPACES', equals: '0')
    ci = option('ci')
    om = lambda do |cmd|
      if omit
        save = case save
               when 'peer'
                 'optional'
               when 'optional'
                 'dev'
               when 'dev'
                 'prod'
               end
      end
      return unless save && save != 'bundle'

      cmd << "--#{save}"
    end
    rm = lambda do |target|
      return if remove.empty?

      run(target.temp(*remove).sub!(/ (?:add|install) /, ' remove '), sync: sync, from: :remove)
    end
    yarn = dependtype(:yarn)
    if yarn > 0
      if !flag && yarn > 1 && prod?
        cmd = session 'yarn', 'workspaces focus --all --production'
      else
        cmd = session('yarn', flag || 'install')
        if yarn == 1
          cmd << '--production' if prod?
          cmd << '--ignore-engines' if option('ignore-engines')
          cmd << '--ignore-scripts' if option('ignore-scripts')
          cmd << '--force' if option('force')
        else
          cmd << '--mode=skip-build' if option('ignore-scripts')
          cmd << '--check-cache' if !flag && option('force')
        end
        if nolockfile?('yarn')
          cmd << '--no-lockfile'
        elsif ci
          if yarn == 1
            cmd << '--frozen-lockfile'
          elsif !flag
            cmd << '--immutable' << '--refresh-lockfile'
          end
        end
        if add
          cmd << '-W' if yarn == 1 && option('w', 'ignore-workspace-root-check', notequals: '0')
          rm.call(cmd)
          om.call(cmd)
          cmd << '--exact' if exact
        end
      end
      append_loglevel
    elsif pnpm?
      cmd = session('pnpm', flag || 'install')
      append_nocolor
      append_loglevel
      if add
        om.call(cmd)
        rm.call(cmd)
        cmd << '--save-exact' if exact
        option('allow-build') { |val| cmd << quote_option('allow-build', val) }
      else
        cmd << '--prod' if prod?
        append_platform
      end
      option('public-hoist-pattern') do |val|
        split_escape(val) { |opt| cmd << shell_option('public-hoist-pattern', opt) }
      end
      cmd << '--ignore-workspace' if ws
      cmd << if option('force')
               '--force'
             elsif nolockfile?('pnpm')
               '--no-lockfile'
             elsif ci
               '--frozen-lockfile'
             end
      cmd << '--ignore-scripts' if option('ignore-scripts')
      cmd << '--dangerously-allow-all-builds' if option('approve-builds')
    else
      cmd = session('npm', ci ? 'ci' : 'install')
      cmd << '--workspaces=false' if ws
      cmd << '--force' if option('force')
      append_nocolor
      append_loglevel
      if omit
        cmd << "--omit=#{save || omit}"
        save = nil
      elsif !add && prod?
        cmd << '--include=prod'
      end
      unless ci
        if add
          cmd << "--save-#{save}" if save
          rm.call(cmd)
          cmd << '--save-exact' if exact
        else
          append_platform
        end
      end
      cmd << '--package-lock=false' << 'save=false' if nolockfile?('npm')
      cmd << '--ignore-scripts' if option('ignore-scripts')
    end
    if add
      return if packages.empty?

      cmd.merge(packages.quote!)
    end
    run(sync: sync, from: flag || :depend)
  end
end

#depend?Boolean

Returns:

  • (Boolean)


1204
1205
1206
# File 'lib/squared/workspace/project/node.rb', line 1204

def depend?
  @depend != false && (!@depend.nil? || outdated?)
end

#dependbinObject



1274
1275
1276
1277
1278
1279
1280
# File 'lib/squared/workspace/project/node.rb', line 1274

def dependbin
  if yarn?
    'yarn'
  else
    pnpm? ? 'pnpm' : 'npm'
  end
end

#dependtype(prog) ⇒ Object



1267
1268
1269
1270
1271
1272
# File 'lib/squared/workspace/project/node.rb', line 1267

def dependtype(prog)
  return @pm[prog] if @pm.key?(prog)

  meth = :"#{prog}?"
  respond_to?(meth) && __send__(meth) ? @pm[prog] : 0
end

#dev?Boolean

Returns:

  • (Boolean)


1259
1260
1261
# File 'lib/squared/workspace/project/node.rb', line 1259

def dev?
  super && (!Node.prod? || (@dev == true && !prod?))
end

#outdated(flag = nil, opts = [], sync: invoked_sync?('outdated', flag)) ⇒ Object



647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
# File 'lib/squared/workspace/project/node.rb', line 647

def outdated(flag = nil, opts = [], sync: invoked_sync?('outdated', flag))
  cmd = session(pnpm? && exist?('pnpm-lock.yaml') ? 'pnpm' : 'npm', 'outdated')
  dryrun = has_value?(opts, 'd', 'dry-run') || dryrun?
  unless dryrun
    log.info cmd.to_s
    on :first, :outdated
  end
  banner = format_banner(cmd.temp(('--dry-run' if dryrun)))
  print_item banner if sync
  begin
    data = pwd_set(cmd, dryrun: dryrun) { `#{cmd.temp('--json --loglevel=error')}` }
    doc = dependfile.read
    json = JSON.parse(doc)
    dep1 = json['dependencies'] || {}
    dep2 = json['devDependencies'] || {}
    target = json['name']
  rescue => e
    on_error(e, dryrun: dryrun)
    return
  end
  found = []
  avail = []
  flag ||= case (up = option('u', 'update'))
           when 'major', 'minor'
             up.to_sym
           else
             prod? ? :patch : :minor
           end
  if sync && !stdin?
    items = if has_value?(opts, 's', 'select')
              se = true
              []
            elsif has_value?(opts, 'i', 'interactive')
              ia = true
              []
            end
  end
  unless data.empty?
    JSON.parse(data).each_pair do |key, val|
      val = val.find { |obj| obj['dependent'] == target } if val.is_a?(Array)
      next unless val && (file = dep1[key] || dep2[key]) && file != '*'

      latest = val['latest']
      ch = file[0]
      if ch.match?(/[~^]/)
        file = file[1..-1]
      elsif ia && flag == :major
        major = true
      else
        avail << [key, file, latest, true]
        next
      end
      current = val['current'] || file
      want = val['wanted']
      unless latest[SEM_VER, 6]
        case flag
        when :major
          want = latest
        when :minor
          want = latest if latest[SEM_VER, 1] == want[SEM_VER, 1]
        when :patch
          if (g = latest.match(SEM_VER)) && (h = want.match(SEM_VER)) && g[1] == h[1] && g[3] == h[3]
            want = latest
          end
        end
      end
      next unless (current != want || file != want) && (want.match?(SEM_VER) || !file.match?(SEM_VER))

      f = semscan file
      w = semscan want
      a = f[0]
      b = f[2]
      c = w[0]
      d = w[2]
      upgrade = case flag
                when :major
                  a == '0' ? c == '0' || c == '1' : true
                when :minor
                  ch == '^' && (a == '0' ? c == '0' && b == d : a == c)
                when :patch
                  a == c && b == d && f[4] != w[4]
                end
      if upgrade && !w[5]
        next if file == want

        found << [key, file, want, if a != c
                                     1
                                   elsif b != d
                                     a == '0' ? 1 : 3
                                   else
                                     5
                                   end, major, f, w]
      elsif !major
        avail << [key, file, latest, latest != current]
      end
    end
  end
  pending = 0
  modified = 0
  width = ->(a, i) { a.map { |aa| aa[i] }.max_by(&:size).size }
  pad = ->(val, ord) { val.succ.to_s.rjust([ord.size.to_s.size, 2].max) }
  footer = lambda do |val, size|
    return unless verbose

    msg, hint = if modified == -1
                  ['Packages were updated', 'more possible']
                else
                  ['No packages were updated', 'possible']
                end
    possible = pending + val
    puts print_footer(empty_status(msg, hint, possible == size ? 0 : possible))
  end
  print_item banner unless sync
  if !found.empty?
    col1 = width.call(found, 0) + 4
    col2 = width.call(found, 1) + 4
    col3 = pad.call(found.size, found).size + 2 + col1 + col2 + width.call(found, 2)
    packages = []
    pat = ->(a) { /("#{Regexp.escape(a[0])}"\s*:\s*)"([~^])#{'?' if a[4]}#{Regexp.escape(a[1])}"/ }
    edit = lambda do |a, pkg, mod|
      packages << a[0]
      modified += 1
      "#{pkg}\"#{mod || (a[3] == 1 && a[4] ? '^' : '')}#{a[2]}\""
    end
    found.each_with_index do |item, i|
      a, b, c, d, e = item
      cur = modified
      doc.send(items ? :sub : :sub!, pat.call(item)) do |capture|
        if $2 == '~' && flag != :patch
          cur = -1
          pending += 1
          capture
        else
          edit.call(item, $1, $2)
        end
      end
      a = a.ljust(col1)
      b = b.ljust(col2)
      sub_style! b, theme[:current] if theme[:current] && !stdin?
      if cur == -1
        c = 'SKIP'
      elsif modified == cur
        c = 'FAIL'
      elsif !stdin?
        if d == 1
          sub_style! a, theme[:major]
          sub_style! c, :bold, color(:green)
        else
          sub_style!(c, **opt_style(color(d == 3 ? :green : :yellow), SEM_VER, d))
        end
        g = item
      end
      s = "#{pad.call(i, found)}. #{a}#{b}#{c}"
      if se
        items << [s, g]
        next
      elsif ia && g
        items << [g]
        if flag != :major || e || semmajor?(item[5], item[6])
          items.pop unless confirm_semver(s.ljust(col3 + s.size - s.stripstyle.size), (d / 2.0).ceil)
          next
        end
      end
      puts s
    end
    pending = avail.reduce(pending) { |a, b| a + (b[3] ? 0 : 1) }
    if (dryrun && Array(items).empty?) || (modified == 0 && (pending > 0 || (items && pending == 0)))
      n = if items
            if items.empty?
              puts 'No updates were selected'
              0
            else
              puts items.map(&:first) if se
              items.size
            end
          else
            found.size
          end
      footer.call(modified, n) unless n == 0
    elsif modified > 0
      if items
        packages.clear
        if ia
          (1..items.size)
        else
          choice('Select a package', items.map(&:first), multiple: true, force: false, index: true,
                                                         border: true)
        end.each do |n|
          item = items[n.pred].last
          doc.sub!(pat.call(item)) { edit.call(item, $1, $2) }
        end
      end
      unless packages.empty?
        modified = -1
        if dryrun
          footer.call(0, found.size)
        else
          File.write(dependfile, doc)
          if sync && (opts.include?('diff') || option('diff'))
            run(git_output('diff', shell_quote(dependfile)), banner: false)
          end
          if has_value?(opts, 'u', 'update') || up
            package(:update, packages: packages, from: :'outdated:update')
          else
            footer.call(0, found.size)
          end
          printsucc
          commit(:add, [dependname], pass: true)
        end
      end
    end
  elsif !avail.empty?
    col1 = width.call(avail, 0) + 4
    col2 = width.call(avail, 1)
    col3 = width.call(avail, 2) + 4
    avail.each_with_index do |item, i|
      a, b, c, d = item
      a = a.ljust(col1)
      b = sub_style b.ljust(col2), color(d ? :red : :yellow)
      c = c.ljust(col3)
      unless d
        sub_style! a, theme[:active]
        sub_style! c, color(:green)
        pending += 1
      end
      puts "#{pad.call(i, avail)}. #{(a + c + b).subhint(d ? 'locked' : 'latest')}"
    end
    footer.call(0, avail.size)
  else
    puts 'No updates were found'
  end
  on :last, :outdated unless dryrun
end

#outdated?Boolean

Returns:

  • (Boolean)


1208
1209
1210
# File 'lib/squared/workspace/project/node.rb', line 1208

def outdated?
  dependfile.exist? && !task_pass?('outdated')
end

#pack(opts = []) ⇒ Object



1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
# File 'lib/squared/workspace/project/node.rb', line 1092

def pack(opts = [])
  return unless version

  cmd = session dependbin, 'pack'
  if dependtype(:yarn) > 1
    op = OptionPartition.new(opts, OPT_BERRY[:pack], cmd, project: self, strict: strict?)
    op.append?('out', Pathname.pwd + "#{project}-#{version}.tgz")
  else
    op = OptionPartition.new(opts, pnpm? ? OPT_PNPM[:pack] : npmopts(:pack), cmd, project: self,
                                                                                  strict: strict?)
    unless pnpm?
      op.each do |opt|
        next unless opt =~ op.values

        case $1
        when 'w', 'workspace'
          op << quotepath($1, $2)
          op.found << opt
        end
      end
    end
    op.append?('pack-destination', Dir.pwd)
  end
  op.clear
  run(from: :pack)
end

#package(flag, opts = [], packages: [], from: nil) ⇒ Object



929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
# File 'lib/squared/workspace/project/node.rb', line 929

def package(flag, opts = [], packages: [], from: nil)
  workspace.rev_clear(name)
  yarn = dependtype(:yarn)
  if yarn > 0 && !(yarn == 1 && ((flag == :update && !packages.empty?) || flag == :rebuild))
    cmd = session 'yarn', case flag
                          when :update
                            if yarn == 1
                              'upgrade'
                            else
                              spec = 0
                              'up'
                            end
                          when :reinstall
                            if yarn == 1
                              remove_modules 'yarn' if opts.include?('force')
                            elsif opts.delete('force')
                              opts << 'check-cache'
                            end
                            opts << 'no-lockfile' if lockfile(true)
                            'install'
                          when :add
                            spec = 1
                            'add'
                          else
                            yarn == 1 && flag == :dedupe ? 'install' : flag
                          end
    op = OptionPartition.new(opts, if yarn == 1
                                     OPT_YARN.fetch(flag == :dedupe ? :install : flag, []) + OPT_YARN[:common]
                                   else
                                     OPT_BERRY.fetch(flag, []) + case flag
                                                                 when :add, :update then OPT_BERRY[:add_a]
                                                                 else []
                                                                 end
                                   end, cmd, project: self, strict: strict?)
    if yarn == 1 && flag != :reinstall
      op << '--no-lockfile' if nolockfile?('yarn')
      op << '--ignore-engines' if option('ignore-engines')
    end
  else
    args = if pnpm?
             case flag
             when :install, :update
               opts << 'no-lockfile' if nolockfile?('pnpm')
               spec = 0 if flag == :update
             when :add
               spec = 1
             when :reinstall
               opts << 'force'
               flag = :install
             end
             flags = [flag]
             flags << :install_a unless flag == :rebuild
             unless flag == :dedupe
               flags << :common_filter
               unless flag == :add
                 flags << :install_b
                 flags << :common_cpu unless flag == :update
               end
             end
             no = OPT_PNPM[:no][flag]
             [
               opts,
               pnpmopts(*flags),
               session('pnpm', flag)
             ]
           else
             case flag
             when :install, :update
               opts.unshift('package-lock=false', 'save=false') if nolockfile?('npm')
               spec = flag == :install ? 0 : 2
             when :add
               spec = 1
               flag = :install
             when :reinstall
               remove_modules 'npm' if opts.delete('force')
               opts.unshift('package-lock=false') if lockfile(true)
               flag = :install
             end
             flags = [flag]
             unless flag == :rebuild
               flags << :install_a
               unless flag == :dedupe
                 %w[save ignore-scripts strict-peer-deps].each do |key|
                   option(key, prefix: 'npm', ignore: false) do |val|
                     opts << basic_option(key, case val
                                               when '0', 'false'
                                                 false
                                               else
                                                 true
                                               end)
                   end
                 end
                 flags << :install_b
               end
               no = OPT_NPM[:no][:install]
             end
             [
               opts,
               npmopts(*flags),
               session('npm', flag)
             ]
           end
    op = OptionPartition.new(*args, no: no, project: self, strict: strict?)
    append_platform if flag == :install
    append_nocolor
  end
  append_loglevel
  case spec
  when Numeric
    op.each do |opt|
      if opt =~ op.values
        case $1
        when 'w', 'workspace'
          op << quotepath($1, $2)
        end
      elsif opt.match?(/^-|=/)
        op.errors << opt
      else
        op.found << (spec == 2 && (n = opt.index('@')) ? opt[0, n] : opt)
      end
    end
    op.swap.concat(packages)
    raise ArgumentError, 'no packages to add' if op.empty? && spec == 1

    op.append(quote: true)
      .clear(errors: true)
  else
    op.clear
  end
  run(from: from || symjoin('package', flag))
end

#packagenameObject



1286
1287
1288
# File 'lib/squared/workspace/project/node.rb', line 1286

def packagename
  read_package 'name'
end

#pnpm?Boolean

Returns:

  • (Boolean)


1241
1242
1243
1244
1245
1246
1247
1248
1249
# File 'lib/squared/workspace/project/node.rb', line 1241

def pnpm?
  (@pm[:pnpm] ||= if rootpath('pnpm-lock.yaml', ascend: dependroot).exist?
                    pnpmtype
                  elsif (ver = read_package || read_install)
                    ver.start_with?('pnpm') ? pnpmtype : 0
                  else
                    @pm[:__] == 'pnpm' ? pnpmtype : 0
                  end) > 0
end

#populateObject



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/squared/workspace/project/node.rb', line 188

def populate(*, **)
  super
  return unless (outdated? && ref?(Node.ref)) || @only

  namespace name do
    Node.subtasks do |action, flags|
      next if task_pass?(action)

      if flags.nil?
        case action
        when 'add'
          format_desc action, nil, 'save?=[=-]prod|dev|optional|peer|bundle,(-)name+'
          task action, [:save] do |_, args|
            packages = if args.save =~ /\A([=-]*)?(prod|dev|optional|peer|bundle)\z/
                         save = [$2, $1.include?('='), $1.include?('-')]
                         args.extras
                       else
                         save = 'prod'
                         args.to_a
                       end
            param_guard(action, 'name', args: packages)
            depend(:add, packages: packages, save: save)
          end
        when 'run'
          next if scripts.empty?

          format_desc action, nil, "script,opts*|#{indexchar}index+|#,pattern*"
          task action, [:script] do |_, args|
            list = scripts.to_a
            if args.script == '#'
              format_list(list, "run[#{indexchar}N]", 'scripts', grep: args.extras, from: dependfile)
            else
              args = param_guard(action, 'script', args: args.to_a)
              opts = args.each_with_object([]) do |val, out|
                if (n, extra = indexitem(val))
                  if (item = list[n.pred])
                    run compose([item.first, extra].compact.join(' '), script: true)
                  elsif exception
                    indexerror n, list
                  else
                    log.warn "run script #{n} of #{list.size}".subhint('out of range')
                    next
                  end
                else
                  out << val
                end
              end
              next if opts.empty?

              yarn = dependtype(:yarn)
              list = if yarn > 0
                       yarn == 1 ? OPT_YARN[:run] + OPT_YARN[:common] : OPT_BERRY[:run]
                     elsif pnpm?
                       pnpmopts :run, :common_filter
                     else
                       npmopts :run
                     end
              OptionPartition.new(opts, list, session(dependbin, 'run'), project: self, strict: strict?)
                             .add_first
                             .append(delim: true, quote: false)
              run(from: :run)
            end
          end
        when 'exec'
          format_desc action, nil, 'pkg/cmd,opts*,args*'
          task action, [:package] do |_, args|
            if (package = args.package)
              args = args.extras
              cmd = if pnpm?
                      pre = ->(ch) { "-#{ch}" if args.delete(ch) }
                      list = pnpmopts :exec, :common_filter
                      session 'pnpm', pre.call('r'), pre.call('c'), 'exec'
                    else
                      list = npmopts :exec
                      session 'npm', 'exec'
                    end
              op = OptionPartition.new(args, list, cmd, project: self, strict: strict?)
              if op.empty?
                op << package
                if (args = readline('Enter arguments', force: false))
                  op.delim unless pnpm?
                  op << args
                end
              else
                op.delim unless pnpm?
                op << package << op.join(' ')
              end
            else
              session 'npm', 'exec', quote_option('c', readline('Enter command', force: true), double: true)
            end
            run(from: :exec)
          end
        when 'nvm'
          next unless ENV['NVM_DIR'] && !workspace.windows?

          format_desc action, nil, 'version?,args*'
          task action, [:version] do |_, args|
            path = ->(s) { File.join(ENV['NVM_DIR'], s) }
            unless (version = args.version)
              cmd = ". #{path.call('nvm.sh')} && nvm list --no-colors --no-alias"
              version = pwd_set(from: :nvm) do
                choice_index('Select a version', IO.popen(cmd).map { |line| line[/\s(v\S+)/, 1] }, series: true)
              end
            end
            args = args.extras
            args << readline('Enter command', force: true) if args.empty?
            args.unshift(path.call('nvm-exec'))
            run(args.join(' '), { 'NODE_VERSION' => version }, banner: false, from: :nvm)
          end
        when 'pack'
          format_desc action, nil, 'opts*'
          task action do |_, args|
            pack args.to_a
          end
        end
      else
        namespace action do
          flags.each do |flag|
            case action
            when 'outdated'
              format_desc action, flag, "#{shortname('i', 's', 'u', 'd')},diff"
              task flag do |_, args|
                outdated flag, args.to_a
              end
            when 'package'
              format_desc(action, flag, 'opts*', before: case flag
                                                         when :dedupe, :rebuild then nil
                                                         when :reinstall then 'force?'
                                                         else 'name*'
                                                         end)
              task flag do |_, args|
                package flag, args.to_a
              end
            when 'bump'
              break unless version

              if flag == :version
                format_desc action, flag, 'version'
                task flag, [:version] do |_, args|
                  version = param_guard(action, flag, args: args, key: :version)
                  bump flag, version
                end
              else
                format_desc action, flag
                task flag do
                  bump flag
                end
              end
            when 'publish'
              format_desc(action, flag, 'otp?,p/ublic|r/estricted?,d/ry-run?', before: ('tag' if flag == :tag))
              task flag do |_, args|
                args = args.to_a
                access = if has_value!(args, 'r', 'restricted')
                           'restricted'
                         elsif has_value!(args, 'p', 'public')
                           'public'
                         end
                dryrun = has_value!(args, 'd', 'dry-run')
                if flag == :latest
                  otp = args.first
                else
                  tag, otp = param_guard(action, flag, args: args)
                end
                publish(flag, otp: otp, tag: tag, access: access, dryrun: dryrun)
              end
            when 'tsc'
              break unless @tsfile

              format_desc(action, flag, 'opts*', "#{flag == :project ? 'before' : 'after'}": 'config?')
              task flag do |_, args|
                args = args.to_a
                if flag == :project
                  project = if exist?(args.first)
                              args.shift
                            else
                              @tsfile
                            end
                end
                watch = has_value!(args, 'w', 'watch')
                tsc(*args, banner: true, project: project, build: flag == :build, watch: !watch.nil?)
              end
            end
          end
        end
      end
    end
  end
end

#prod?Boolean

Returns:

  • (Boolean)


1263
1264
1265
# File 'lib/squared/workspace/project/node.rb', line 1263

def prod?
  @prod != false && (Node.prod? || super)
end

#publish(flag = nil, sync: invoked_sync?('publish', flag), otp: nil, tag: nil, access: nil, dryrun: nil) ⇒ Object



885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
# File 'lib/squared/workspace/project/node.rb', line 885

def publish(flag = nil, *, sync: invoked_sync?('publish', flag), otp: nil, tag: nil, access: nil, dryrun: nil)
  if read_package('private')
    ws = children.select { |proj| proj.ref?(Node.ref) }
    if ws.empty?
      print_error('nothing to publish', subject: name, hint: 'private')
    elsif confirm_basic('Publish workspace?', ws.map(&:name).join(', '), 'N')
      ws.each { |proj| proj.publish(flag, sync: sync, otp: otp, tag: tag, access: access, dryrun: dryrun) }
    end
    return
  end
  return print_error("version: #{dependname}", subject: name, hint: 'not found') unless version

  cmd = session 'npm', 'publish'
  cmd << basic_option('otp', otp) if otp ||= option('otp')
  cmd << basic_option('tag', tag.tr(' ', '-')) if tag ||= option('tag')
  case access || option('access')
  when 'p', 'public'
    cmd << '--access=public'
  when 'r', 'restricted'
    cmd << '--access=restricted'
  end
  dryrun ||= dryrun?('npm')
  if dryrun
    cmd << '--dry-run'
  else
    from = :'npm:publish'
    log.info cmd.to_s
  end
  if sync
    run(sync: sync, from: from, interactive: !dryrun && ['Publish', 'N', npmname])
  else
    require 'open3'
    on :first, from
    pwd_set(cmd, dryrun: dryrun) do
      cmd = session_done cmd
      Open3.popen2e(cmd) do |_, out|
        write_lines(out, banner: format_banner(cmd),
                         sub: npmnotice(opt_style(color(:bright_blue), /^(.+)(Tarball .+)$/, 2)))
      end
    end
    on :last, from
  end
end

#refObject



184
185
186
# File 'lib/squared/workspace/project/node.rb', line 184

def ref
  Node.ref
end

#refresh?Boolean

Returns:

  • (Boolean)


1216
1217
1218
# File 'lib/squared/workspace/project/node.rb', line 1216

def refresh?
  !Node.prod?
end

#scriptsObject



1290
1291
1292
# File 'lib/squared/workspace/project/node.rb', line 1290

def scripts
  @scripts ||= read_package('scripts').yield_self { |ret| ret.is_a?(Hash) ? ret : {} }
end

#serve(root, opts = [], bind: nil, port: 3000) ⇒ Object



1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
# File 'lib/squared/workspace/project/node.rb', line 1180

def serve(root, opts = [], bind: nil, port: 3000, **)
  var = {}
  if File.extname(root) =~ /[cm]?js/
    var['HOST'] = bind if bind
    var['PORT'] = port.to_s if port
    target = root
    root = File.dirname(target)
  else
    require 'tempfile'
    app = APP_SERVE.dup
    app.gsub!('$ROOT', root)
    app.gsub!('$HOST', bind || 'localhost')
    app.gsub!('$PORT', port.to_s)
    file = Tempfile.new([name, '.cjs'])
    file.write(app)
    file.close
    trap 'INT' do
      file.unlink
    end
    target = file.path
  end
  shell(var, session('node', shell_quote(target), *opts.map { |s| fill_option(s) }).done, chdir: root)
end

#tsc(*args, with: nil, pass: , sync: true, banner: verbose?, , from: :tsc, **kwargs) ⇒ Object



1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
# File 'lib/squared/workspace/project/node.rb', line 1119

def tsc(*args, with: nil, pass: PASS_NODE[:tsc], sync: true, banner: verbose?, from: :tsc, **kwargs)
  session_apply(with, args: args, kwargs: kwargs, pass: pass) if with
  p = kwargs[:project]
  b = kwargs[:build]
  w = kwargs[:watch]
  list = OPT_TSC[:base] + OPT_TSC[:compiler]
  list.concat(Array(kwargs.fetch(:legacy, 5)).flat_map { |n| OPT_TSC.fetch(:"v#{n}", {}).fetch(:compiler, []) })
  cmd = session 'tsc', if p
                         quote_option 'p', basepath(p)
                       elsif b
                         list.concat(OPT_TSC[:build])
                         '-b'
                       end
  if w
    list.concat(OPT_TSC[:watch])
    cmd << '-w'
  end
  op = OptionPartition.new(args, list, cmd, project: self, strict: strict?, sep: ' ')
  unless p
    if b.is_a?(String)
      op.add_path(b)
    elsif w.is_a?(String)
      op.add_path(w)
    else
      op.exist?(add: true)
    end
  end
  op.clear
  cmd = session_done(op.target)
  print_run(cmd, banner, **kwargs)
  session 'npx', cmd
  start = time_epoch if kwargs.fetch(:verbose, verbose? && !stdin?)
  ret = run(sync: sync, banner: banner, exception: kwargs.fetch(:exception, exception?), from: from)
  print_status(name, subject: 'tsc', start: start) if success?(ret, banner, start.nil?) && start
  ret
end

#updateObject



881
882
883
# File 'lib/squared/workspace/project/node.rb', line 881

def update(*)
  package(:update, from: :update)
end

#update?Boolean

Returns:

  • (Boolean)


1212
1213
1214
# File 'lib/squared/workspace/project/node.rb', line 1212

def update?
  outdated?
end

#versionObject



1282
1283
1284
# File 'lib/squared/workspace/project/node.rb', line 1282

def version
  @version ||= read_package('version')
end

#workspaces?Boolean

Returns:

  • (Boolean)


1251
1252
1253
1254
1255
1256
1257
# File 'lib/squared/workspace/project/node.rb', line 1251

def workspaces?
  if pnpm?
    exist?('pnpm-workspace.yaml')
  else
    read_package('workspaces').is_a?(Array)
  end
end

#yarn?Boolean

Returns:

  • (Boolean)


1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
# File 'lib/squared/workspace/project/node.rb', line 1220

def yarn?
  (@pm[:yarn] ||= if rootpath('yarn.lock', ascend: dependroot).exist?
                    yarntype
                  elsif (ver = read_package || read_install)
                    if ver =~ /^yarn(?:@(\d)|$)/
                      $1 && $1.to_i > 1 ? yarntype : 1
                    else
                      0
                    end
                  else
                    case @pm[:__]
                    when 'yarn'
                      1
                    when 'berry'
                      yarntype
                    else
                      0
                    end
                  end) > 0
end