<commit_before>// @flow
/* Trying to avoid the unknown-prop errors on styled components
 by filtering by React's attribute whitelist.
 */

/* Logic copied from ReactDOMUnknownPropertyHook */
const reactProps = {
  children: true,
  dangerouslySetInnerHTML: true,
  key: true,
  ref: true,
  autoFocus: true,
  defaultValue: true,
  valueLink: true,
  defaultChecked: true,
  checkedLink: true,
  innerHTML: true,
  suppressContentEditableWarning: true,
  onFocusIn: true,
  onFocusOut: true,
  className: true,

  /* List copied from https://facebook.github.io/react/docs/events.html */
  onCopy: true,
  onCut: true,
  onPaste: true,
  onCompositionEnd: true,
  onCompositionStart: true,
  onCompositionUpdate: true,
  onKeyDown: true,
  onKeyPress: true,
  onKeyUp: true,
  onFocus: true,
  onBlur: true,
  onChange: true,
  onInput: true,
  onSubmit: true,
  onReset: true,
  onClick: true,
  onContextMenu: true,
  onDoubleClick: true,
  onDrag: true,
  onDragEnd: true,
  onDragEnter: true,
  onDragExit: true,
  onDragLeave: true,
  onDragOver: true,
  onDragStart: true,
  onDrop: true,
  onMouseDown: true,
  onMouseEnter: true,
  onMouseLeave: true,
  onMouseMove: true,
  onMouseOut: true,
  onMouseOver: true,
  onMouseUp: true,
  onSelect: true,
  onTouchCancel: true,
  onTouchEnd: true,
  onTouchMove: true,
  onTouchStart: true,
  onScroll: true,
  onWheel: true,
  onAbort: true,
  onCanPlay: true,
  onCanPlayThrough: true,
  onDurationChange: true,
  onEmptied: true,
  onEncrypted: true,
  onEnded: true,
  onError: true,
  onLoadedData: true,
  onLoadedMetadata: true,
  onLoadStart: true,
  onPause: true,
  onPlay: true,
  onPlaying: true,
  onProgress: true,
  onRateChange: true,
  onSeeked: true,
  onSeeking: true,
  onStalled: true,
  onSuspend: true,
  onTimeUpdate: true,
  onVolumeChange: true,
  onWaiting: true,
  onLoad: true,
  onAnimationStart: true,
  onAnimationEnd: true,
  onAnimationIteration: true,
  onTransitionEnd: true,

  onCopyCapture: true,
  onCutCapture: true,
  onPasteCapture: true,
  onCompositionEndCapture: true,
  onCompositionStartCapture: true,
  onCompositionUpdateCapture: true,
  onKeyDownCapture: true,
  onKeyPressCapture: true,
  onKeyUpCapture: true,
  onFocusCapture: true,
  onBlurCapture: true,
  onChangeCapture: true,
  onInputCapture: true,
  onSubmitCapture: true,
  onResetCapture: true,
  onClickCapture: true,
  onContextMenuCapture: true,
  onDoubleClickCapture: true,
  onDragCapture: true,
  onDragEndCapture: true,
  onDragEnterCapture: true,
  onDragExitCapture: true,
  onDragLeaveCapture: true,
  onDragOverCapture: true,
  onDragStartCapture: true,
  onDropCapture: true,
  onMouseDownCapture: true,
  onMouseEnterCapture: true,
  onMouseLeaveCapture: true,
  onMouseMoveCapture: true,
  onMouseOutCapture: true,
  onMouseOverCapture: true,
  onMouseUpCapture: true,
  onSelectCapture: true,
  onTouchCancelCapture: true,
  onTouchEndCapture: true,
  onTouchMoveCapture: true,
  onTouchStartCapture: true,
  onScrollCapture: true,
  onWheelCapture: true,
  onAbortCapture: true,
  onCanPlayCapture: true,
  onCanPlayThroughCapture: true,
  onDurationChangeCapture: true,
  onEmptiedCapture: true,
  onEncryptedCapture: true,
  onEndedCapture: true,
  onErrorCapture: true,
  onLoadedDataCapture: true,
  onLoadedMetadataCapture: true,
  onLoadStartCapture: true,
  onPauseCapture: true,
  onPlayCapture: true,
  onPlayingCapture: true,
  onProgressCapture: true,
  onRateChangeCapture: true,
  onSeekedCapture: true,
  onSeekingCapture: true,
  onStalledCapture: true,
  onSuspendCapture: true,
  onTimeUpdateCapture: true,
  onVolumeChangeCapture: true,
  onWaitingCapture: true,
  onLoadCapture: true,
  onAnimationStartCapture: true,
  onAnimationEndCapture: true,
  onAnimationIterationCapture: true,
  onTransitionEndCapture: true,
}

/* From HTMLDOMPropertyConfig */
const htmlProps = {
  /**
   * Standard Properties
   */
  accept: true,
  acceptCharset: true,
  accessKey: true,
  action: true,
  allowFullScreen: true,
  allowTransparency: true,
  alt: true,
  // specifies target context for links with `preload` type
  as: true,
  async: true,
  autoComplete: true,
  // autoFocus is polyfilled/normalized by AutoFocusUtils
  // autoFocus: true,
  autoPlay: true,
  capture: true,
  cellPadding: true,
  cellSpacing: true,
  charSet: true,
  challenge: true,
  checked: true,
  cite: true,
  classID: true,
  className: true,
  cols: true,
  colSpan: true,
  content: true,
  contentEditable: true,
  contextMenu: true,
  controls: true,
  coords: true,
  crossOrigin: true,
  data: true, // For `<object />` acts as `src`.
  dateTime: true,
  default: true,
  defer: true,
  dir: true,
  disabled: true,
  download: true,
  draggable: true,
  encType: true,
  form: true,
  formAction: true,
  formEncType: true,
  formMethod: true,
  formNoValidate: true,
  formTarget: true,
  frameBorder: true,
  headers: true,
  height: true,
  hidden: true,
  high: true,
  href: true,
  hrefLang: true,
  htmlFor: true,
  httpEquiv: true,
  icon: true,
  id: true,
  inputMode: true,
  integrity: true,
  is: true,
  keyParams: true,
  keyType: true,
  kind: true,
  label: true,
  lang: true,
  list: true,
  loop: true,
  low: true,
  manifest: true,
  marginHeight: true,
  marginWidth: true,
  max: true,
  maxLength: true,
  media: true,
  mediaGroup: true,
  method: true,
  min: true,
  minLength: true,
  // Caution; `option.selected` is not updated if `select.multiple` is
  // disabled with `removeAttribute`.
  multiple: true,
  muted: true,
  name: true,
  nonce: true,
  noValidate: true,
  open: true,
  optimum: true,
  pattern: true,
  placeholder: true,
  playsInline: true,
  poster: true,
  preload: true,
  profile: true,
  radioGroup: true,
  readOnly: true,
  referrerPolicy: true,
  rel: true,
  required: true,
  reversed: true,
  role: true,
  rows: true,
  rowSpan: true,
  sandbox: true,
  scope: true,
  scoped: true,
  scrolling: true,
  seamless: true,
  selected: true,
  shape: true,
  size: true,
  sizes: true,
  span: true,
  spellCheck: true,
  src: true,
  srcDoc: true,
  srcLang: true,
  srcSet: true,
  start: true,
  step: true,
  style: true,
  summary: true,
  tabIndex: true,
  target: true,
  title: true,
  // Setting .type throws on non-<input> tags
  type: true,
  useMap: true,
  value: true,
  width: true,
  wmode: true,
  wrap: true,

  /**
   * RDFa Properties
   */
  about: true,
  datatype: true,
  inlist: true,
  prefix: true,
  // property is also supported for OpenGraph in meta tags.
  property: true,
  resource: true,
  typeof: true,
  vocab: true,

  /**
   * Non-standard Properties
   */
  // autoCapitalize and autoCorrect are supported in Mobile Safari for
  // keyboard hints.
  autoCapitalize: true,
  autoCorrect: true,
  // autoSave allows WebKit/Blink to persist values of input fields on page reloads
  autoSave: true,
  // color is for Safari mask-icon link
  color: true,
  // itemProp, itemScope, itemType are for
  // Microdata support. See http://schema.org/docs/gs.html
  itemProp: true,
  itemScope: true,
  itemType: true,
  // itemID and itemRef are for Microdata support as well but
  // only specified in the WHATWG spec document. See
  // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
  itemID: true,
  itemRef: true,
  // results show looking glass icon and recent searches on input
  // search fields in WebKit/Blink
  results: true,
  // IE-only attribute that specifies security restrictions on an iframe
  // as an alternative to the sandbox attribute on IE<10
  security: true,
  // IE-only attribute that controls focus behavior
  unselectable: 0,
}

