@somewhere-cloud/cli 0.38.28 → 0.38.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
9
12
  var __commonJS = (cb, mod) => function __require() {
10
13
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
14
  };
@@ -75,6 +78,37 @@ var require_function_route = __commonJS({
75
78
  }
76
79
  });
77
80
 
81
+ // worker/src/utils/log-sanitize.ts
82
+ var SENSITIVE_PARAMS, SENSITIVE_PARAM_NAMES;
83
+ var init_log_sanitize = __esm({
84
+ "worker/src/utils/log-sanitize.ts"() {
85
+ "use strict";
86
+ SENSITIVE_PARAMS = [
87
+ "access_token",
88
+ "refresh_token",
89
+ // OAuth callbacks carry one-use credentials even when validation refuses them.
90
+ "code",
91
+ "state",
92
+ // A creator or link secret belongs only in a request body; a stray query copy is never kept.
93
+ "creator_secret",
94
+ "secret",
95
+ "signature",
96
+ "api_key",
97
+ "apikey",
98
+ "token",
99
+ "key",
100
+ "sig",
101
+ // A DSN carries its own password, and percent-encoding hides it from the
102
+ // Postgres URI rule below. `password` covers the other connection-string
103
+ // form, `postgres://reader@host/db?password=…`, which has no userinfo
104
+ // password for that rule to match.
105
+ "dsn",
106
+ "password"
107
+ ];
108
+ SENSITIVE_PARAM_NAMES = new Set(SENSITIVE_PARAMS);
109
+ }
110
+ });
111
+
78
112
  // worker/containers/compile/declared-data-contract.cjs
