wmeKit Sync

Using wme-sync-lib

wme-sync-lib adds WME Sync to a Waze Map Editor userscript: the editor’s settings and data follow them to every browser they edit from. It handles the username, the PIN, tokens and retries, so your script only calls get and set. Using an AI coding agent? Point it at /AGENTS.md, the same guide written for agents.

How it works

  1. Data is stored per Waze username and per script (your scriptId), as JSON values under keys.
  2. The first time anything syncs for a username, WME Sync creates it and generates an 8-digit PIN. The library shows that PIN to the editor once.
  3. In any other browser the editor enters the PIN once. Tokens live in each script’s own GM storage, so another script using WME Sync asks for the PIN once too. After that a long-lived token is used and refreshed automatically.
  4. Editors don’t need an account. Optionally they can link the username here, with its PIN, to browse and download their data, change the PIN and sign browsers out.

Setup

Add @require https://sync.wmekit.com/wme-sync-lib.js to your header along with the GM @grants and @connect sync.wmekit.com. Keep any @grants you already have. @grant none won’t work, because the library talks through GM_xmlhttpRequest and stores its tokens with GM_setValue (so CORS doesn’t apply). With any grant, your script runs sandboxed, so read the WME SDK globals (getWmeSdk, SDK_INITIALIZED) from unsafeWindow. The library defines a global WMESync.

// ==UserScript==
// @name         My WME Script
// @match        https://www.waze.com/*editor*
// @match        https://beta.waze.com/*editor*
// @require      https://sync.wmekit.com/wme-sync-lib.js
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        unsafeWindow
// @connect      sync.wmekit.com
// ==/UserScript==

unsafeWindow.SDK_INITIALIZED.then(async () => {
  const sdk = unsafeWindow.getWmeSdk({ scriptId: 'my-wme-script', scriptName: 'My WME Script' })
  await sdk.Events.once({ eventName: 'wme-ready' })

  // On the first call in a browser it sets up sync: new usernames get a PIN (shown to the
  // editor), existing ones are asked for theirs. Tokens are remembered after that.
  const sync = await WMESync.init({ scriptId: 'my-wme-script', sdk })

  const settings = (await sync.get('settings')) ?? { highlight: true }
  settings.lastOpened = Date.now()
  await sync.set('settings', settings)
})

init options

Call WMESync.init(options) after wme-ready. It makes no network request: the first data call (or ensureSignedIn()) runs the PIN step. It throws if there’s no username, which happens when the editor isn’t logged in to WME, so wrap it in try/catch and skip syncing.

OptionDescription
scriptIdRequired. Your script’s data namespace: 1–64 characters of A–Z a–z 0–9 . _ -. Pick it once and never change it: a new scriptId starts with empty data.
sdkThe WME SDK instance (from getWmeSdk), after wme-ready. The editor’s username is read from sdk.State.getUserInfo().
usernameThe Waze username, instead of sdk, if you already have it from the SDK.
labelShown in the editor’s token list on the dashboard. Defaults to “<scriptId> on <browser>”.
baseUrlAnother server, e.g. http://localhost:3000 while developing WME Sync itself.
promptForPin(username, retry)Asks for the PIN of an existing username. Return a string, or null to cancel. retry is true after a wrong PIN. Defaults to window.prompt.
onPinGenerated(username, pin)Called once when the first sync created the username, to show its new PIN. Defaults to window.alert.
let sync = null
try {
  sync = await WMESync.init({
    scriptId: 'my-wme-script', // stable, 1–64 chars of A–Z a–z 0–9 . _ -  NEVER change it later
    sdk,                       // used to read the signed-in editor's Waze username
    label: 'My WME Script',    // optional: shown in the editor's dashboard token list
  })
} catch (e) {
  // The editor isn't logged in to WME (no username): skip syncing this session.
  console.warn('[my-wme-script] WME Sync not started', e)
}

Methods

Everything except getPin() returns a promise. Expired tokens are refreshed for you, and the first call in a browser runs the PIN step.

MethodReturns / notes
get(key)The value, or undefined if the key isn’t set.
getEntry(key){ value, version, size, updated_at }, or undefined.
set(key, value, { ifVersion? })Stores any JSON value and resolves to { version, updated_at }. With ifVersion, throws a 409 if the stored version differs; ifVersion: 0 means “only if the key doesn’t exist”.
setMany({ key: value, … })Writes up to 100 keys in one request. Resolves to { key: { version, updated_at } }.
getAll()Every key of this script, as { key: value }.
keys()The key names of this script.
remove(key)Deletes a key. Resolves to true if it existed.
clear()Deletes every key of this script and resolves to the count.
getPin()The PIN this browser knows (generated or entered here), or null. Synchronous; no request.
me(){ username, linked, bytes_used, bytes_limit, scripts }: storage use across all scripts.
ensureSignedIn()Runs the PIN step now instead of on the first data call, e.g. when the editor turns sync on.
signOut()Revokes this browser’s token and forgets the PIN. The next call asks for the PIN again.

Limits

LimitValue
Keys1–128 characters of A–Z a–z 0–9 . _ -
ValuesAny JSON: object, array, string, number, boolean or null
Value size256 KB
Storage per Waze username5 MB, shared by all scripts
setMany100 keys per call
Wrong PINs5 per username and 20 per IP per 15 minutes, then 429
New usernames5 per IP per day, then 429