const svgProps = {
  accentHeight: true,
  accumulate: true,
  additive: true,
  alignmentBaseline: true,
  allowReorder: true,
  alphabetic: true,
  amplitude: true,
  arabicForm: true,
  ascent: true,
  attributeName: true,
  attributeType: true,
  autoReverse: true,
  azimuth: true,
  baseFrequency: true,
  baseProfile: true,
  baselineShift: true,
  bbox: true,
  begin: true,
  bias: true,
  by: true,
  calcMode: true,
  capHeight: true,
  clip: true,
  clipPath: true,
  clipRule: true,
  clipPathUnits: true,
  colorInterpolation: true,
  colorInterpolationFilters: true,
  colorProfile: true,
  colorRendering: true,
  contentScriptType: true,
  contentStyleType: true,
  cursor: true,
  cx: true,
  cy: true,
  d: true,
  decelerate: true,
  descent: true,
  diffuseConstant: true,
  direction: true,
  display: true,
  divisor: true,
  dominantBaseline: true,
  dur: true,
  dx: true,
  dy: true,
  edgeMode: true,
  elevation: true,
  enableBackground: true,
  end: true,
  exponent: true,
  externalResourcesRequired: true,
  fill: true,
  fillOpacity: true,
  fillRule: true,
  filter: true,
  filterRes: true,
  filterUnits: true,
  floodColor: true,
  floodOpacity: true,
  focusable: true,
  fontFamily: true,
  fontSize: true,
  fontSizeAdjust: true,
  fontStretch: true,
  fontStyle: true,
  fontVariant: true,
  fontWeight: true,
  format: true,
  from: true,
  fx: true,
  fy: true,
  g1: true,
  g2: true,
  glyphName: true,
  glyphOrientationHorizontal: true,
  glyphOrientationVertical: true,
  glyphRef: true,
  gradientTransform: true,
  gradientUnits: true,
  hanging: true,
  horizAdvX: true,
  horizOriginX: true,
  ideographic: true,
  imageRendering: true,
  in: true,
  in2: true,
  intercept: true,
  k: true,
  k1: true,
  k2: true,
  k3: true,
  k4: true,
  kernelMatrix: true,
  kernelUnitLength: true,
  kerning: true,
  keyPoints: true,
  keySplines: true,
  keyTimes: true,
  lengthAdjust: true,
  letterSpacing: true,
  lightingColor: true,
  limitingConeAngle: true,
  local: true,
  markerEnd: true,
  markerMid: true,
  markerStart: true,
  markerHeight: true,
  markerUnits: true,
  markerWidth: true,
  mask: true,
  maskContentUnits: true,
  maskUnits: true,
  mathematical: true,
  mode: true,
  numOctaves: true,
  offset: true,
  opacity: true,
  operator: true,
  order: true,
  orient: true,
  orientation: true,
  origin: true,
  overflow: true,
  overlinePosition: true,
  overlineThickness: true,
  paintOrder: true,
  panose1: true,
  pathLength: true,
  patternContentUnits: true,
  patternTransform: true,
  patternUnits: true,
  pointerEvents: true,
  points: true,
  pointsAtX: true,
  pointsAtY: true,
  pointsAtZ: true,
  preserveAlpha: true,
  preserveAspectRatio: true,
  primitiveUnits: true,
  r: true,
  radius: true,
  refX: true,
  refY: true,
  renderingIntent: true,
  repeatCount: true,
  repeatDur: true,
  requiredExtensions: true,
  requiredFeatures: true,
  restart: true,
  result: true,
  rotate: true,
  rx: true,
  ry: true,
  scale: true,
  seed: true,
  shapeRendering: true,
  slope: true,
  spacing: true,
  specularConstant: true,
  specularExponent: true,
  speed: true,
  spreadMethod: true,
  startOffset: true,
  stdDeviation: true,
  stemh: true,
  stemv: true,
  stitchTiles: true,
  stopColor: true,
  stopOpacity: true,
  strikethroughPosition: true,
  strikethroughThickness: true,
  string: true,
  stroke: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeLinecap: true,
  strokeLinejoin: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true,
  surfaceScale: true,
  systemLanguage: true,
  tableValues: true,
  targetX: true,
  targetY: true,
  textAnchor: true,
  textDecoration: true,
  textRendering: true,
  textLength: true,
  to: true,
  transform: true,
  u1: true,
  u2: true,
  underlinePosition: true,
  underlineThickness: true,
  unicode: true,
  unicodeBidi: true,
  unicodeRange: true,
  unitsPerEm: true,
  vAlphabetic: true,
  vHanging: true,
  vIdeographic: true,
  vMathematical: true,
  values: true,
  vectorEffect: true,
  version: true,
  vertAdvY: true,
  vertOriginX: true,
  vertOriginY: true,
  viewBox: true,
  viewTarget: true,
  visibility: true,
  widths: true,
  wordSpacing: true,
  writingMode: true,
  x: true,
  xHeight: true,
  x1: true,
  x2: true,
  xChannelSelector: true,
  xlinkActuate: true,
  xlinkArcrole: true,
  xlinkHref: true,
  xlinkRole: true,
  xlinkShow: true,
  xlinkTitle: true,
  xlinkType: true,
  xmlBase: true,
  xmlns: true,
  xmlnsXlink: true,
  xmlLang: true,
  xmlSpace: true,
  y: true,
  y1: true,
  y2: true,
  yChannelSelector: true,
  z: true,
  zoomAndPan: true,
}

/* From DOMProperty */
const ATTRIBUTE_NAME_START_CHAR =
  ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'
const ATTRIBUTE_NAME_CHAR = `${ATTRIBUTE_NAME_START_CHAR}\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040`
const isCustomAttribute = RegExp.prototype.test.bind(
  new RegExp(`^(data|aria)-[${ATTRIBUTE_NAME_CHAR}]*$`),
)

const hasOwnProperty: (name: string) => boolean = {}.hasOwnProperty
export default (name: string) =>
  hasOwnProperty.call(htmlProps, name) ||
  hasOwnProperty.call(svgProps, name) ||
  isCustomAttribute(name.toLowerCase()) ||
  hasOwnProperty.call(reactProps, name)
<commit_msg>revert "Revert "replace valid attrs with an optimized regex""<commit_after>// @flow
/* eslint-disable max-len */
/**
 * Trying to avoid the unknown-prop errors on styled components by filtering by
 * React's attribute whitelist.
 *
 * Regenerate the regex with: https://github.com/devongovett/regexgen
 **/
/*
 children  dangerouslySetInnerHTML  key  ref  autoFocus  defaultValue  valueLink  defaultChecked  checkedLink  innerHTML  suppressContentEditableWarning  onFocusIn  onFocusOut  className  onCopy  onCut  onPaste  onCompositionEnd  onCompositionStart  onCompositionUpdate  onKeyDown  onKeyPress  onKeyUp  onFocus  onBlur  onChange  onInput  onSubmit  onReset  onClick  onContextMenu  onDoubleClick  onDrag  onDragEnd  onDragEnter  onDragExit  onDragLeave  onDragOver  onDragStart  onDrop  onMouseDown  onMouseEnter  onMouseLeave  onMouseMove  onMouseOut  onMouseOver  onMouseUp  onSelect  onTouchCancel  onTouchEnd  onTouchMove  onTouchStart  onScroll  onWheel  onAbort  onCanPlay  onCanPlayThrough  onDurationChange  onEmptied  onEncrypted  onEnded  onError  onLoadedData  onLoadedMetadata  onLoadStart  onPause  onPlay  onPlaying  onProgress  onRateChange  onSeeked  onSeeking  onStalled  onSuspend  onTimeUpdate  onVolumeChange  onWaiting  onLoad  onAnimationStart  onAnimationEnd  onAnimationIteration  onTransitionEnd  onCopyCapture  onCutCapture  onPasteCapture  onCompositionEndCapture  onCompositionStartCapture  onCompositionUpdateCapture  onKeyDownCapture  onKeyPressCapture  onKeyUpCapture  onFocusCapture  onBlurCapture  onChangeCapture  onInputCapture  onSubmitCapture  onResetCapture  onClickCapture  onContextMenuCapture  onDoubleClickCapture  onDragCapture  onDragEndCapture  onDragEnterCapture  onDragExitCapture  onDragLeaveCapture  onDragOverCapture  onDragStartCapture  onDropCapture  onMouseDownCapture  onMouseEnterCapture  onMouseLeaveCapture  onMouseMoveCapture  onMouseOutCapture  onMouseOverCapture  onMouseUpCapture  onSelectCapture  onTouchCancelCapture  onTouchEndCapture  onTouchMoveCapture  onTouchStartCapture  onScrollCapture  onWheelCapture  onAbortCapture  onCanPlayCapture  onCanPlayThroughCapture  onDurationChangeCapture  onEmptiedCapture  onEncryptedCapture  onEndedCapture  onErrorCapture  onLoadedDataCapture  onLoadedMetadataCapture  onLoadStartCapture  onPauseCapture  onPlayCapture  onPlayingCapture  onProgressCapture  onRateChangeCapture  onSeekedCapture  onSeekingCapture  onStalledCapture  onSuspendCapture  onTimeUpdateCapture  onVolumeChangeCapture  onWaitingCapture  onLoadCapture  onAnimationStartCapture  onAnimationEndCapture  onAnimationIterationCapture  onTransitionEndCapture  accept  acceptCharset  accessKey  action  allowFullScreen  allowTransparency  alt  as  async  autoComplete  autoPlay  capture  cellPadding  cellSpacing  charSet  challenge  checked  cite  classID  className  cols  colSpan  content  contentEditable  contextMenu  controls  coords  crossOrigin  data  dateTime  default  defer  dir  disabled  download  draggable  encType  form  formAction  formEncType  formMethod  formNoValidate  formTarget  frameBorder  headers  height  hidden  high  href  hrefLang  htmlFor  httpEquiv  icon  id  inputMode  integrity  is  keyParams  keyType  kind  label  lang  list  loop  low  manifest  marginHeight  marginWidth  max  maxLength  media  mediaGroup  method  min  minLength  multiple  muted  name  nonce  noValidate  open  optimum  pattern  placeholder  playsInline  poster  preload  profile  radioGroup  readOnly  referrerPolicy  rel  required  reversed  role  rows  rowSpan  sandbox  scope  scoped  scrolling  seamless  selected  shape  size  sizes  span  spellCheck  src  srcDoc  srcLang  srcSet  start  step  style  summary  tabIndex  target  title  type  useMap  value  width  wmode  wrap  about  datatype  inlist  prefix  property  resource  typeof  vocab  autoCapitalize  autoCorrect  autoSave  color  itemProp  itemScope  itemType  itemID  itemRef  results  security  unselectable  accentHeight  accumulate  additive  alignmentBaseline  allowReorder  alphabetic  amplitude  arabicForm  ascent  attributeName  attributeType  autoReverse  azimuth  baseFrequency  baseProfile  baselineShift  bbox  begin  bias  by  calcMode  capHeight  clip  clipPath  clipRule  clipPathUnits  colorInterpolation  colorInterpolationFilters  colorProfile  colorRendering  contentScriptType  contentStyleType  cursor  cx  cy  d  decelerate  descent  diffuseConstant  direction  display  divisor  dominantBaseline  dur  dx  dy  edgeMode  elevation  enableBackground  end  exponent  externalResourcesRequired  fill  fillOpacity  fillRule  filter  filterRes  filterUnits  floodColor  floodOpacity  focusable  fontFamily  fontSize  fontSizeAdjust  fontStretch  fontStyle  fontVariant  fontWeight  format  from  fx  fy  g1  g2  glyphName  glyphOrientationHorizontal  glyphOrientationVertical  glyphRef  gradientTransform  gradientUnits  hanging  horizAdvX  horizOriginX  ideographic  imageRendering  in  in2  intercept  k  k1  k2  k3  k4  kernelMatrix  kernelUnitLength  kerning  keyPoints  keySplines  keyTimes  lengthAdjust  letterSpacing  lightingColor  limitingConeAngle  local  markerEnd  markerMid  markerStart  markerHeight  markerUnits  markerWidth  mask  maskContentUnits  maskUnits  mathematical  mode  numOctaves  offset  opacity  operator  order  orient  orientation  origin  overflow  overlinePosition  overlineThickness  paintOrder  panose1  pathLength  patternContentUnits  patternTransform  patternUnits  pointerEvents  points  pointsAtX  pointsAtY  pointsAtZ  preserveAlpha  preserveAspectRatio  primitiveUnits  r  radius  refX  refY  renderingIntent  repeatCount  repeatDur  requiredExtensions  requiredFeatures  restart  result  rotate  rx  ry  scale  seed  shapeRendering  slope  spacing  specularConstant  specularExponent  speed  spreadMethod  startOffset  stdDeviation  stemh  stemv  stitchTiles  stopColor  stopOpacity  strikethroughPosition  strikethroughThickness  string  stroke  strokeDasharray  strokeDashoffset  strokeLinecap  strokeLinejoin  strokeMiterlimit  strokeOpacity  strokeWidth  surfaceScale  systemLanguage  tableValues  targetX  targetY  textAnchor  textDecoration  textRendering  textLength  to  transform  u1  u2  underlinePosition  underlineThickness  unicode  unicodeBidi  unicodeRange  unitsPerEm  vAlphabetic  vHanging  vIdeographic  vMathematical  values  vectorEffect  version  vertAdvY  vertOriginX  vertOriginY  viewBox  viewTarget  visibility  widths  wordSpacing  writingMode  x  xHeight  x1  x2  xChannelSelector  xlinkActuate  xlinkArcrole  xlinkHref  xlinkRole  xlinkShow  xlinkTitle  xlinkType  xmlBase  xmlns  xmlnsXlink  xmlLang  xmlSpace  y  y1  y2  yChannelSelector  z  zoomAndPan
*/
/* eslint-enable max-len */