79
113
  var require_declared_data_contract = __commonJS({
80
114
  "worker/containers/compile/declared-data-contract.cjs"(exports, module2) {
@@ -1275,30 +1309,11 @@ var import_function_route = __toESM(require_function_route());
1275
1309
  // worker/src/runtime/verify-signup.ts
1276
1310
  var VERIFY_SIGNUP_FETCH_PROLOGUE = " const verifySignup = await __sw_captureVerifySignup(request); request = verifySignup.request;";
1277
1311
 
1278
- // worker/src/utils/log-sanitize.ts
1279
- var SENSITIVE_PARAMS = [
1280
- "access_token",
1281
- "refresh_token",
1282
- // OAuth callbacks carry one-use credentials even when validation refuses them.
1283
- "code",
1284
- "state",
1285
- // A creator or link secret belongs only in a request body; a stray query copy is never kept.
1286
- "creator_secret",
1287
- "secret",
1288
- "signature",
1289
- "api_key",
1290
- "apikey",
1291
- "token",
1292
- "key",
1293
- "sig",
1294
- // A DSN carries its own password, and percent-encoding hides it from the
1295
- // Postgres URI rule below. `password` covers the other connection-string
1296
- // form, `postgres://reader@host/db?password=…`, which has no userinfo
1297
- // password for that rule to match.
1298
- "dsn",
1299
- "password"
1300
- ];
1301
- var SENSITIVE_PARAM_NAMES = new Set(SENSITIVE_PARAMS);
1312
+ // worker/src/utils/platform-compile-failure.ts
1313
+ var COMPILE_UNAVAILABLE_REALERT_MS = 60 * 60 * 1e3;
1314
+
1315
+ // worker/src/utils/authority.ts
1316
+ init_log_sanitize();
1302
1317
 
1303
1318
  // worker/src/utils/function-bundle-transport.ts
1304
1319
  var NATIVE_RUNTIME_SERVICE_BINDING = "RUNTIME_PLATFORM_API";
@@ -2337,6 +2352,9 @@ function __sw_parseTraceparent(raw) {
2337
2352
  // the customer's own file path, so they are named from the reserved operation
2338
2353
  // segment or the HTTP method, never from a path segment; anything that is not
2339
2354
  // a platform /v1/ path is 'platform.call', never the path itself.
2355
+ // sw.rooms -> its platform-private door half (the browser ticket door). Module
2356
+ // scope: customer modules cannot name it, and nothing is stored on sw.
2357
+ const __sw_roomsDoor = new WeakMap();
2340
2358
  const __sw_FS_OPS = { move: 1, copy: 1, restore: 1, stat: 1, versions: 1, diff: 1, glob: 1, search: 1, replace: 1, sign: 1, 'public-url': 1, visibility: 1 };
2341
2359
  const __sw_FS_METHOD_OPS = { GET: 'sw.fs.get', HEAD: 'sw.fs.get', PUT: 'sw.fs.write', DELETE: 'sw.fs.delete', POST: 'sw.fs.post' };
2342
2360
  function __sw_traceOpName(path, method) {
@@ -15957,6 +15975,138 @@ var PUSH_JS = ` push: (function () {
15957
15975
  };
15958
15976
  })(),`;
15959
15977
 
15978
+ // worker/src/runtime/rooms.ts
15979
+ var ROOMS_JS = ` rooms: (function () {
15980
+ function __sw_roomsError(code, message, status) {
15981
+ const err = new Error(message);
15982
+ err.code = code;
15983
+ err.status = status;
15984
+ err.__sw_expose = true;
15985
+ return __sw_markExpected(err);
15986
+ }
15987
+ function __sw_roomsRef(label, table, id) {
15988
+ if (typeof table !== 'string' || table.length === 0 || table.length > 128) {
15989
+ throw __sw_roomsError('VALIDATION_ERROR', label + ': table must be the name of a table that declares rooms.', 400);
15990
+ }
15991
+ if (!(typeof id === 'string' && id.length > 0 && id.length <= 4096) && !(typeof id === 'number' && Number.isSafeInteger(id))) {
15992
+ throw __sw_roomsError('VALIDATION_ERROR', label + ': id must be the row id (a string or a whole number).', 400);
15993
+ }
15994
+ return { table: table, id: id };
15995
+ }
15996
+ function __sw_roomsVisitorToken() {
15997
+ const staged = typeof __sw_visitorSessionToken === 'function' ? __sw_visitorSessionToken() : null;
15998
+ return staged || __sw_readCookie(__sw_authSnapshotRequest.headers.get('cookie'), '__Host-sw_visitor') || null;
15999
+ }
16000
+ // The verified person of this request, carried the way every user-owned
16001
+ // surface carries it. The platform re-verifies; nothing here is trusted.
16002
+ async function __sw_roomsCallerHeaders(label, issueVisitor) {
16003
+ if (__sw_signedDelivery || __sw_hasRuntimeProjectAuthority()) {
16004
+ throw __sw_roomsError('ROOM_NO_CALLER', label + ' acts as the person who made this request, and this request has none (a job, schedule or server call). Use sw.rooms.server.' + label.split('.').pop() + ' for platform authority.', 403);
16005
+ }
16006
+ __sw_enforceAmbientCookieCsrf();
16007
+ if (await __sw_optionalSubject()) {
16008
+ return await __sw_runtimeSubjectHeaders('X-Somewhere-Rooms-Authority', 'none');
16009
+ }
16010
+ let visitor = __sw_roomsVisitorToken();
16011
+ if (!visitor && issueVisitor && typeof __sw_resolveVisitorIdentity === 'function') {
16012
+ // The ticket door gives a first-time anonymous visitor a session when the
16013
+ // app declares visitor identity, so the person is the same on reconnect.
16014
+ try { await __sw_resolveVisitorIdentity(); visitor = __sw_roomsVisitorToken(); }
16015
+ catch (err) { if (!err || err.code !== 'VISITOR_IDENTITY_UNAVAILABLE') throw err; }
16016
+ }
16017
+ if (visitor) return { 'X-Somewhere-Rooms-Authority': 'visitor', 'X-Sw-Visitor-Session': visitor };
16018
+ return { 'X-Somewhere-Rooms-Authority': 'none' };
16019
+ }
16020
+ async function __sw_roomsCall(path, headers, body) {
16021
+ const r = await platformFetch(path, {
16022
+ method: 'POST',
16023
+ headers: Object.assign({ 'Content-Type': 'application/json' }, headers),
16024
+ body: JSON.stringify(Object.assign({ project_id: projectId }, body)),
16025
+ });
16026
+ const data = await __sw_platformJSONBody(r);
16027
+ if (!r.ok || !data || data.ok === false) {
16028
+ const err = __sw_platformError(r, data);
16029
+ if (data && typeof data.reason === 'string') err.reason = data.reason;
16030
+ if (data && data.state !== undefined) err.state = data.state;
16031
+ if (data && data.version !== undefined) err.version = data.version;
16032
+ if (r.status >= 400 && r.status < 500) { err.__sw_expose = true; __sw_markExpected(err); }
16033
+ throw err;
16034
+ }
16035
+ return data.data;
16036
+ }
16037
+ function __sw_roomsOps(label, prefix, headersFor) {
16038
+ return {
16039
+ async act(table, id, action) {
16040
+ const ref = __sw_roomsRef(label + '.act', table, id);
16041
+ return __sw_roomsCall(prefix + 'act', await headersFor(label + '.act'), Object.assign(ref, { action: action }));
16042
+ },
16043
+ async set(table, id, patch) {
16044
+ const ref = __sw_roomsRef(label + '.set', table, id);
16045
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
16046
+ throw __sw_roomsError('VALIDATION_ERROR', label + '.set: patch must be an object of top-level keys (null deletes a key).', 400);
16047
+ }
16048
+ return __sw_roomsCall(prefix + 'set', await headersFor(label + '.set'), Object.assign(ref, { patch: patch }));
16049
+ },
16050
+ async send(table, id, message) {
16051
+ const ref = __sw_roomsRef(label + '.send', table, id);
16052
+ return __sw_roomsCall(prefix + 'send', await headersFor(label + '.send'), Object.assign(ref, { message: message }));
16053
+ },
16054
+ async get(table, id) {
16055
+ const ref = __sw_roomsRef(label + '.get', table, id);
16056
+ return __sw_roomsCall(prefix + 'get', await headersFor(label + '.get'), ref);
16057
+ },
16058
+ };
16059
+ }
16060
+ async function __sw_roomsServerHeaders() { return { 'X-Somewhere-Rooms-Authority': 'server' }; }
16061
+ const __sw_roomsVerified = new WeakMap();
16062
+ async function __sw_roomsEvent(req) {
16063
+ if (!req || typeof req.clone !== 'function' || !req.headers) {
16064
+ throw __sw_roomsError('ROOM_EVENT_INVALID', 'sw.rooms.event(req) takes the request your referee function received.', 400);
16065
+ }
16066
+ const known = __sw_roomsVerified.get(req);
16067
+ if (known) return known;
16068
+ const pending = (async function () {
16069
+ const eventId = req.headers.get('x-somewhere-room-event');
16070
+ const invalid = function () { return __sw_roomsError('ROOM_EVENT_INVALID', 'This request is not an event sent by a room of this app.', 403); };
16071
+ if (!eventId) throw invalid();
16072
+ const bytes = new Uint8Array(await req.clone().arrayBuffer());
16073
+ let event;
16074
+ try { event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); } catch (_) { throw invalid(); }
16075
+ if (!event || typeof event !== 'object' || !event.row || typeof event.row.table !== 'string') throw invalid();
16076
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
16077
+ let hex = '';
16078
+ for (let i = 0; i < digest.length; i++) hex += digest[i].toString(16).padStart(2, '0');
16079
+ let answer;
16080
+ try {
16081
+ answer = await __sw_roomsCall('/v1/rooms/verify-event', {}, { table: event.row.table, id: event.row.id, event_id: eventId, body_sha256: hex });
16082
+ } catch (err) {
16083
+ if (err && err.status >= 400 && err.status < 500) throw invalid();
16084
+ throw err;
16085
+ }
16086
+ if (!answer || answer.valid !== true) throw invalid();
16087
+ return event;
16088
+ })();
16089
+ __sw_roomsVerified.set(req, pending);
16090
+ pending.catch(function () { __sw_roomsVerified.delete(req); });
16091
+ return pending;
16092
+ }
16093
+ const __sw_rooms = Object.assign(__sw_roomsOps('sw.rooms', '/v1/rooms/', function (label) { return __sw_roomsCallerHeaders(label, false); }), {
16094
+ server: Object.freeze(__sw_roomsOps('sw.rooms.server', '/v1/rooms/server/', __sw_roomsServerHeaders)),
16095
+ event: __sw_roomsEvent,
16096
+ });
16097
+ Object.freeze(__sw_rooms);
16098
+ // Platform-private: the browser ticket door (/__sw/rooms/ticket) asks for a
16099
+ // ticket as this request's person. Module-scoped, never reachable from sw.
16100
+ __sw_roomsDoor.set(__sw_rooms, {
16101
+ async ticket(table, id) {
16102
+ const ref = __sw_roomsRef('joinRoom', table, id);
16103
+ return __sw_roomsCall('/v1/rooms/ticket', await __sw_roomsCallerHeaders('sw.rooms.ticket', true), ref);
16104
+ },
16105
+ });
16106
+ return __sw_rooms;
16107
+ })(),
16108
+ `;
16109
+
15960
16110
  // worker/src/runtime/context-tail.ts
15961
16111
  var CONTEXT_TAIL_JS = ` };
15962
16112
  // sw.realtime is RETIRED (tsk_e0cc5403). There is no namespace: the property
@@ -16066,11 +16216,22 @@ var CONTEXT_TAIL_JS = ` };
16066
16216
  portal: sw.payments.portal,
16067
16217
  portalForUser: sw.payments.portalForUser,
16068
16218
  });
16219
+ // Rooms are a live-app feature: every operation refuses with one typed code,
16220
+ // before any transport, and the real namespace is never reachable here.
16221
+ function draftRoomsUnavailable() {
16222
+ const err = new Error('Rooms work on the live app only, not in a preview. Deploy, then open the live app.');
16223
+ err.code = 'ROOMS_DRAFT_UNAVAILABLE';
16224
+ err.status = 409;
16225
+ err.__sw_expose = true;
16226
+ throw err;
16227
+ }
16228
+ const draftRoomsOps = { act: draftRoomsUnavailable, set: draftRoomsUnavailable, send: draftRoomsUnavailable, get: draftRoomsUnavailable };
16229
+ const draftRooms = Object.freeze(Object.assign({}, draftRoomsOps, { server: Object.freeze(Object.assign({}, draftRoomsOps)), event: draftRoomsUnavailable }));
16069
16230
  const draftSafe = new Set([
16070
16231
  'project_id', 'subdomain', 'tier', 'env', 'request_id', 'params',
16071
16232
  // Groups stays discoverable only to return its draft refusal before transport.
16072
16233
  'groups',
16073
- 'crypto', 'db', 'fs', 'auth', 'billing', 'email', 'payments', 'logs', 'sw', 'ctx',
16234
+ 'crypto', 'db', 'fs', 'auth', 'billing', 'email', 'payments', 'logs', 'rooms', 'sw', 'ctx',
16074
16235
  '__sw_pendingRefresh', '__sw_pendingCookies', '__sw_pendingBackground',
16075
16236
  // Response state the shim's attachPendingRefresh reads on every answer (#439). A draft's
16076
16237
  // read session is inert by construction (context-head: envelope null when isDraftExecution),
@@ -16099,10 +16260,11 @@ var CONTEXT_TAIL_JS = ` };
16099
16260
  const descriptor = Object.getOwnPropertyDescriptor(sw, property);
16100
16261
  if (!descriptor) continue;
16101
16262
  if (property === 'db' || property === 'fs' || property === 'auth' || property === 'billing' || property === 'email'
16102
- || property === 'payments') {
16263
+ || property === 'payments' || property === 'rooms') {
16103
16264
  Object.defineProperty(draftTarget, property, {
16104
16265
  value: property === 'db' ? draftDb : property === 'fs' ? draftFs : property === 'auth' ? draftAuth
16105
- : property === 'billing' ? draftBilling : property === 'email' ? draftEmail : draftPayments,
16266
+ : property === 'billing' ? draftBilling : property === 'email' ? draftEmail
16267
+ : property === 'rooms' ? draftRooms : draftPayments,
16106
16268
  enumerable: descriptor.enumerable,
16107
16269
  });
16108
16270
  } else {
@@ -16178,6 +16340,7 @@ var PARTS = [
16178
16340
  WEB_JS,
16179
16341
  NOTIFICATIONS_JS,
16180
16342
  PUSH_JS,
16343
+ ROOMS_JS,
16181
16344
  CONTEXT_TAIL_JS
16182
16345
  ];
16183
16346
  var PLATFORM_CONTEXT_JS = PARTS.join("\n").trim();
@@ -17524,6 +17687,443 @@ async function __sw_handlePushDoor(request, sw, env) {
17524
17687
  }
17525
17688
  `;
17526
17689
 
17690
+ // worker/src/runtime/rooms-client.ts
17691
+ var ROOMS_CLIENT_MODULE_JS = `
17692
+ const TICKET_PATH = '/__sw/rooms/ticket';
17693
+ const CONNECT_PATH = '/__sw/rooms/connect';
17694
+ const RENEW_MS = 240000;
17695
+ const PING_MS = 30000;
17696
+ const PING_FRAME = '{"t":"ping"}';
17697
+ const PONG_FRAME = '{"t":"pong"}';
17698
+ const FINAL_BYE = { row_deleted: 'ROOM_ROW_DELETED', full: 'ROOM_FULL' };
17699
+
17700
+ function roomError(code, message, extra) {
17701
+ const err = new Error(message);
17702
+ err.code = code;
17703
+ if (extra) for (const key in extra) err[key] = extra[key];
17704
+ return err;
17705
+ }
17706
+
17707
+ function merge(base, patch) {
17708
+ const next = Object.assign({}, base);
17709
+ for (const key of Object.keys(patch || {})) {
17710
+ if (patch[key] === null) delete next[key];
17711
+ else next[key] = patch[key];
17712
+ }
17713
+ return next;
17714
+ }
17715
+
17716
+ async function requestTicket(table, id) {
17717
+ let res;
17718
+ try {
17719
+ res = await fetch(TICKET_PATH, {
17720
+ method: 'POST',
17721
+ credentials: 'same-origin',
17722
+ headers: { 'content-type': 'application/json' },
17723
+ body: JSON.stringify({ table: table, id: id }),
17724
+ });
17725
+ } catch (cause) {
17726
+ throw roomError('ROOM_UNREACHABLE', 'The room could not be reached. Check the connection.', { retryable: true, cause: cause });
17727
+ }
17728
+ let body = null;
17729
+ try { body = await res.json(); } catch (_) {}
17730
+ if (!res.ok || !body || body.ok === false || !body.data || typeof body.data.ticket !== 'string') {
17731
+ const code = (body && (body.code || body.error)) || 'ROOM_UNREACHABLE';
17732
+ throw roomError(code, (body && body.message) || ('The room could not be joined (' + res.status + ').'), {
17733
+ status: res.status,
17734
+ retryable: res.status >= 500 || res.status === 429 || !body,
17735
+ });
17736
+ }
17737
+ return body.data.ticket;
17738
+ }
17739
+
17740
+ function connectUrl(ticket) {
17741
+ return (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + CONNECT_PATH + '?ticket=' + encodeURIComponent(ticket);
17742
+ }
17743
+
17744
+ class Room {
17745
+ constructor(table, id) {
17746
+ this.table = table;
17747
+ this.id = id;
17748
+ this.state = {};
17749
+ this.version = 0;
17750
+ this.people = [];
17751
+ this.canSet = false;
17752
+ this.referee = false;
17753
+ this.status = 'connecting';
17754
+ const room = this;
17755
+ this.me = {
17756
+ info: null,
17757
+ set(info) {
17758
+ if (!info || typeof info !== 'object' || Array.isArray(info)) throw new TypeError('room.me.set takes an object');
17759
+ room.me.info = info;
17760
+ room._frame({ t: 'me', info: info });
17761
+ },
17762
+ };
17763
+ this._handlers = { state: new Set(), message: new Set(), people: new Set(), status: new Set(), timer_failed: new Set() };
17764
+ this._base = {};
17765
+ this._you = null;
17766
+ this._n = 0;
17767
+ this._sets = [];
17768
+ this._acts = new Map();
17769
+ this._socket = null;
17770
+ this._generation = 0;
17771
+ this._stopped = false;
17772
+ this._failures = 0;
17773
+ this._retry = null;
17774
+ this._renew = null;
17775
+ this._ping = null;
17776
+ this._lastPong = 0;
17777
+ this._firstJoin = null;
17778
+ }
17779
+
17780
+ on(event, fn) {
17781
+ const set = this._handlers[event];
17782
+ if (!set) throw new TypeError('room.on: unknown event ' + event + ' (use state, people, message, status or timer_failed)');
17783
+ if (typeof fn !== 'function') throw new TypeError('room.on takes a function');
17784
+ set.add(fn);
17785
+ return () => set.delete(fn);
17786
+ }
17787
+
17788
+ _emit(event, a, b) {
17789
+ for (const fn of Array.from(this._handlers[event])) {
17790
+ try { fn(a, b); } catch (err) { setTimeout(() => { throw err; }); }
17791
+ }
17792
+ }
17793
+
17794
+ _setStatus(status, detail) {
17795
+ if (this.status === status) return;
17796
+ this.status = status;
17797
+ this._emit('status', status, detail);
17798
+ }
17799
+
17800
+ _frame(frame) {
17801
+ const socket = this._socket;
17802
+ if (!socket || socket.readyState !== 1 || this.status !== 'open') return false;
17803
+ socket.send(JSON.stringify(frame));
17804
+ return true;
17805
+ }
17806
+
17807
+ _recompute(change) {
17808
+ let next = this._base;
17809
+ for (const entry of this._sets) next = merge(next, entry.patch);
17810
+ this.state = next;
17811
+ this._emit('state', this.state, change || null);
17812
+ }
17813
+
17814
+ _decoratePeople(list) {
17815
+ return list.map((person) => Object.assign({}, person, { me: person.id === this._you }));
17816
+ }
17817
+
17818
+ set(patch) {
17819
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
17820
+ return Promise.reject(new TypeError('room.set takes an object of top-level keys (null deletes a key)'));
17821
+ }
17822
+ if (this._stopped) return Promise.reject(roomError('ROOM_LEFT', 'This room was left.'));
17823
+ if (this.referee) return Promise.reject(roomError('ROOM_HAS_REFEREE', 'This room has a referee: use room.act(action).'));
17824
+ const n = ++this._n;
17825
+ return new Promise((resolve, reject) => {
17826
+ const entry = { n: n, patch: patch, resolve: resolve, reject: reject, acked: null };
17827
+ if (!this._frame({ t: 'set', n: n, patch: patch })) {
17828
+ reject(roomError('ROOM_NOT_CONNECTED', 'The room is reconnecting; nothing was changed. Try again when room.status is open.'));
17829
+ return;
17830
+ }
17831
+ this._sets.push(entry);
17832
+ this._recompute({ by: 'me', pending: true });
17833
+ });
17834
+ }
17835
+
17836
+ act(action) {
17837
+ if (this._stopped) return Promise.reject(roomError('ROOM_LEFT', 'This room was left.'));
17838
+ if (!this.referee) return Promise.reject(roomError('ROOM_NO_REFEREE', 'This room has no referee: use room.set(patch).'));
17839
+ const n = ++this._n;
17840
+ return new Promise((resolve, reject) => {
17841
+ if (!this._frame({ t: 'act', n: n, action: action })) {
17842
+ reject(roomError('ROOM_NOT_CONNECTED', 'The room is reconnecting; the action was not sent. Try again when room.status is open.'));
17843
+ return;
17844
+ }
17845
+ this._acts.set(n, { resolve: resolve, reject: reject, acked: null });
17846
+ });
17847
+ }
17848
+
17849
+ send(data) {
17850
+ if (this._stopped) return false;
17851
+ return this._frame({ t: 'msg', data: data });
17852
+ }
17853
+
17854
+ leave() {
17855
+ if (this._stopped) return;
17856
+ this._stopped = true;
17857
+ this._generation++;
17858
+ this._clearTimers();
17859
+ if (this._socket) { try { this._socket.close(1000, 'leave'); } catch (_) {} }
17860
+ this._socket = null;
17861
+ this._failUnanswered('ROOM_LEFT');
17862
+ this._setStatus('closed', { code: 'left' });
17863
+ }
17864
+
17865
+ _clearTimers() {
17866
+ if (this._retry !== null) { clearTimeout(this._retry); this._retry = null; }
17867
+ if (this._renew !== null) { clearInterval(this._renew); this._renew = null; }
17868
+ if (this._ping !== null) { clearInterval(this._ping); this._ping = null; }
17869
+ }
17870
+
17871
+ // Unanswered operations whose connection is gone: their outcome is unknown.
17872
+ // Never re-sent; the caller gets the fresh state with the refusal.
17873
+ _failUnanswered(reasonCode) {
17874
+ const state = this.state;
17875
+ const unknown = (kind) => roomError('ROOM_OUTCOME_UNKNOWN', 'The connection dropped before the room answered this ' + kind + '. It may or may not have been applied; err.state is the room\\'s current state.', { state: state, version: this.version, cause: reasonCode });
17876
+ for (const entry of this._acts.values()) entry.reject(unknown('action'));
17877
+ this._acts.clear();
17878
+ for (const entry of this._sets) entry.reject(unknown('change'));
17879
+ this._sets = [];
17880
+ }
17881
+
17882
+ _settleAcked() {
17883
+ for (const [n, entry] of this._acts) {
17884
+ if (entry.acked !== null && this.version >= entry.acked) { this._acts.delete(n); entry.resolve(this.state); }
17885
+ }
17886
+ const before = this._sets.length;
17887
+ this._sets = this._sets.filter((entry) => {
17888
+ if (entry.acked !== null && this.version >= entry.acked) { entry.resolve(this._base); return false; }
17889
+ return true;
17890
+ });
17891
+ return before !== this._sets.length;
17892
+ }
17893
+
17894
+ _onFrame(frame) {
17895
+ if (!frame || typeof frame.t !== 'string') return;
17896
+ switch (frame.t) {
17897
+ case 'hello': {
17898
+ const first = this._firstJoin !== null;
17899
+ this._you = frame.you;
17900
+ this.canSet = frame.can_set === true;
17901
+ this.referee = frame.referee === true;
17902
+ this._base = frame.state && typeof frame.state === 'object' ? frame.state : {};
17903
+ this.version = frame.version || 0;
17904
+ this.people = this._decoratePeople(Array.isArray(frame.people) ? frame.people : []);
17905
+ this._failures = 0;
17906
+ this._setStatus('open');
17907
+ // Anything unanswered from the previous connection gets this fresh state.
17908
+ this.state = this._base;
17909
+ this._failUnanswered('reconnected');
17910
+ this._recompute({ by: null, joined: true });
17911
+ this._emit('people', this.people);
17912
+ if (this.me.info) this._frame({ t: 'me', info: this.me.info });
17913
+ if (first) { const done = this._firstJoin; this._firstJoin = null; done.resolve(this); }
17914
+ return;
17915
+ }
17916
+ case 'state': {
17917
+ if (typeof frame.version === 'number' && frame.version <= this.version) return;
17918
+ this._base = frame.state !== undefined ? (frame.state || {}) : merge(this._base, frame.patch);
17919
+ this.version = frame.version;
17920
+ this._settleAcked();
17921
+ this._recompute({ by: frame.by === undefined ? null : frame.by, version: frame.version });
17922
+ return;
17923
+ }
17924
+ case 'ok': {
17925
+ const act = this._acts.get(frame.n);
17926
+ if (act) {
17927
+ if (this.version >= frame.version) { this._acts.delete(frame.n); act.resolve(this.state); }
17928
+ else act.acked = frame.version;
17929
+ return;
17930
+ }
17931
+ const entry = this._sets.find((item) => item.n === frame.n);
17932
+ if (entry) {
17933
+ entry.acked = frame.version;
17934
+ if (this._settleAcked()) this._recompute({ by: 'me', version: this.version });
17935
+ }
17936
+ return;
17937
+ }
17938
+ case 'no': {
17939
+ if (frame.state !== undefined && typeof frame.version === 'number' && frame.version >= this.version) {
17940
+ this._base = frame.state || {};
17941
+ this.version = frame.version;
17942
+ }
17943
+ const err = roomError(frame.code || 'ROOM_REFUSED', frame.reason || frame.code || 'The room refused this.', { reason: frame.reason, state: this._base, version: this.version });
17944
+ const act = this._acts.get(frame.n);
17945
+ if (act) { this._acts.delete(frame.n); err.state = this.state; act.reject(err); return; }
17946
+ const index = this._sets.findIndex((item) => item.n === frame.n);
17947
+ if (index !== -1) {
17948
+ const entry = this._sets.splice(index, 1)[0];
17949
+ this._recompute({ by: 'me', refused: frame.code });
17950
+ err.state = this.state;
17951
+ entry.reject(err);
17952
+ }
17953
+ return;
17954
+ }
17955
+ case 'msgs': {
17956
+ for (const item of Array.isArray(frame.items) ? frame.items : []) this._emit('message', item.data, item.from);
17957
+ return;
17958
+ }
17959
+ case 'people': {
17960
+ const left = new Set(frame.left || []);
17961
+ const changed = new Map((frame.changed || []).map((person) => [person.id, person]));
17962
+ let next = this.people.filter((person) => !left.has(person.id)).map((person) => changed.has(person.id) ? Object.assign({}, person, changed.get(person.id), { me: person.id === this._you }) : person);
17963
+ next = next.concat(this._decoratePeople((frame.joined || []).filter((person) => !next.some((p) => p.id === person.id))));
17964
+ this.people = next;
17965
+ this._emit('people', this.people);
17966
+ return;
17967
+ }
17968
+ case 'timer_failed': {
17969
+ this._emit('timer_failed');
17970
+ return;
17971
+ }
17972
+ case 'bye': {
17973
+ this._bye = frame.code;
17974
+ return;
17975
+ }
17976
+ case 'pong': {
17977
+ this._lastPong = Date.now();
17978
+ return;
17979
+ }
17980
+ default:
17981
+ return;
17982
+ }
17983
+ }
17984
+
17985
+ async _connect() {
17986
+ const generation = ++this._generation;
17987
+ let ticket;
17988
+ try {
17989
+ ticket = await requestTicket(this.table, this.id);
17990
+ } catch (err) {
17991
+ if (generation !== this._generation || this._stopped) return;
17992
+ if (err.retryable) return this._scheduleRetry();
17993
+ return this._finish(err);
17994
+ }
17995
+ if (generation !== this._generation || this._stopped) return;
17996
+ this._bye = null;
17997
+ const socket = new WebSocket(connectUrl(ticket));
17998
+ this._socket = socket;
17999
+ this._lastPong = Date.now();
18000
+ socket.onmessage = (message) => {
18001
+ if (generation !== this._generation) return;
18002
+ if (message.data === PONG_FRAME) { this._lastPong = Date.now(); return; }
18003
+ let frame = null;
18004
+ try { frame = JSON.parse(message.data); } catch (_) { return; }
18005
+ this._onFrame(frame);
18006
+ };
18007
+ let closed = false;
18008
+ const onGone = () => {
18009
+ if (closed || generation !== this._generation) return;
18010
+ closed = true;
18011
+ this._socket = null;
18012
+ if (this._ping !== null) { clearInterval(this._ping); this._ping = null; }
18013
+ if (this._renew !== null) { clearInterval(this._renew); this._renew = null; }
18014
+ if (this._stopped) return;
18015
+ const finalCode = this._bye && FINAL_BYE[this._bye];
18016
+ if (finalCode) {
18017
+ return this._finish(roomError(finalCode, finalCode === 'ROOM_FULL' ? 'This room is full.' : 'This room\\'s row was deleted.'));
18018
+ }
18019
+ this._setStatus('reconnecting', { code: this._bye || 'dropped' });
18020
+ // expired / app_updated rejoin at once with a fresh ticket; a drop backs off.
18021
+ if (this._bye === 'expired' || this._bye === 'app_updated') this._connect();
18022
+ else this._scheduleRetry();
18023
+ };
18024
+ socket.onclose = onGone;
18025
+ socket.onerror = onGone;
18026
+ socket.onopen = () => {
18027
+ if (generation !== this._generation) return;
18028
+ this._ping = setInterval(() => {
18029
+ if (Date.now() - this._lastPong > PING_MS * 2 + 5000) { try { socket.close(4000, 'no answer'); } catch (_) {} onGone(); return; }
18030
+ try { socket.send(PING_FRAME); } catch (_) {}
18031
+ }, PING_MS);
18032
+ this._renew = setInterval(() => this._renewTicket(generation), RENEW_MS);
18033
+ };
18034
+ }
18035
+
18036
+ // Every 4 minutes: a fresh ticket over the open connection. The row's read
18037
+ // rule is evaluated again each time; a refusal means access was removed and
18038
+ // the room closes the connection when the current ticket expires.
18039
+ async _renewTicket(generation) {
18040
+ try {
18041
+ const ticket = await requestTicket(this.table, this.id);
18042
+ if (generation === this._generation && this._socket && this._socket.readyState === 1) {
18043
+ this._socket.send(JSON.stringify({ t: 'ticket', ticket: ticket }));
18044
+ }
18045
+ } catch (err) {
18046
+ if (!err.retryable) console.warn('[rooms] access to ' + this.table + ' ' + this.id + ' was not renewed: ' + err.code);
18047
+ }
18048
+ }
18049
+
18050
+ _scheduleRetry() {
18051
+ if (this._stopped || this._retry !== null) return;
18052
+ this._setStatus('reconnecting', { code: 'dropped' });
18053
+ const delay = Math.min(500 * Math.pow(2, this._failures), 30000) * (0.75 + Math.random() * 0.5);
18054
+ this._failures = Math.min(this._failures + 1, 6);
18055
+ this._retry = setTimeout(() => { this._retry = null; this._connect(); }, delay);
18056
+ }
18057
+
18058
+ _finish(err) {
18059
+ this._stopped = true;
18060
+ this._generation++;
18061
+ this._clearTimers();
18062
+ this._failUnanswered(err.code);
18063
+ this._setStatus('closed', { code: err.code, error: err });
18064
+ if (this._firstJoin) { const done = this._firstJoin; this._firstJoin = null; done.reject(err); }
18065
+ }
18066
+
18067
+ _start() {
18068
+ return new Promise((resolve, reject) => {
18069
+ this._firstJoin = { resolve: resolve, reject: reject };
18070
+ if (typeof window !== 'undefined') {
18071
+ window.addEventListener('online', () => {
18072
+ if (!this._stopped && this._retry !== null) { clearTimeout(this._retry); this._retry = null; this._connect(); }
18073
+ });
18074
+ }
18075
+ this._connect();
18076
+ });
18077
+ }
18078
+ }
18079
+
18080
+ export async function joinRoom(table, id) {
18081
+ if (typeof table !== 'string' || !table) throw new TypeError('joinRoom(table, id): table is the name of a table that declares rooms');
18082
+ if (!(typeof id === 'string' && id) && !Number.isSafeInteger(id)) throw new TypeError('joinRoom(table, id): id is the row id');
18083
+ return new Room(table, id)._start();
18084
+ }
18085
+ `.trim();
18086
+ var ROOMS_DOOR_RUNTIME_JS = String.raw`
18087
+ const __SW_ROOMS_CLIENT_MODULE = ${JSON.stringify(ROOMS_CLIENT_MODULE_JS)};
18088
+ function __sw_roomsDoorMatch(url) {
18089
+ if (url.pathname !== '/__sw/rooms/ticket' && url.pathname !== '/__sw/rooms/client.js') return null;
18090
+ return { path: '/__sw/rooms', params: {}, load: async () => ({ default: (request, sw) => __sw_handleRoomsDoor(request, sw) }) };
18091
+ }
18092
+ async function __sw_handleRoomsDoor(request, sw) {
18093
+ const url = new URL(request.url);
18094
+ if (url.pathname === '/__sw/rooms/client.js') {
18095
+ if (request.method !== 'GET' && request.method !== 'HEAD') __sw_dataFail(405, 'METHOD_NOT_ALLOWED', 'Use GET /__sw/rooms/client.js.');
18096
+ return new Response(request.method === 'HEAD' ? null : __SW_ROOMS_CLIENT_MODULE, {
18097
+ status: 200,
18098
+ headers: { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'public, max-age=300' },
18099
+ });
18100
+ }
18101
+ if (__sw_artifactExecution !== 'standard') {
18102
+ __sw_dataFail(409, 'ROOMS_DRAFT_UNAVAILABLE', 'Rooms work on the live app only, not in a preview.');
18103
+ }
18104
+ if (request.method !== 'POST') __sw_dataFail(405, 'METHOD_NOT_ALLOWED', 'Use POST /__sw/rooms/ticket.');
18105
+ const origin = request.headers.get('origin');
18106
+ if (!origin) __sw_dataFail(400, 'ORIGIN_REQUIRED', 'Room requests require the app Origin header.');
18107
+ if (origin !== url.origin) __sw_dataFail(403, 'ROOM_ORIGIN_FORBIDDEN', 'Room requests must come from this app origin.');
18108
+ const input = await __sw_dataReadBody(request);
18109
+ if (!input || typeof input !== 'object' || Array.isArray(input)) __sw_dataFail(400, 'VALIDATION_ERROR', 'Send { table, id }.');
18110
+ for (const key of Object.keys(input)) {
18111
+ if (key !== 'table' && key !== 'id') __sw_dataFail(400, 'VALIDATION_ERROR', 'A ticket request takes only table and id; ' + key + ' is not accepted.');
18112
+ }
18113
+ let data;
18114
+ try {
18115
+ data = await __sw_roomsDoor.get(sw.rooms).ticket(input.table, input.id);
18116
+ } catch (err) {
18117
+ if (err && typeof err.status === 'number' && err.status >= 400 && err.status < 500) err.__sw_expose = true;
18118
+ throw err;
18119
+ }
18120
+ return new Response(JSON.stringify({ ok: true, data: data }), {
18121
+ status: 200,
18122
+ headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
18123
+ });
18124
+ }
18125
+ `;
18126
+
17527
18127
  // worker/src/utils/function-trace-source.ts
17528
18128
  var FUNCTION_TRACE_SOURCE = String.raw`
17529
18129
  /** The trace id for this invocation, or null when tracing did not initialize. */
@@ -18655,9 +19255,17 @@ globalThis.sw.endpoint = function (config) {
18655
19255
  try { user = await sw.auth.fromRequest(request); } catch (_) { /* swallow */ }
18656
19256
  }
18657
19257
 
18658
- // Body validation (skipped on GET/DELETE/HEAD \u2014 no body expected).
19258
+ // Body validation. A declared schema means the handler always gets the
19259
+ // validated body: GET/HEAD cannot carry one and are refused with 405;
19260
+ // every other method must send valid JSON (tsk_9a9b1a31).
18659
19261
  var body = null;
18660
- if (bodySchema && request.method !== 'GET' && request.method !== 'DELETE' && request.method !== 'HEAD') {
19262
+ if (bodySchema && (request.method === 'GET' || request.method === 'HEAD')) {
19263
+ return __sw_mergeHeaders(
19264
+ __sw_jsonError(405, 'METHOD_NOT_ALLOWED', request.method + ' is not supported: this endpoint declares a body schema, so it accepts a JSON body with POST, PUT, PATCH or DELETE. Answer GET from its own export const GET handler in the same file.'),
19265
+ Object.assign({ Allow: 'POST, PUT, PATCH, DELETE, OPTIONS' }, corsHeaders)
19266
+ );
19267
+ }
19268
+ if (bodySchema) {
18661
19269
  try { body = await request.json(); }
18662
19270
  catch (_) {
18663
19271
  return __sw_mergeHeaders(
@@ -25803,6 +26411,59 @@ function declaredScopeIdentityColumns(scope) {
25803
26411
  const collect = (policy) => policy.kind === "owner" ? [policy.column] : policy.kind === "member" ? [...policy.group] : policy.kind === "any_of" ? policy.policies.flatMap(collect) : policy.kind === "all_of" ? [...collect(policy.gate), ...collect(policy.who)] : policy.kind === "group" ? [policy.column] : policy.kind === "app_role" ? [] : [policy.via];
25804
26412
  return [...new Set(collect(scope.policy))];
25805
26413
  }
26414
+ var ROOM_REFEREE_PATH = /^\/api\/[A-Za-z0-9_\-]+(?:\/[A-Za-z0-9_\-.]+)*$/;
26415
+ function readRoomsOption(r, rawName, line) {
26416
+ r.expectPunct("{", `opening the rooms option of table "${rawName}", which takes { save?: 'column', referee?: '/api/path' }`);
26417
+ const out = { line };
26418
+ while (!r.tryPunct("}")) {
26419
+ const opt = r.readKey(`for an option of rooms on table "${rawName}"`);
26420
+ if (opt.name !== "save" && opt.name !== "referee") {
26421
+ throw new SchemaTsError(`line ${opt.line}: rooms on table "${rawName}" has an unknown option "${opt.name}". Allowed: save, referee.`);
26422
+ }
26423
+ if (out[opt.name]) throw new SchemaTsError(`line ${opt.line}: rooms on table "${rawName}" declares ${opt.name} twice.`);
26424
+ r.expectPunct(":", `after rooms.${opt.name}`);
26425
+ const t = r.next();
26426
+ if (t.kind !== "string") throw new SchemaTsError(`line ${t.line}: rooms.${opt.name} on table "${rawName}" must be a quoted literal string.`);
26427
+ out[opt.name] = { value: t.value, line: t.line };
26428
+ if (!r.tryPunct(",")) {
26429
+ r.expectPunct("}", `closing the rooms option of table "${rawName}"`);
26430
+ break;
26431
+ }
26432
+ }
26433
+ return out;
26434
+ }
26435
+ function validateRoomsOption(input, rawName, nameLine, columns, scope, client, relations) {
26436
+ if (columns.filter((c) => c.helper === "id").length !== 1) {
26437
+ throw new SchemaTsError(`line ${input.line}: table "${rawName}" declares rooms, which need exactly one id() column: a room is attached to one row by its id.`);
26438
+ }
26439
+ const out = {};
26440
+ if (input.save) {
26441
+ const name = input.save.value.toLowerCase();
26442
+ const column = columns.find((c) => c.name === name);
26443
+ if (!column) throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${input.save.value}", which is not one of its declared columns.`);
26444
+ if (column.helper !== "json") throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which must be a json() column: the room saves its whole state there.`);
26445
+ if (declaredScopeIdentityColumns(scope).includes(name) || declaredOwnerColumn(scope) === name) {
26446
+ throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which the table's access rule reads; the room's state can never decide who may see the row.`);
26447
+ }
26448
+ if (relations.some((rel) => rel.kind === "belongsTo" && rel.fk === name)) {
26449
+ throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which is a relation key.`);
26450
+ }
26451
+ const writable = [...client?.create ?? [], ...client?.update ?? [], ...client?.intake?.fields ?? []];
26452
+ if (writable.includes(name)) {
26453
+ throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which is browser-writable through client.create, client.update or client.intake. The room is the only writer of its save column; remove it from those lists.`);
26454
+ }
26455
+ out.save = name;
26456
+ }
26457
+ if (input.referee) {
26458
+ const path = input.referee.value;
26459
+ if (!ROOM_REFEREE_PATH.test(path) || path.length > 200 || path.split("/").some((part) => part === "." || part === "..")) {
26460
+ throw new SchemaTsError(`line ${input.referee.line}: rooms.referee on table "${rawName}" must be the path of one of the app's own functions, such as '/api/game-room'.`);
26461
+ }
26462
+ out.referee = path;
26463
+ }
26464
+ void nameLine;
26465
+ return out;
26466
+ }
25806
26467
  var COLUMN_HELPERS = /* @__PURE__ */ new Set([
25807
26468
  "id",
25808
26469
  "text",
@@ -26679,6 +27340,7 @@ function readTable(r, rawName, nameLine) {
26679
27340
  let relations = [];
26680
27341
  let relationsDeclared = false;
26681
27342
  let clientInput;
27343
+ let roomsInput;
26682
27344
  if (r.tryPunct(",")) {
26683
27345
  r.expectPunct("{", `opening the options of table "${rawName}"`);
26684
27346
  while (!r.tryPunct("}")) {
@@ -26703,9 +27365,12 @@ function readTable(r, rawName, nameLine) {
26703
27365
  } else if (key.name === "client") {
26704
27366
  if (clientInput) throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "client" twice.`);
26705
27367
  clientInput = readClientPermissions(r);
27368
+ } else if (key.name === "rooms") {
27369
+ if (roomsInput) throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "rooms" twice.`);
27370
+ roomsInput = readRoomsOption(r, rawName, key.line);
26706
27371
  } else {
26707
27372
  throw new SchemaTsError(
26708
- `line ${key.line}: table "${rawName}" has an unknown option "${key.name}". Allowed: scope, indexes, unique, relations, client.`
27373
+ `line ${key.line}: table "${rawName}" has an unknown option "${key.name}". Allowed: scope, indexes, unique, relations, client, rooms.`
26709
27374
  );
26710
27375
  }
26711
27376
  if (!r.tryPunct(",")) {
@@ -26832,7 +27497,8 @@ function readTable(r, rawName, nameLine) {
26832
27497
  }
26833
27498
  client = parsed.permissions;
26834
27499
  }
26835
- return { kind: "table", table: { name, scope, relations, columns, indexes, uniques, removedColumns: [...removedColumns].sort(), ...client ? { client } : {} } };
27500
+ const rooms = roomsInput ? validateRoomsOption(roomsInput, rawName, nameLine, columns, scope, client, relations) : void 0;
27501
+ return { kind: "table", table: { name, scope, relations, columns, indexes, uniques, removedColumns: [...removedColumns].sort(), ...client ? { client } : {}, ...rooms ? { rooms } : {} } };
26836
27502
  }
26837
27503
  function extractSchemaTs(source, options = {}) {
26838
27504
  if (typeof source !== "string" || source.trim().length === 0) {