Errors

Every failure is a WMESyncError with .status and .body ({ error, code? } from the server).

statusMeaningWhat to do
0Network error or timeoutKeep using local settings and try again later.
400Invalid scriptId, key or value, or no username (editor not logged in to WME)A bug in your integration, or skip syncing when nobody is logged in.
401The editor cancelled the PIN prompt (“WME Sync sign-in cancelled”)Turn sync off for now and offer a “Connect WME Sync” button.
403origin_not_allowed: the call came from a web page other than WMECall from your userscript, through wme-sync-lib.
409ifVersion didn’t match; body.version is the current versionRe-read, merge and write again.
413Value over 256 KB, or the username’s 5 MB is fullStore less, or split it across keys.
429Too many wrong PINs, or too many new usernames from this network todayTell the editor to wait (15 minutes, or until tomorrow).

Custom PIN UI

The defaults use window.alert to show a new PIN and window.prompt to ask for one. They work, but a script with its own UI should replace them. Also add a “Show my WME Sync PIN” item (getPin()) and a “Disconnect” item (signOut()) to your settings: editors lose PINs.

const sync = await WMESync.init({
  scriptId: 'my-wme-script',
  sdk,
  // A new username was just created: show its PIN once, clearly.
  onPinGenerated: (username, pin) =>
    showMyDialog(`WME Sync is set up for ${username}. Your PIN is ${pin}. Keep it: you'll need it in other browsers.`),
  // The username already exists: ask for its PIN. Resolve to a string, or null to cancel.
  promptForPin: (username, retry) =>
    askMyDialog(retry ? 'That PIN was wrong. Try again:' : `Enter the WME Sync PIN for ${username}:`),
})

// In your settings panel:
showPinButton.onclick = () => alert(sync.getPin() ?? 'This browser doesn’t know the PIN.')
disconnectButton.onclick = () => sync.signOut() // the next call asks for the PIN again

Recommended pattern

Make sync an enhancement on top of local storage, never a hard dependency. Load local settings first, sync after, save locally on every change and debounce the upload.

const LOCAL_KEY = 'my-script-settings'
const DEFAULTS = { v: 1, highlight: true, color: '#33ccff' }

let settings = { ...DEFAULTS, ...JSON.parse(localStorage.getItem(LOCAL_KEY) || '{}') }
let sync = null

async function startSync(sdk) {
  if (localStorage.getItem('my-script-sync') === 'off') return
  try {
    sync = await WMESync.init({ scriptId: 'my-script', sdk, label: 'My Script' })
    const remote = await sync.get('settings') // first call: the PIN step happens here
    if (remote) {
      settings = { ...DEFAULTS, ...remote }
      localStorage.setItem(LOCAL_KEY, JSON.stringify(settings))
      applySettings(settings)
    } else {
      await sync.set('settings', settings) // first sync: upload what this browser has
    }
  } catch (e) {
    if (e?.status === 401) localStorage.setItem('my-script-sync', 'off') // declined: don't ask on every load
    console.warn('[my-script] WME Sync unavailable, using local settings', e)
    sync = null
  }
}

let saveTimer
function saveSettings(next) {
  settings = next
  localStorage.setItem(LOCAL_KEY, JSON.stringify(settings)) // always save locally first
  clearTimeout(saveTimer)
  saveTimer = setTimeout(() => sync?.set('settings', settings).catch((e) => console.warn('[my-script] sync failed', e)), 1500)
}

Concurrent edits

By default the last write wins, which is right for settings. If two browsers can change the same structured data, such as a list, read it with getEntry, write with ifVersion and merge again on a 409.

// Add a favourite without losing one added meanwhile in another browser.
async function addFavorite(sync, place) {
  for (let attempt = 0; attempt < 3; attempt++) {
    const entry = await sync.getEntry('favorites') // undefined if the key isn't set yet
    const list = entry?.value ?? []
    try {
      // ifVersion: 0 means "only if the key doesn't exist yet".
      await sync.set('favorites', [...list, place], { ifVersion: entry?.version ?? 0 })
      return
    } catch (e) {
      if (e?.status !== 409) throw e // someone else wrote first: re-read, merge, try again
    }
  }
  throw new Error('favorites kept changing, try again later')
}

Guidelines

  • One scriptId per script, never changed. Renaming it orphans the editor’s data.
  • Few, meaningful keys (settings, favorites, layers), not one key per toggle. Use setMany when several change together.
  • Debounce writes (at least a second). Don’t write on every keystroke or map move.
  • Read once at startup. There are no live updates: another browser’s changes arrive on the next WME load.
  • Version your stored shape (e.g. { v: 2, … }) so later versions of your script can migrate it.
  • Let editors turn sync off, and keep working when WME Sync is unreachable.
Don’ts
  • Don’t store passwords, API keys, tokens, or other people’s personal data.
  • Don’t hardcode, log or send the PIN anywhere, and don’t read the library’s stored tokens (wmesync.* GM values).
  • Don’t take the username from anywhere except the WME SDK.
  • Don’t block your script’s startup on WME Sync. Load local settings first, sync after.
  • Don’t create throwaway usernames for testing; each IP gets 5 a day. Test with your own username and inspect or delete the data on the dashboard.

Writing the integration with an AI coding agent? Give it /AGENTS.md: it has all of the above plus a checklist to finish with.