const ATTRIBUTE_REGEX = /(?:s(?:uppressContentEditableWarn|croll|pac)|(?:shape|image|text)Render|(?:letter|word)Spac|vHang|hang)ing|(?:on(?:AnimationIteration|C(?:o(?:mposition(?:Update|Start|End)|ntextMenu|py)|anPlayThrough|anPlay|hange|lick|ut)|(?:(?:Duration|Volume|Rate)Chang|(?:MouseLea|(?:Touch|Mouse)Mo|DragLea)v|Paus)e|Loaded(?:Metad|D)ata|(?:Animation|Touch|Load|Drag)Start|(?:(?:T(?:ransition|ouch)|Animation)E|Suspe)nd|DoubleClick|(?:TouchCanc|Whe)el|(?:Mouse(?:Ent|Ov)e|Drag(?:Ent|Ov)e|Erro)r|TimeUpdate|(?:E(?:n(?:crypt|d)|mpti)|S(?:tall|eek))ed|MouseDown|P(?:rogress|laying)|(?:MouseOu|DragExi|S(?:elec|ubmi)|Rese|Inpu)t|KeyPress|DragEnd|Key(?:Down|Up)|(?:Wait|Seek)ing|(?:MouseU|Dro)p|Scroll|Paste|Focus|Abort|Drag|Play|Load|Blur)Captur|alignmentBaselin|(?:limitingConeAng|xlink(?:(?:Arcr|R)o|Tit)|s(?:urfaceSca|ty|ca)|unselectab|baseProfi|fontSty|(?:focus|dragg)ab|multip|profi|tit)l|d(?:ominantBaselin|efaultValu)|a(?:uto(?:Capitaliz|Revers|Sav)|dditiv)|(?:(?:formNoValid|xlinkActu|noValid|accumul|rot)a|autoComple|decelera)t|(?:(?:attribute|item)T|datat)yp|(?:attribute|glyph)Nam|playsInlin|(?:formE|e)ncTyp|(?:writing|input|edge)Mod|(?:xlinkTy|itemSco|keyTy|slo)p|(?:amplitu|mo)d|(?:xmlSpa|non)c|fillRul|(?:dateTi|na)m|r(?:esourc|ol)|xmlBas|wmod)e|(?:glyphOrientationHorizont|loc)al|(?:externalResourcesRequir|select|revers|mut)ed|c(?:o(?:lorInterpolationFilter|ntrol|ord)s|o(?:lor(?:Interpolation)?|ntent)|(?:ontentS(?:cript|tyle)Typ|o(?:ntentEditab|lorProfi)l|l(?:assNam|ipRul)|a(?:lcMod|ptur)|it)e|olorRendering|l(?:ipPathUnits|assID)|o(?:ntextMenu|ls)|h(?:eckedLink|a(?:llenge|rSet)|ildren|ecked)|ell(?:Spac|Padd)ing|(?:rossOrigi|olSpa)n|apHeight|lip(?:Path)?|ursor|[xy])|glyphOrientationVertical|d(?:angerouslySetInnerHTML|efaultChecked|ownload|isabled|isplay|[xy])|(?:s(?:trikethroughThickn|eaml)es|(?:und|ov)erlineThicknes|r(?:equiredExtension|adiu)|(?:requiredFeatur|tableValu|stitchTil|numOctav|filterR)e|key(?:(?:Splin|Tim)e|Param)|autoFocu|header|bia)s|(?:(?:st(?:rikethroughPosi|dDevia)|(?:und|ov)erlinePosi|(?:textDecor|elev)a|orienta)tio|(?:strokeLinejo|orig)i|formActio|zoomAndPa|onFocusI|directio|(?:vers|act)io|rowSpa|begi|ico)n|o(?:n(?:AnimationIteration|C(?:o(?:mposition(?:Update|Start|End)|ntextMenu|py)|anPlayThrough|anPlay|hange|lick|ut)|(?:(?:Duration|Volume|Rate)Chang|(?:MouseLea|(?:Touch|Mouse)Mo|DragLea)v|Paus)e|Loaded(?:Metad|D)ata|(?:Animation|Touch|Load|Drag)Start|(?:(?:T(?:ransition|ouch)|Animation)E|Suspe)nd|DoubleClick|(?:TouchCanc|Whe)el|(?:Mouse(?:Ent|Ov)e|Drag(?:Ent|Ov)e|Erro)r|TimeUpdate|(?:E(?:n(?:crypt|d)|mpti)|S(?:tall|eek))ed|MouseDown|P(?:rogress|laying)|(?:MouseOu|DragExi|S(?:elec|ubmi)|Rese|Inpu)t|KeyPress|DragEnd|Key(?:Down|Up)|(?:Wait|Seek)ing|(?:MouseU|Dro)p|Scroll|Paste|Focus|Abort|Drag|Play|Load|Blur)|rient)|p(?:reserveA(?:spectRatio|lpha)|ointsAt[X-Z]|anose1)|(?:patternContent|ma(?:sk(?:Content)?|rker)|primitive|gradient|pattern|filter)Units|(?:gradientT|patternT|t)ransform|(?:(?:allowTranspar|baseFrequ)enc|re(?:ferrerPolic|adOnl)|(?:(?:st(?:roke|op)O|floodO|fillO|o)pac|integr|secur)it|visibilit|fontFamil|accessKe|propert|summar)y|(?:strokeMiterlimi|(?:specularConsta|repeatCou|fontVaria)n|(?:(?:specularE|e)xpon|renderingInt|asc)en|d(?:iffuseConsta|esce)n|(?:fontSizeAdju|lengthAdju|manife)s|baselineShif|vectorEffec|(?:(?:mar(?:ker|gin)|x)H|accentH|fontW)eigh|a(?:utoCorrec|bou)|markerStar|onFocusOu|in(?:tercep|lis)|restar|forma|heigh|lis)t|(?:(?:st(?:rokeDasho|artO)|o)ffs|acceptChars|formTarg|viewTarg|srcS)et|(?:(?:enableBackgrou|markerE)n|s(?:p(?:readMetho|ee)|ee)|formMetho|m(?:arkerMi|etho)|preloa|kin)d|k(?:ernel(?:UnitLength|Matrix)|[1-4])|(?:[xy]ChannelSelect|lightingCol|textAnch|floodCol|stopCol|operat|htmlF)or|(?:allowFullScre|hidd)en|strokeDasharray|systemLanguage|(?:strokeLineca|itemPro|useMa|wra|loo)p|v(?:Mathematical|ert(?:Origin[XY]|AdvY)|alues|ocab)|(?:pointerEve|keyPoi)nts|unicodeRange|(?:(?:allowReord|placehold|frameBord|paintOrd|post|ord)e|repeatDu|d(?:efe|u))r|mathematical|(?:vI|i)deographic|h(?:oriz(?:Origin|Adv)X|ttpEquiv)|u(?:nicodeBidi|[12])|(?:fontStretc|hig)h|(?:(?:mar(?:ker|gin)W|strokeW)id|azimu)th|vAlphabetic|mediaGroup|spellCheck|(?:unitsPerE|optimu|fro)m|r(?:adioGroup|e(?:sults|f[XY]|l)|ows|[xy])|(?:xmlnsXl|valueL)ink|a(?:rabicForm|l(?:phabetic|t)|sync)|pathLength|(?:text|m(?:in|ax))Length|innerHTML|xlinkShow|(?:xlinkHr|glyphR)ef|r(?:e(?:quired|sult|f))?|o(?:verflow|pen)|(?:tabInde|(?:sand|b)bo|viewBo)x|(?:(?:href|xml|src)La|kerni)ng|f(?:o(?:ntSize|rm)|il(?:ter|l))|autoPlay|unicode|p(?:attern|oints)|t(?:arget[XY]|o)|i(?:temRef|n2|s)|divisor|d(?:efault|ata|ir)?|srcDoc|s(?:coped|te(?:m[hv]|p)|pan)|(?:width|size)s|(?:stri|la)ng|prefix|itemID|s(?:t(?:roke|art)|hape|cope|rc)|a(?:ccept|s)|t(?:arget|ype)|typeof|width|value|x(?:mlns)?|label|m(?:edia|a(?:sk|x)|in)|size|href|k(?:ey)?|end|low|x[12]|i[dn]|y[12]|g[12]|by|f[xy]|[yz]/

/* From DOMProperty */
const ATTRIBUTE_NAME_START_CHAR =
  ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'
const ATTRIBUTE_NAME_CHAR = `${ATTRIBUTE_NAME_START_CHAR}\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040`
const isCustomAttribute = RegExp.prototype.test.bind(
  new RegExp(`^(data|aria)-[${ATTRIBUTE_NAME_CHAR}]*$`),
)

export default (name: string) =>
  name.search(ATTRIBUTE_REGEX) !== -1 || isCustomAttribute(name.toLowerCase())
<|endoftext|>


<commit_before>"use strict";

var Grid = function(w,h) {
  return {
    width:  function() { return w; },
    height: function() { return h; }
  };
};

exports.Grid = Grid;
<commit_msg>tidy up exports, still failing<commit_after>"use strict";

var On  = 1;
var Off = 0;

var Grid = function(w,h) {
  return {
    width:  function() { return w; },
    height: function() { return h; }
  };
};

exports.Grid = Grid;
exports.On = On;
exports.Off = Off;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview The class representing a cursor.
 * Used primarily for keyboard navigation.
 * @author aschmiedt@google.com (Abby Schmiedt)
 */
'use strict';

goog.module('Blockly.Cursor');
goog.module.declareLegacyNamespace();

goog.require('Blockly.ASTNode');
goog.require('Blockly.Marker');
goog.require('Blockly.registry');
goog.require('Blockly.utils.object');

/**
 * Class for a cursor.
 * A cursor controls how a user navigates the Blockly AST.
 * @constructor
 * @extends {Blockly.Marker}
 */
const Cursor = function() {
  Cursor.superClass_.constructor.call(this);

  /**
   * @override
   */
  this.type = 'cursor';
};
Blockly.utils.object.inherits(Cursor, Blockly.Marker);

/**
 * Find the next connection, field, or block.
 * @return {Blockly.ASTNode} The next element, or null if the current node is
 *     not set or there is no next value.
 * @public
 */
Cursor.prototype.next = function() {
  const curNode = this.getCurNode();
  if (!curNode) {
    return null;
  }

  let newNode = curNode.next();
  while (newNode && newNode.next() &&
         (newNode.getType() == Blockly.ASTNode.types.NEXT ||
          newNode.getType() == Blockly.ASTNode.types.BLOCK)) {
    newNode = newNode.next();
  }

  if (newNode) {
    this.setCurNode(newNode);
  }
  return newNode;
};

/**
 * Find the in connection or field.
 * @return {Blockly.ASTNode} The in element, or null if the current node is
 *     not set or there is no in value.
 * @public
 */
Cursor.prototype.in = function() {
  let curNode = this.getCurNode();
  if (!curNode) {
    return null;
  }
  // If we are on a previous or output connection, go to the block level before
  // performing next operation.
  if (curNode.getType() == Blockly.ASTNode.types.PREVIOUS ||
      curNode.getType() == Blockly.ASTNode.types.OUTPUT) {
    curNode = curNode.next();
  }
  const newNode = curNode.in();

  if (newNode) {
    this.setCurNode(newNode);
  }
  return newNode;
};

/**
 * Find the previous connection, field, or block.
 * @return {Blockly.ASTNode} The previous element, or null if the current node
 *     is not set or there is no previous value.
 * @public
 */
Cursor.prototype.prev = function() {
  const curNode = this.getCurNode();
  if (!curNode) {
    return null;
  }
  let newNode = curNode.prev();

  while (newNode && newNode.prev() &&
         (newNode.getType() == Blockly.ASTNode.types.NEXT ||
          newNode.getType() == Blockly.ASTNode.types.BLOCK)) {
    newNode = newNode.prev();
  }

  if (newNode) {
    this.setCurNode(newNode);
  }
  return newNode;
};

/**
 * Find the out connection, field, or block.
 * @return {Blockly.ASTNode} The out element, or null if the current node is
 *     not set or there is no out value.
 * @public
 */
Cursor.prototype.out = function() {
  const curNode = this.getCurNode();
  if (!curNode) {
    return null;
  }
  let newNode = curNode.out();

  if (newNode && newNode.getType() == Blockly.ASTNode.types.BLOCK) {
    newNode = newNode.prev() || newNode;
  }

  if (newNode) {
    this.setCurNode(newNode);
  }
  return newNode;
};

Blockly.registry.register(
    Blockly.registry.Type.CURSOR, Blockly.registry.DEFAULT, Cursor);

exports = Cursor;
<commit_msg>Migrate core/keyboard_nav/cursor.js named requires<commit_after>/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview The class representing a cursor.
 * Used primarily for keyboard navigation.
 * @author aschmiedt@google.com (Abby Schmiedt)
 */
'use strict';

goog.module('Blockly.Cursor');
goog.module.declareLegacyNamespace();

const ASTNode = goog.require('Blockly.ASTNode');
const Marker = goog.require('Blockly.Marker');
const {DEFAULT, register, Type} = goog.require('Blockly.registry');
const {inherits} = goog.require('Blockly.utils.object');

/**
 * Class for a cursor.
 * A cursor controls how a user navigates the Blockly AST.
 * @constructor
 * @extends {Marker}
 */
const Cursor = function() {
  Cursor.superClass_.constructor.call(this);

  /**
   * @override
   */
  this.type = 'cursor';
};
inherits(Cursor, Marker);

/**
 * Find the next connection, field, or block.
 * @return {ASTNode} The next element, or null if the current node is
 *     not set or there is no next value.
 * @public
 */
Cursor.prototype.next = function() {
  const curNode = this.getCurNode();
  if (!curNode) {
    return null;
  }

  let newNode = curNode.next();
  while (newNode && newNode.next() &&
         (newNode.getType() == ASTNode.types.NEXT ||
          newNode.getType() == ASTNode.types.BLOCK)) {
    newNode = newNode.next();
  }

  if (newNode) {
    this.setCurNode(newNode);
  }
  return newNode;
};

/**
 * Find the in connection or field.
 * @return {ASTNode} The in element, or null if the current node is
 *     not set or there is no in value.
 * @public
 */
Cursor.prototype.in = function() {
  let curNode = this.getCurNode();
  if (!curNode) {
    return null;
  }
  // If we are on a previous or output connection, go to the block level before
  // performing next operation.
  if (curNode.getType() == ASTNode.types.PREVIOUS ||
      curNode.getType() == ASTNode.types.OUTPUT) {
    curNode = curNode.next();
  }
  const newNode = curNode.in();

  if (newNode) {
    this.setCurNode(newNode);
  }
  return newNode;
};

/**
 * Find the previous connection, field, or block.
 * @return {ASTNode} The previous element, or null if the current node
 *     is not set or there is no previous value.
 * @public
 */
Cursor.prototype.prev = function() {
  const curNode = this.getCurNode();
  if (!curNode) {
    return null;
  }
  let newNode = curNode.prev();

  while (newNode && newNode.prev() &&
         (newNode.getType() == ASTNode.types.NEXT ||
          newNode.getType() == ASTNode.types.BLOCK)) {
    newNode = newNode.prev();
  }

  if (newNode) {
    this.setCurNode(newNode);
  }
  return newNode;
};

/**
 * Find the out connection, field, or block.
 * @return {ASTNode} The out element, or null if the current node is
 *     not set or there is no out value.
 * @public
 */
Cursor.prototype.out = function() {
  const curNode = this.getCurNode();
  if (!curNode) {
    return null;
  }
  let newNode = curNode.out();

  if (newNode && newNode.getType() == ASTNode.types.BLOCK) {
    newNode = newNode.prev() || newNode;
  }

  if (newNode) {
    this.setCurNode(newNode);
  }
  return newNode;
};

register(Type.CURSOR, DEFAULT, Cursor);

exports = Cursor;
<|endoftext|>


<commit_before>/**
 canvas.js
 Copyright (c) 2014 NTT DOCOMO,INC.
 Released under the MIT license
 http://opensource.org/licenses/mit-license.php
 */

var currentPath = '/';
var deleteMode;

/**
 * Canvasプロファイルのメニューを表示する.
 *
 * @param {String} serviceId サービスID
 */
function showCanvas(serviceId) {
  initAll();
  setTitle('Canvas Profile', 'black');

  var btnStr = getBackButton('Device Top', 'doCanvasBack', serviceId, '');
  reloadHeader(btnStr);
  reloadFooter(btnStr);

  var str = '
Canvas DrawImage
';
  reloadList(str);
}

/**
 * Backボタン
 *
 * @param {String} serviceId サービスID
 * @param {String} sessionKey セッションKEY
 */
function doCanvasBack(serviceId, sessionKey) {
  searchDevice(serviceId);
}

/**
 * Backボタン
 *
 * @param {String} serviceId サービスID
 * @param {String} sessionKey セッションKEY
 */
function doCanvasDrawImageBack(serviceId, sessionKey) {
  showCanvas(serviceId);
}

/**
 * ファイル送信フォームを表示する.
 *
 * @param {String} serviceId　サービスID
 */
function showCanvasDrawImage(serviceId) {
  initAll();
  setTitle('Canvas Profile(DrawImage)');

  var btnStr = getBackButton('Canvas Top', 'doCanvasDrawImageBack',
                  serviceId, '');
  reloadHeader(btnStr);
  reloadFooter(btnStr);

  var builder = new dConnect.URIBuilder();
  builder.setProfile('canvas');
  builder.setAttribute('drawimage');
  var uri = builder.build();

  if (DEBUG) {
    console.log('Uri: ' + uri);
  }

  /* ※省略パラメータがあり1種類のformでは対応できないため2つformを用意しています。 */

  var str = '';

  str += '<form action="' + uri + '" method="POST"' +
          ' enctype="multipart/form-data" id="fileForm">
';
  str += '<input type="hidden" name="serviceId" value="' + serviceId + '"/>';
  str += '<input type="hidden" name="accessToken" value="' +
          accessToken + '"/>';

  str += makeInputText('path', 'path', 'path');
  str += makeInputText('uri', 'uri', 'uri');
  str += '<input type="file" name="data" id="data"/>';

  str += 'mode:';
  str += '<SELECT name="mode" id="mode">';
  str += '<OPTION value="">等倍配置モード</OPTION>';
  str += '<OPTION value="scales">最大化して画像描画</OPTION>';
  str += '<OPTION value="fills">等倍画像を敷き詰めて描画</OPTION>';
  str += '</SELECT>';

  str += 'x:';
  str += '<input type="text" name="x" value="0"/>';
  str += 'y:';
  str += '<input type="text" name="y" value="0"/>';
  str += '<input type="button" name="sendButton" ' +
          'id="sendButton" value="Upload" onclick="doCanvasDrawImage(\'' +
          serviceId + '\', \'fileForm\');"/>';
  str += '<input type="button" name="sendDeleteButton"' +
          ' id="sendDeleteButton" value="Delete"' +
          ' onclick="doDeleteCanvasDrawImage(\'' + serviceId + '\');"/>';
  str += '</form>';
  reloadContent(str);

  $('#data').change(
      function() {
        if (!this.files.length) {
          alert('File is null');
          return;
        } else {
          var file = '/' + this.files[0].name;
          $('#path').val(file);
        }
      }
  );
}

/**
 * 画像描画処理.
 *
 *  @param {String} serviceId サービスID
 *  @param {String} fileFormId ファイルフォームID
 */
function doCanvasDrawImage(serviceId, fileFormId) {
  closeLoading();
  showLoading();

  var myForm = document.getElementById(fileFormId);
  var myFormData = new FormData(myForm);
  var myXhr = new XMLHttpRequest();

  myXhr.open(myForm.method, myForm.action, true);
  myXhr.onreadystatechange = function() {
    if (myXhr.readyState === 4) {
      if (myXhr.status === 200 || myXhr.status == 0) {
        if (DEBUG) {
          console.log('Response:' + myXhr.responseText)
        }
        var str = '';
        var obj = JSON.parse(myXhr.responseText);
        if (obj.result == 0) {
          //alert('success:canvas/drawimage');
          $('#path').val('');
          $('#data').val('');
        } else {
          showError('POST canvas/drawimage', obj.errorCode, obj.errorMessage);
        }
      } else {
        alert('error:' + myXhr.status);
      }
      closeLoading();
    }
  };
  myXhr.send(myFormData);
}

/**
 * 画像削除処理.
 *
 *  @param {String} serviceId サービスID
 *  @param {String} fileFormId ファイルフォームID
 */
function doDeleteCanvasDrawImage(serviceId) {
  closeLoading();
  showLoading();

  var builder = new dConnect.URIBuilder();
  builder.setProfile('canvas');
  builder.setAttribute('drawimage');
  builder.setServiceId(serviceId);
  builder.setAccessToken(accessToken);
  var uri = builder.build();

  if (DEBUG) {
    console.log('Uri:' + uri);
  }

  dConnect.delete(uri, null, function(json) {
    closeLoading();
    if (DEBUG) {
      console.log('Response: ', json);
    }
  }, function(errorCode, errorMessage) {
    closeLoading();
    showError('DELETE canvas/drawimage', errorCode, errorMessage);
  });
}
<commit_msg>Swaggerの仕様に合わせ、値のないパラメータは送らないようにした<commit_after>/**
 canvas.js
 Copyright (c) 2014 NTT DOCOMO,INC.
 Released under the MIT license
 http://opensource.org/licenses/mit-license.php
 */

var currentPath = '/';
var deleteMode;

/**
 * Canvasプロファイルのメニューを表示する.
 *
 * @param {String} serviceId サービスID
 */
function showCanvas(serviceId) {
  initAll();
  setTitle('Canvas Profile', 'black');

  var btnStr = getBackButton('Device Top', 'doCanvasBack', serviceId, '');
  reloadHeader(btnStr);
  reloadFooter(btnStr);

  var str = '
Canvas DrawImage
';
  reloadList(str);
}

/**
 * Backボタン
 *
 * @param {String} serviceId サービスID
 * @param {String} sessionKey セッションKEY
 */
function doCanvasBack(serviceId, sessionKey) {
  searchDevice(serviceId);
}

/**
 * Backボタン
 *
 * @param {String} serviceId サービスID
 * @param {String} sessionKey セッションKEY
 */
function doCanvasDrawImageBack(serviceId, sessionKey) {
  showCanvas(serviceId);
}

/**
 * ファイル送信フォームを表示する.
 *
 * @param {String} serviceId　サービスID
 */
function showCanvasDrawImage(serviceId) {
  initAll();
  setTitle('Canvas Profile(DrawImage)');

  var btnStr = getBackButton('Canvas Top', 'doCanvasDrawImageBack',
                  serviceId, '');
  reloadHeader(btnStr);
  reloadFooter(btnStr);

  var builder = new dConnect.URIBuilder();
  builder.setProfile('canvas');
  builder.setAttribute('drawimage');
  var uri = builder.build();

  if (DEBUG) {
    console.log('Uri: ' + uri);
  }

  /* ※省略パラメータがあり1種類のformでは対応できないため2つformを用意しています。 */

  var str = '';

  str += '<form action="' + uri + '" method="POST"' +
          ' enctype="multipart/form-data" id="fileForm">
';
  str += '<input type="hidden" name="serviceId" value="' + serviceId + '"/>';
  str += '<input type="hidden" name="accessToken" value="' +
          accessToken + '"/>';

  str += makeInputText('path', 'path', 'path');
  str += makeInputText('uri', 'uri', 'uri');
  str += '<input type="file" name="data" id="data"/>';

  str += 'mode:';
  str += '<SELECT name="mode" id="mode">';
  str += '<OPTION value="">等倍配置モード</OPTION>';
  str += '<OPTION value="scales">最大化して画像描画</OPTION>';
  str += '<OPTION value="fills">等倍画像を敷き詰めて描画</OPTION>';
  str += '</SELECT>';

  str += 'x:';
  str += '<input type="text" name="x" value="0"/>';
  str += 'y:';
  str += '<input type="text" name="y" value="0"/>';
  str += '<input type="button" name="sendButton" ' +
          'id="sendButton" value="Upload" onclick="doCanvasDrawImage(\'' +
          serviceId + '\', \'fileForm\');"/>';
  str += '<input type="button" name="sendDeleteButton"' +
          ' id="sendDeleteButton" value="Delete"' +
          ' onclick="doDeleteCanvasDrawImage(\'' + serviceId + '\');"/>';
  str += '</form>';
  reloadContent(str);

  $('#data').change(
      function() {
        if (!this.files.length) {
          alert('File is null');
          return;
        } else {
          var file = '/' + this.files[0].name;
          $('#path').val(file);
        }
      }
  );
}

/**
 * 画像描画処理.
 *
 *  @param {String} serviceId サービスID
 *  @param {String} fileFormId ファイルフォームID
 */
function doCanvasDrawImage(serviceId, fileFormId) {
  closeLoading();
  showLoading();

  var myForm = document.getElementById(fileFormId);
  var myFormData = new FormData(myForm);
  var myXhr = new XMLHttpRequest();
  if (!myFormData.get('mode')) {
    myFormData.delete('mode');
  }
  myXhr.open(myForm.method, myForm.action, true);
  myXhr.onreadystatechange = function() {
    if (myXhr.readyState === 4) {
      if (myXhr.status === 200 || myXhr.status == 0) {
        if (DEBUG) {
          console.log('Response:' + myXhr.responseText)
        }
        var str = '';
        var obj = JSON.parse(myXhr.responseText);
        if (obj.result == 0) {
          //alert('success:canvas/drawimage');
          $('#path').val('');
          $('#data').val('');
        } else {
          showError('POST canvas/drawimage', obj.errorCode, obj.errorMessage);
        }
      } else {
        alert('error:' + myXhr.status);
      }
      closeLoading();
    }
  };
  myXhr.send(myFormData);
}

/**
 * 画像削除処理.
 *
 *  @param {String} serviceId サービスID
 *  @param {String} fileFormId ファイルフォームID
 */
function doDeleteCanvasDrawImage(serviceId) {
  closeLoading();
  showLoading();

  var builder = new dConnect.URIBuilder();
  builder.setProfile('canvas');
  builder.setAttribute('drawimage');
  builder.setServiceId(serviceId);
  builder.setAccessToken(accessToken);
  var uri = builder.build();

  if (DEBUG) {
    console.log('Uri:' + uri);
  }

  dConnect.delete(uri, null, function(json) {
    closeLoading();
    if (DEBUG) {
      console.log('Response: ', json);
    }
  }, function(errorCode, errorMessage) {
    closeLoading();
    showError('DELETE canvas/drawimage', errorCode, errorMessage);
  });
}
<|endoftext|>


<commit_before>var path = require('path'),
    fs = require('fs'),
    External = require('./external'),
    Step = require('step'),
    _ = require('underscore')._,
    sys = require('sys'),
    mess = require('mess');

require.paths.unshift(path.join(__dirname, '..', 'lib'));

/**
 * Rendering circuitry for JSON map manifests.
 *
 * This is node-only for the time being.
 */

/**
 * Convert a two-element-per-item Array
 * into an object, for the purpose of checking membership
 * and replacing stuff.
 * @param {Array} list a list.
 */
var to = function(list) {
    return list && list[0] && _.reduce(list, function(m, r) {
        if (r && r.length > 1) {
          m[r[0]] = r[1];
        }
        return m;
    }, {});
};

mess.Renderer = function Renderer(env) {
    var env = {
        data_dir: env.data_dir || '/tmp/',
        local_data_dir: env.local_data_dir || '',
        validation_data: env.validation_data || false
    };
    return {
        /**
         * Keep a copy of passed-in environment variables
         */
        env: env,
        /**
         * Wrapper for downloading externals: likely removable
         *
         * @param {String} uri the URI of the resource.
         * @param {Function} callback
         */
        grab: function(uri, callback) {
            new(External)(this.env).process(uri, callback);
        },

        /**
         * Download any file-based remote datsources.
         *
         * Usable as an entry point: does not expect any modification to
         * the map object beyond JSON parsing.
         *
         * @param {Object} m map object.
         * @param {Function} callback
         */
        localizeExternals: function(m, callback) {
            var that = this;
            Step(
                function() {
                    var group = this.group();
                    m.Layer.forEach(function(l) {
                        if (l.Datasource.file) {
                            that.grab(l.Datasource.file, group());
                        }
                    });
                    if (m.Layer.length == 0) group()();
                },
                function(err, results) {
                    var result_map = to(results);
                    m.Layer = _.map(_.filter(m.Layer,
                            function(l) {
                                return l.Datasource.file &&
                                    result_map[l.Datasource.file];
                            }),
                            function(l) {
                                l.Datasource.file = result_map[l.Datasource.file];
                                return l;
                            }
                    );
                    callback(err, m);
                }
            );
        },

        /**
         * Download any remote stylesheets
         *
         * @param {Object} m map object.
         * @param {Function} callback
         */
        localizeStyle: function(m, callback) {
            var that = this;
            Step(
                function() {
                    var group = this.group();
                    m.Stylesheet.forEach(function(s) {
                        if (!s.id) {
                            that.grab(s, group());
                        }
                    });
                    group()();
                },
                function(err, results) {
                    var result_map = to(results);
                    for (s in m.Stylesheet) {
                        if (!m.Stylesheet[s].id) {
                            m.Stylesheet[s] = result_map[m.Stylesheet[s]];
                        }
                    }
                    callback(err, m);
                }
            );
        },

        /**
         * Compile (already downloaded) styles with mess.js,
         * calling callback with an array of [map object, [stylesheet objects]]
         *
         * Called with the results of localizeStyle or localizeExternals:
         * expects not to handle downloading.
         *
         * @param {Object} m map object.
         * @param {Function} callback
         */
        style: function(m, callback) {
            var that = this;
            Step(
                function() {
                    var group = this.group();
                    m.Stylesheet.forEach(function(s) {
                        if (s.id) {
                            group()(null, [s.id, s.data]);
                        } else {
                            fs.readFile(s, 'utf-8', function(err, data) {
                                group()(err, [s, data]);
                            });
                        }
                    });
                },
                function(e, results) {
                    var options = {},
                        group = this.group();
                    for (var i = 0, l = results.length; i < l; i++) {
                        new(mess.Parser)(_.extend(_.extend({
                            filename: s
                        }, that.env), this.env)).parse(results[i][1], function(err, tree) {
                            if (err) {
                                mess.writeError(err, options);
                                throw err;
                            } else {
                                try {
                                    group()(err, [
                                        results[i][0],
                                        tree.toCSS({ compress: false }),
                                        tree]);
                                    return;
                                } catch (e) {
                                    throw e;
                                    return;
                                }
                            }
                        });
                    }
                },
                function(err, results) {
                    if (err) {
                        callback(err);
                        return;
                    }

                    var result_map = to(results);
                    for (s in m.Stylesheet) {
                        if (!m.Stylesheet[s].id) {
                            m.Stylesheet[s] = result_map[m.Stylesheet[s]];
                        } else {
                            m.Stylesheet[s] = result_map[m.Stylesheet[s].id];
                        }
                    }
                    callback(err, [m, results]);
                }
            );
        },

        /**
         * Prepare full XML map output. Called with the results
         * of this.style
         *
         * @param {Array} res array of [map object, stylesheets].
         * @param {Function} callback
         */
        template: function(err, res, callback) {
            if (err) {
                callback(err);
                return;
            }

            var m = res[0],
                stylesheets = res[1],

                entities = _.template('<?xml version="1.0" ' +
                    'encoding="utf-8"?>\n' +
                    '<!DOCTYPE Map[\n' +
                    '<% for (ref in externals) { %>' +
                    '  <!ENTITY <%= ref %> SYSTEM "<%= externals[ref] %>">\n' +
                    '<% } %>]>\n'),

                styles = _.template('<StyleName><%= name %></StyleName>'),

                layer = _.template('\n  <Layer\n   id="<%= id %>"\n' +
                    '   name="<%= name %>"\n' +
                    '   srs="<%= srs %>">\n' +
                    '<% for (s in styles) { %>' +
                    '    <StyleName><%= styles[s] %></StyleName>\n' +
                    '<% } %>' +
                    '    <Datasource>\n<% for (n in Datasource) { %>' +
                    '      <Parameter name="<%= n %>"><%= Datasource[n] %>' +
                    '</Parameter>\n' +
                    '<% } %>    </Datasource>\n' +
                    '  </Layer>\n'),

                stylesheet_tmpl = _.template('  <% for (i in Stylesheet) { %>' +
                    '<%= Stylesheet[i] %>\n' +
                    '<% } %>\n'),

                // referencing externals in the body of the map
                references = _.template('<% for (ref in externals) { %>' +
                    '&<%= ref %>;\n' +
                    '<% } %>'),

                // for the Map[] doctype: XML entities to
                // organize code
                entity_list = { externals: [], symbols: [] };

            /**
             * Index a hash of the CSS rules in all stylesheets
             * This is performance-critical: necessary to test
             * at some point
             *
             * @param {Array} stylesheets
             * @return {Array} list of selectors.
             */
            var ruleHash = function(stylesheets) {
                return _.flatten(_.map(stylesheets, function(s) {
                    return _.map(s[2].rules, function(r) {
                        if (r && r.selectors && r.selectors[0]._css) {
                            return r.selectors[0]._css;
                        }
                    });
                }));
            };

            var findBackground = function(stylesheets) {
                var b = '#FFFFFF';
                _.each(stylesheets, function(s) {
                    _.each(s[2].rules, function(r) {
                        if (r && r.selectors && r.selectors[0]._css &&
                            r.selectors[0]._css === 'Map') {
                            var bg = _.detect(r.rules, function(rule) {
                                return rule.name == 'background-color';
                            });
                            if (bg) {
                                b = bg.value.toCSS({ compress: false });
                            }
                        }
                    });
                });
                return b;
            };

            /**
             * Add styles to a layer object
             *
             * @param {Object} layer the layer object.
             * @param {Array} stylesheets the results of ruleHash().
             * @return Formalized layer definition with .styles = [].
             */
            var styleIntersect = function(layer, stylesheets) {
                var hash = ruleHash(stylesheets),
                    classes = _.map((layer['class'] || '').split(' '),
                        function(c) {
                            return 'class-' + c.trim();
                    }),
                    layer_id = 'id-' + layer.id;
                layer.styles = [];
                _.each(hash, function(h) {
                    if (h && (h.search(layer_id) != -1)) {
                        layer.styles.push(h);
                    }
                });

                _.each(hash, function(h) {
                    _.each(classes, function(c) {
                        if (h && (h.search(c) != -1)) {
                            layer.styles.push(c);
                        }
                    });
                });
                return layer;
            };

            var output = [entities(entity_list)];
            // TODO: must change when background colors are available
            output.push('<Map background-color="' +
                    findBackground(stylesheets)
                    + '" srs="+proj=merc +a=6378137 +b=6378137 '
                    + '+lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m '
                    + '+nadgrids=@null +no_defs">\n');
            // using array joins here: faster in IE7, unclear in general.
            m.Layer.forEach(function(l) {
                l = styleIntersect(l, stylesheets);
                output.push(layer(l));
            });
            output.push(references(entity_list));
            output.push(stylesheet_tmpl(m));
            output.push('</Map>');
            callback(null, output.join(''));
        },

        /**
         * Prepare a JML document (given as a string) into a
         * fully-localized XML file ready for Mapnik2 consumption
         *
         * @param {String} str the JSON file as a string.
         * @param {Function} callback to be called with err, XML representation.
         */
        render: function(str, callback) {
            var m = JSON.parse(str),
                that = this;
            this.localizeExternals(m, function(err, res) {
                that.localizeStyle(res, function(err, res) {
                    that.style(res, function(err, res) {
                        that.template(err, res, function(err, res) {
                            callback(err, res);
                        });
                    });
                });
            });
        }
    };
};

module.exports = mess;
<commit_msg>Add node-srs based layer SRS autodetection.<commit_after>var path = require('path'),
    fs = require('fs'),
    External = require('./external'),
    Step = require('step'),
    _ = require('underscore')._,
    sys = require('sys'),
    mess = require('mess');

require.paths.unshift(path.join(__dirname, '..', 'lib'));

/**
 * Rendering circuitry for JSON map manifests.
 *
 * This is node-only for the time being.
 */

/**
 * Convert a two-element-per-item Array
 * into an object, for the purpose of checking membership
 * and replacing stuff.
 * @param {Array} list a list.
 */
var to = function(list) {
    return list && list[0] && _.reduce(list, function(m, r) {
        if (r && r.length > 1) {
          m[r[0]] = r[1];
        }
        return m;
    }, {});
};

mess.Renderer = function Renderer(env) {
    var env = {
        data_dir: env.data_dir || '/tmp/',
        local_data_dir: env.local_data_dir || '',
        validation_data: env.validation_data || false
    };
    return {
        /**
         * Keep a copy of passed-in environment variables
         */
        env: env,
        /**
         * Wrapper for downloading externals: likely removable
         *
         * @param {String} uri the URI of the resource.
         * @param {Function} callback
         */
        grab: function(uri, callback) {
            new(External)(this.env).process(uri, callback);
        },

        /**
         * Ensure that map layers have a populated SRS value and attempt to
         * autodetect SRS if missing. Requires that node-srs is available and
         * that any remote datasources have been localized.
         *
         * @param {Object} m map object.
         * @param {Function} callback
         */
        ensureSRS: function(m, callback) {
            Step(
                function() {
                    var group = this.group();
                    var autodetect = _.filter(m.Layer, function(l) { return !l.srs });
                    _.each(autodetect, function(l) {
                        var finish = group();
                        Step(
                            function() {
                                fs.readdir(path.dirname(l.Datasource.file), this);
                            },
                            function(err, files) {
                                var prj = _.detect(files, function(f) {
                                    return path.extname(f).toLowerCase() == '.prj';
                                });
                                if (prj) {
                                    prj = path.join(path.dirname(l.Datasource.file), prj);
                                    fs.readFile(prj, 'utf-8', this);
                                } else {
                                    this(new Error('No projection found'));
                                }
                            },
                            function(err, srs) {
                                if (!err) {
                                    try {
                                        l.srs = require('srs').parse(srs).proj4;
                                    } catch (err) {
                                        finish(err);
                                    }
                                }
                                finish(err);
                            }
                        );
                    });
                    // If no layers missing SRS information, next.
                    autodetect.length === 0 && group()();
                },
                function(err) {
                    m.Layer = _.filter(m.Layer, function(l) { return l.srs });
                    callback(err, m);
                }
            );
        },

        /**
         * Download any file-based remote datsources.
         *
         * Usable as an entry point: does not expect any modification to
         * the map object beyond JSON parsing.
         *
         * @param {Object} m map object.
         * @param {Function} callback
         */
        localizeExternals: function(m, callback) {
            var that = this;
            Step(
                function() {
                    var group = this.group();
                    m.Layer.forEach(function(l) {
                        if (l.Datasource.file) {
                            that.grab(l.Datasource.file, group());
                        }
                    });
                    if (m.Layer.length == 0) group()();
                },
                function(err, results) {
                    var result_map = to(results);
                    m.Layer = _.map(_.filter(m.Layer,
                            function(l) {
                                return l.Datasource.file &&
                                    result_map[l.Datasource.file];
                            }),
                            function(l) {
                                l.Datasource.file = result_map[l.Datasource.file];
                                return l;
                            }
                    );
                    callback(err, m);
                }
            );
        },

        /**
         * Download any remote stylesheets
         *
         * @param {Object} m map object.
         * @param {Function} callback
         */
        localizeStyle: function(m, callback) {
            var that = this;
            Step(
                function() {
                    var group = this.group();
                    m.Stylesheet.forEach(function(s) {
                        if (!s.id) {
                            that.grab(s, group());
                        }
                    });
                    group()();
                },
                function(err, results) {
                    var result_map = to(results);
                    for (s in m.Stylesheet) {
                        if (!m.Stylesheet[s].id) {
                            m.Stylesheet[s] = result_map[m.Stylesheet[s]];
                        }
                    }
                    callback(err, m);
                }
            );
        },

        /**
         * Compile (already downloaded) styles with mess.js,
         * calling callback with an array of [map object, [stylesheet objects]]
         *
         * Called with the results of localizeStyle or localizeExternals:
         * expects not to handle downloading.
         *
         * @param {Object} m map object.
         * @param {Function} callback
         */
        style: function(m, callback) {
            var that = this;
            Step(
                function() {
                    var group = this.group();
                    m.Stylesheet.forEach(function(s) {
                        if (s.id) {
                            group()(null, [s.id, s.data]);
                        } else {
                            fs.readFile(s, 'utf-8', function(err, data) {
                                group()(err, [s, data]);
                            });
                        }
                    });
                },
                function(e, results) {
                    var options = {},
                        group = this.group();
                    for (var i = 0, l = results.length; i < l; i++) {
                        new(mess.Parser)(_.extend(_.extend({
                            filename: s
                        }, that.env), this.env)).parse(results[i][1], function(err, tree) {
                            if (err) {
                                mess.writeError(err, options);
                                throw err;
                            } else {
                                try {
                                    group()(err, [
                                        results[i][0],
                                        tree.toCSS({ compress: false }),
                                        tree]);
                                    return;
                                } catch (e) {
                                    throw e;
                                    return;
                                }
                            }
                        });
                    }
                },
                function(err, results) {
                    if (err) {
                        callback(err);
                        return;
                    }

                    var result_map = to(results);
                    for (s in m.Stylesheet) {
                        if (!m.Stylesheet[s].id) {
                            m.Stylesheet[s] = result_map[m.Stylesheet[s]];
                        } else {
                            m.Stylesheet[s] = result_map[m.Stylesheet[s].id];
                        }
                    }
                    callback(err, [m, results]);
                }
            );
        },

        /**
         * Prepare full XML map output. Called with the results
         * of this.style
         *
         * @param {Array} res array of [map object, stylesheets].
         * @param {Function} callback
         */
        template: function(err, res, callback) {
            if (err) {
                callback(err);
                return;
            }

            var m = res[0],
                stylesheets = res[1],

                entities = _.template('<?xml version="1.0" ' +
                    'encoding="utf-8"?>\n' +
                    '<!DOCTYPE Map[\n' +
                    '<% for (ref in externals) { %>' +
                    '  <!ENTITY <%= ref %> SYSTEM "<%= externals[ref] %>">\n' +
                    '<% } %>]>\n'),

                styles = _.template('<StyleName><%= name %></StyleName>'),

                layer = _.template('\n  <Layer\n   id="<%= id %>"\n' +
                    '   name="<%= name %>"\n' +
                    '   srs="<%= srs %>">\n' +
                    '<% for (s in styles) { %>' +
                    '    <StyleName><%= styles[s] %></StyleName>\n' +
                    '<% } %>' +
                    '    <Datasource>\n<% for (n in Datasource) { %>' +
                    '      <Parameter name="<%= n %>"><%= Datasource[n] %>' +
                    '</Parameter>\n' +
                    '<% } %>    </Datasource>\n' +
                    '  </Layer>\n'),

                stylesheet_tmpl = _.template('  <% for (i in Stylesheet) { %>' +
                    '<%= Stylesheet[i] %>\n' +
                    '<% } %>\n'),

                // referencing externals in the body of the map
                references = _.template('<% for (ref in externals) { %>' +
                    '&<%= ref %>;\n' +
                    '<% } %>'),

                // for the Map[] doctype: XML entities to
                // organize code
                entity_list = { externals: [], symbols: [] };

            /**
             * Index a hash of the CSS rules in all stylesheets
             * This is performance-critical: necessary to test
             * at some point
             *
             * @param {Array} stylesheets
             * @return {Array} list of selectors.
             */
            var ruleHash = function(stylesheets) {
                return _.flatten(_.map(stylesheets, function(s) {
                    return _.map(s[2].rules, function(r) {
                        if (r && r.selectors && r.selectors[0]._css) {
                            return r.selectors[0]._css;
                        }
                    });
                }));
            };

            var findBackground = function(stylesheets) {
                var b = '#FFFFFF';
                _.each(stylesheets, function(s) {
                    _.each(s[2].rules, function(r) {
                        if (r && r.selectors && r.selectors[0]._css &&
                            r.selectors[0]._css === 'Map') {
                            var bg = _.detect(r.rules, function(rule) {
                                return rule.name == 'background-color';
                            });
                            if (bg) {
                                b = bg.value.toCSS({ compress: false });
                            }
                        }
                    });
                });
                return b;
            };

            /**
             * Add styles to a layer object
             *
             * @param {Object} layer the layer object.
             * @param {Array} stylesheets the results of ruleHash().
             * @return Formalized layer definition with .styles = [].
             */
            var styleIntersect = function(layer, stylesheets) {
                var hash = ruleHash(stylesheets),
                    classes = _.map((layer['class'] || '').split(' '),
                        function(c) {
                            return 'class-' + c.trim();
                    }),
                    layer_id = 'id-' + layer.id;
                layer.styles = [];
                _.each(hash, function(h) {
                    if (h && (h.search(layer_id) != -1)) {
                        layer.styles.push(h);
                    }
                });

                _.each(hash, function(h) {
                    _.each(classes, function(c) {
                        if (h && (h.search(c) != -1)) {
                            layer.styles.push(c);
                        }
                    });
                });
                return layer;
            };

            var output = [entities(entity_list)];
            // TODO: must change when background colors are available
            output.push('<Map background-color="' +
                    findBackground(stylesheets)
                    + '" srs="+proj=merc +a=6378137 +b=6378137 '
                    + '+lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m '
                    + '+nadgrids=@null +no_defs">\n');
            // using array joins here: faster in IE7, unclear in general.
            m.Layer.forEach(function(l) {
                l = styleIntersect(l, stylesheets);
                output.push(layer(l));
            });
            output.push(references(entity_list));
            output.push(stylesheet_tmpl(m));
            output.push('</Map>');
            callback(null, output.join(''));
        },

        /**
         * Prepare a JML document (given as a string) into a
         * fully-localized XML file ready for Mapnik2 consumption
         *
         * @param {String} str the JSON file as a string.
         * @param {Function} callback to be called with err, XML representation.
         */
        render: function(str, callback) {
            var m = JSON.parse(str),
                that = this;
            this.localizeExternals(m, function(err, res) {
                that.ensureSRS(res, function(err, res) {
                    that.localizeStyle(res, function(err, res) {
                        that.style(res, function(err, res) {
                            that.template(err, res, function(err, res) {
                                callback(err, res);
                            });
                        });
                    });
                });
            });
        }
    };
};

module.exports = mess;
<|endoftext|>


<commit_before>"use strict";
var assert = require('assert');

var Suit = {
  Spades: 1,
  Diamonds: 2,
  Clubs: 3,
  Hearts: 4
};

var Stack = function() {

  Stack.prototype._cards = [];

  Stack.prototype.empty = function() {
    return true;
  };

  Stack.prototype.add = function(card) {

  };

  Stack.prototype.top = function() {

  };

  return this;
};

var Deck = function() {
  return this;
};

var Card = function(suit,value) {
  this._suit = suit;
  this._value = value;

  Card.prototype.suit = function() {
    return this._suit;
  };

  Card.prototype.value = function() {
    return this._value;
  };

  return this;
};

describe('klondike', function() {
  describe('card', function() {
    it('has a suit and a value', function() {
      var card = new Card(Suit.Spades,1);
      assert.equal(Suit.Spades, card.suit());
      assert.equal(1, card.value());
    });
  });

  describe('deck', function() {
    it('consists of 52 cards', function() {
      var deck = new Deck();
    });
  });

  describe('stack', function() {
    it('is a concept', function() {
      assert(new Stack().empty());
    });

    it('can add card', function() {
      var stack = new Stack();
      stack.add(new Card(Suit.Spades, 1));

      assert.deepEqual(new Card(Suit.Spades, 1), stack.top());
    });
  });

});
<commit_msg>simplest possible pass<commit_after>"use strict";
var assert = require('assert');

var Suit = {
  Spades: 1,
  Diamonds: 2,
  Clubs: 3,
  Hearts: 4
};

var Stack = function() {

  Stack.prototype._cards = [];

  Stack.prototype.empty = function() {
    return true;
  };

  Stack.prototype.add = function(card) {
    this._cards.push(card);
  };

  Stack.prototype.top = function() {
    return this._cards[0];
  };

  return this;
};

var Deck = function() {
  return this;
};

var Card = function(suit,value) {
  this._suit = suit;
  this._value = value;

  Card.prototype.suit = function() {
    return this._suit;
  };

  Card.prototype.value = function() {
    return this._value;
  };

  return this;
};

describe('klondike', function() {
  describe('card', function() {
    it('has a suit and a value', function() {
      var card = new Card(Suit.Spades,1);
      assert.equal(Suit.Spades, card.suit());
      assert.equal(1, card.value());
    });
  });

  describe('deck', function() {
    it('consists of 52 cards', function() {
      var deck = new Deck();
    });
  });

  describe('stack', function() {
    it('is a concept', function() {
      assert(new Stack().empty());
    });

    it('can add card', function() {
      var stack = new Stack();
      stack.add(new Card(Suit.Spades, 1));

      assert.deepEqual(new Card(Suit.Spades, 1), stack.top());
    });
  });

});
<|endoftext|>


<commit_before>/*
 * grunt-init-amber
 * https://amber-lang.net/
 *
 * Copyright (c) 2013 Manfred Kroehnert, contributors
 * Licensed under the MIT license.
 */

'use strict';

// Basic template description.
exports.description = 'Create a web application based on Amber Smalltalk.';

// Template-specific notes to be displayed before question prompts.
exports.notes = ' _Project title_ should be a human-readable title.';

// Template-specific notes to be displayed after question prompts.
exports.after = 'You need to have these installed globally via npm:' +
' _amber-cli_; _grunt-cli_; _bower_.' +
' Now, install project dependencies with _bower install_,' +
' tool dependencies with _npm install_ and optionally, recompile with _grunt_.' +
' If you are running _amber init_, these three tasks are going to be performed for you now.' +
' Afterwards, start the development server with _amber serve_.' +
' Your application is then accessible via _http://localhost:4000/_';

// Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = '*';

// The actual init template.
exports.template = function (grunt, init, done) {
    var remembered = {};

    function rememberViaValidator(name) {
        var oldValidator = init.prompts[name].validator || function (line) {
                return true;
            };

        var newValidator;
        switch (oldValidator.length) { //apply would not work, .length is used to call it differently
            case 1:
                newValidator = function (line) {
                    remembered[name] = line;
                    return oldValidator.call(this, line);
                };
                break;
            case 2:
                newValidator = function (line, next) {
                    remembered[name] = line;
                    return oldValidator.call(this, line, next);
                };
                break;
            default:
                throw new Error("Panic: " + oldValidator.length + "-argument validator for " + name + ".");
        }

        init.prompts[name].validator = newValidator;
    }

    function capitalize(string) {
        return string[0].toUpperCase() + string.slice(1).toLowerCase();
    }

    init.prompts.name.message = 'Main class and package of Amber application.\nProject name is derived by lowercasing this.';
    init.prompts.name.validator = function (line) {
        return /^[A-Z][A-Za-z0-9]*$/.test(line)
    };
    init.prompts.name.warning = 'Must be a valid class name: only alphanumeric and starting with an uppercase letter!';
    rememberViaValidator('name');
    rememberViaValidator('title');

    init.process({type: 'amber'}, [
        // Prompt for these values.
        init.prompt('title', 'Application or Library Title'),
        init.prompt('name', function (value, data, done) {
            var words = remembered.title.split(/\W/);
            words = words.filter(function (x) {
                return x && x !== "none";
            }).map(capitalize);
            value = words.length ? words.join('') : 'MysteriousApp';
            done(null, value);
        }),
        init.prompt('description', 'The Application or The Library doing The Thing.'),
        init.prompt('author_name'),
        init.prompt('author_email'),
        {
            name: 'namespace',
            message: 'Namespace of the new Amber package.',
            altDefault: function (value, data, done) {
                value = 'amber-' + remembered.name.toLowerCase();
                done(null, value);
            },
            validator: /^[a-z][a-z0-9/\-]*$/,
            warning: 'Only lowercase letters, numbers, and - are allowed in namespaces!'
        },
        init.prompt('version'),
        init.prompt('repository'),
        init.prompt('homepage'),
        init.prompt('bugs'),
        init.prompt('author_url'),
        init.prompt('licenses', 'MIT')
    ], function (err, props) {
        // Files to copy (and process).
        var files = init.filesToCopy(props);

        // Add properly-named license files.
        init.addLicenseFiles(files, props.licenses);

        // Actually copy (and process) files.
        init.copyAndProcess(files, props, {noProcess: 'libs/**'});

        // Clean up non-npm props.
        delete props.namespace;

        props.name = props.name.toLowerCase();

        // A few additional properties.
        props.keywords = ['Amber', 'Smalltalk'];
        props.devDependencies = {
            "amber-dev": "^0.8.0",
            "grunt": "^0.4.5",
            "grunt-contrib-clean": "^0.6.0",
            "grunt-contrib-requirejs": "^0.4.4",
            "grunt-execute": "^0.2.2",
            "requirejs": "^2.1.15"
        };
        props.node_version = '0.10.x || 0.12.x || >=4.0.0';
        props.scripts = {
            "test": "grunt test"
        };

        // Generate package.json file, used by npm and grunt.
        init.writePackageJSON('package.json', props);

        // generate bower.json file
        grunt.file.write('bower.json', JSON.stringify({
            "name": props.name,
            "description": props.description,
            "version": props.version,
            "ignore": [
                "**/.*",
                "node_modules",
                "bower_components",
                "/*.js",
                "/*.html",
                "test",
                "tests"
            ],
            "authors": [
                {
                    "name": props.author_name,
                    "email": props.author_email
                }
            ],
            "homepage": props.homepage,
            "main": props.main,
            "keywords": props.keywords,
            "license": props.licenses,
            "private": false,
            "dependencies": {
                "amber": "^0.14.17",
                "amber-contrib-jquery": ">=0.1.0",
                "amber-contrib-web": ">=0.1.0",
                "amber-contrib-domite": ">=0.3.1",
                "silk": ">=0.1.3"
            },
            "devDependencies": {
                "amber-ide-starter-dialog": "^0.1.0",
                "amber-contrib-legacy": "^0.2.1",
                "helios": ">=0.5.3"
            }
        }, null, 4));

        // All done!
        done();
    });

};
<commit_msg>bump grunt-contrib-clean<commit_after>/*
 * grunt-init-amber
 * https://amber-lang.net/
 *
 * Copyright (c) 2013 Manfred Kroehnert, contributors
 * Licensed under the MIT license.
 */

'use strict';

// Basic template description.
exports.description = 'Create a web application based on Amber Smalltalk.';

// Template-specific notes to be displayed before question prompts.
exports.notes = ' _Project title_ should be a human-readable title.';

// Template-specific notes to be displayed after question prompts.
exports.after = 'You need to have these installed globally via npm:' +
' _amber-cli_; _grunt-cli_; _bower_.' +
' Now, install project dependencies with _bower install_,' +
' tool dependencies with _npm install_ and optionally, recompile with _grunt_.' +
' If you are running _amber init_, these three tasks are going to be performed for you now.' +
' Afterwards, start the development server with _amber serve_.' +
' Your application is then accessible via _http://localhost:4000/_';

// Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = '*';

// The actual init template.
exports.template = function (grunt, init, done) {
    var remembered = {};

    function rememberViaValidator(name) {
        var oldValidator = init.prompts[name].validator || function (line) {
                return true;
            };

        var newValidator;
        switch (oldValidator.length) { //apply would not work, .length is used to call it differently
            case 1:
                newValidator = function (line) {
                    remembered[name] = line;
                    return oldValidator.call(this, line);
                };
                break;
            case 2:
                newValidator = function (line, next) {
                    remembered[name] = line;
                    return oldValidator.call(this, line, next);
                };
                break;
            default:
                throw new Error("Panic: " + oldValidator.length + "-argument validator for " + name + ".");
        }

        init.prompts[name].validator = newValidator;
    }

    function capitalize(string) {
        return string[0].toUpperCase() + string.slice(1).toLowerCase();
    }

    init.prompts.name.message = 'Main class and package of Amber application.\nProject name is derived by lowercasing this.';
    init.prompts.name.validator = function (line) {
        return /^[A-Z][A-Za-z0-9]*$/.test(line)
    };
    init.prompts.name.warning = 'Must be a valid class name: only alphanumeric and starting with an uppercase letter!';
    rememberViaValidator('name');
    rememberViaValidator('title');

    init.process({type: 'amber'}, [
        // Prompt for these values.
        init.prompt('title', 'Application or Library Title'),
        init.prompt('name', function (value, data, done) {
            var words = remembered.title.split(/\W/);
            words = words.filter(function (x) {
                return x && x !== "none";
            }).map(capitalize);
            value = words.length ? words.join('') : 'MysteriousApp';
            done(null, value);
        }),
        init.prompt('description', 'The Application or The Library doing The Thing.'),
        init.prompt('author_name'),
        init.prompt('author_email'),
        {
            name: 'namespace',
            message: 'Namespace of the new Amber package.',
            altDefault: function (value, data, done) {
                value = 'amber-' + remembered.name.toLowerCase();
                done(null, value);
            },
            validator: /^[a-z][a-z0-9/\-]*$/,
            warning: 'Only lowercase letters, numbers, and - are allowed in namespaces!'
        },
        init.prompt('version'),
        init.prompt('repository'),
        init.prompt('homepage'),
        init.prompt('bugs'),
        init.prompt('author_url'),
        init.prompt('licenses', 'MIT')
    ], function (err, props) {
        // Files to copy (and process).
        var files = init.filesToCopy(props);

        // Add properly-named license files.
        init.addLicenseFiles(files, props.licenses);

        // Actually copy (and process) files.
        init.copyAndProcess(files, props, {noProcess: 'libs/**'});

        // Clean up non-npm props.
        delete props.namespace;

        props.name = props.name.toLowerCase();

        // A few additional properties.
        props.keywords = ['Amber', 'Smalltalk'];
        props.devDependencies = {
            "amber-dev": "^0.8.0",
            "grunt": "^0.4.5",
            "grunt-contrib-clean": "^0.7.0",
            "grunt-contrib-requirejs": "^0.4.4",
            "grunt-execute": "^0.2.2",
            "requirejs": "^2.1.15"
        };
        props.node_version = '0.10.x || 0.12.x || >=4.0.0';
        props.scripts = {
            "test": "grunt test"
        };

        // Generate package.json file, used by npm and grunt.
        init.writePackageJSON('package.json', props);

        // generate bower.json file
        grunt.file.write('bower.json', JSON.stringify({
            "name": props.name,
            "description": props.description,
            "version": props.version,
            "ignore": [
                "**/.*",
                "node_modules",
                "bower_components",
                "/*.js",
                "/*.html",
                "test",
                "tests"
            ],
            "authors": [
                {
                    "name": props.author_name,
                    "email": props.author_email
                }
            ],
            "homepage": props.homepage,
            "main": props.main,
            "keywords": props.keywords,
            "license": props.licenses,
            "private": false,
            "dependencies": {
                "amber": "^0.14.17",
                "amber-contrib-jquery": ">=0.1.0",
                "amber-contrib-web": ">=0.1.0",
                "amber-contrib-domite": ">=0.3.1",
                "silk": ">=0.1.3"
            },
            "devDependencies": {
                "amber-ide-starter-dialog": "^0.1.0",
                "amber-contrib-legacy": "^0.2.1",
                "helios": ">=0.5.3"
            }
        }, null, 4));

        // All done!
        done();
    });

};
<|endoftext|>