@somewhere-cloud/cli 0.38.86 → 0.38.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/commands/deploy.js +19 -8
  3. package/dist/commands/deploy.js.map +1 -1
  4. package/dist/commands/docs.js +4 -3
  5. package/dist/commands/docs.js.map +1 -1
  6. package/dist/lib/app-test.d.ts +125 -0
  7. package/dist/lib/app-test.js +267 -0
  8. package/dist/lib/app-test.js.map +1 -0
  9. package/dist/lib/deploy-tests.d.ts +6 -0
  10. package/dist/lib/deploy-tests.js +13 -4
  11. package/dist/lib/deploy-tests.js.map +1 -1
  12. package/dist/lib/form-auth.d.ts +83 -0
  13. package/dist/lib/form-auth.js +350 -0
  14. package/dist/lib/form-auth.js.map +1 -0
  15. package/dist/lib/init-agent-guide.d.ts +2 -2
  16. package/dist/lib/init-agent-guide.js +61 -84
  17. package/dist/lib/init-agent-guide.js.map +1 -1
  18. package/dist/lib/init-feature-template.js +10 -10
  19. package/dist/lib/init-green-template.js +0 -3
  20. package/dist/lib/init-green-template.js.map +1 -1
  21. package/dist/lib/init-test-template.d.ts +1 -1
  22. package/dist/lib/init-test-template.js +55 -139
  23. package/dist/lib/init-test-template.js.map +1 -1
  24. package/dist/lib/init-ui-kit.d.ts +2 -2
  25. package/dist/lib/init-ui-kit.js +2 -2
  26. package/dist/lib/playwright-fixtures.d.ts +10 -45
  27. package/dist/lib/playwright-fixtures.js +59 -328
  28. package/dist/lib/playwright-fixtures.js.map +1 -1
  29. package/dist/lib/test-reporter.d.ts +3 -1
  30. package/dist/lib/test-reporter.js +31 -50
  31. package/dist/lib/test-reporter.js.map +1 -1
  32. package/dist/lib/test-run.d.ts +1 -0
  33. package/dist/lib/test-run.js +14 -17
  34. package/dist/lib/test-run.js.map +1 -1
  35. package/dist/script.d.ts +3 -0
  36. package/dist/script.js +4 -0
  37. package/dist/script.js.map +1 -0
  38. package/npm-shrinkwrap.json +2 -2
  39. package/package.json +6 -2
  40. package/dist/lib/test-ledger.d.ts +0 -73
  41. package/dist/lib/test-ledger.js +0 -261
  42. package/dist/lib/test-ledger.js.map +0 -1
@@ -0,0 +1,350 @@
1
+ import { messagesAfter } from './test-identities.js';
2
+ import { rememberSecrets, scrub } from './test-diagnostics.js';
3
+ import { mark as timelineMark, span } from './test-timeline.js';
4
+ import { admitReservedAddress, generatedAddress, generatedPassword, recordAttempt, recordId } from './form-accounts.js';
5
+ export const FIND_MS = 5_000;
6
+ export const DEFAULT_FORM = {
7
+ email: '[data-sw-auth="email"]', password: '[data-sw-auth="password"]',
8
+ signUp: '[data-sw-auth="sign-up"]', signIn: '[data-sw-auth="sign-in"]',
9
+ mode: '[data-sw-auth="mode"]', signOut: '[data-sw-auth="sign-out"]',
10
+ };
11
+ const pick = (page, control) => typeof control === 'string' ? page.locator(control) : control(page);
12
+ const describe = (control) => typeof control === 'string' ? control : 'your locator';
13
+ /** Wait for the starter's session check to settle (data-app-state on the app root, outside any
14
+ * form). 'ready' is either state; a Locator waits for that element instead. */
15
+ export async function ready(page, state = 'ready') {
16
+ const locator = typeof state === 'string' ? page.locator(state === 'ready' ? '[data-app-state="signed-in"], [data-app-state="signed-out"]' : `[data-app-state="${state}"]`) : state;
17
+ await span('ready', { state: typeof state === 'string' ? state : 'locator' }, () => locator.waitFor({ state: 'visible' }));
18
+ }
19
+ /** The auth state, when the app publishes it; an app without data-app-state is not waited on. */
20
+ async function authState(page, state) {
21
+ if (!(await page.locator('[data-app-state]').count()))
22
+ return;
23
+ await page.locator(`[data-app-state="${state}"]`).waitFor({ state: 'visible', timeout: 15_000 });
24
+ }
25
+ async function signedIn(page, form) {
26
+ if (form?.signedIn)
27
+ await pick(page, form.signedIn).first().waitFor({ state: 'visible', timeout: 15_000 });
28
+ else
29
+ await authState(page, 'signed-in');
30
+ }
31
+ /** Open the page that shows the form and wait until the app says who is signed in. */
32
+ async function openSignedOut(page, form) {
33
+ await page.goto(form?.path ?? '/');
34
+ const root = page.locator('[data-app-state]');
35
+ // Whichever comes first: the app's session state (the starter publishes it) or the form itself.
36
+ await root.or(pick(page, form?.email ?? DEFAULT_FORM.email)).first().waitFor({ state: 'attached', timeout: FIND_MS }).catch(() => { });
37
+ if (await root.count()) {
38
+ await page.locator('[data-app-state="signed-in"], [data-app-state="signed-out"]').waitFor({ state: 'visible', timeout: 15_000 });
39
+ if (await page.locator('[data-app-state="signed-in"]').count())
40
+ throw new Error('this page is already signed in; call signOut(page) first or use another page');
41
+ }
42
+ }
43
+ /** Fill and submit the form for one action, found by what each control does. */
44
+ async function submitForm(page, action, input, form = {}) {
45
+ const f = { ...DEFAULT_FORM, ...form };
46
+ const wanted = pick(page, action === 'sign-up' ? f.signUp : f.signIn).first();
47
+ const missing = (what, control) => new StepError(`${action === 'sign-up' ? 'signUp' : 'signIn'}: no ${what} (${describe(control)}) on ${form.path ?? '/'} within ${FIND_MS / 1000} s. `
48
+ + 'Mark your form\'s controls with data-sw-auth="email", "password", "sign-up" and "sign-in" (and "mode" if one control switches between them), '
49
+ + 'or pass { form: { email, password, signUp, signIn } } with your own selectors.');
50
+ await pick(page, f.email).first().waitFor({ state: 'visible', timeout: FIND_MS }).catch(() => { throw missing('email field', f.email); });
51
+ if (!(await wanted.isVisible())) {
52
+ // Starters before 0.38.88: one submit button, and the form's current mode on data-sw-auth-mode.
53
+ const legacy = page.locator('[data-sw-auth="form"][data-sw-auth-mode]');
54
+ if (!form.signUp && !form.signIn && await legacy.count() && await page.locator('[data-sw-auth="submit"]').count()) {
55
+ if ((await legacy.first().getAttribute('data-sw-auth-mode')) !== action) {
56
+ await pick(page, f.mode).first().click();
57
+ await page.locator(`[data-sw-auth="form"][data-sw-auth-mode="${action}"]`).waitFor({ timeout: FIND_MS });
58
+ }
59
+ await pick(page, f.email).first().fill(input.email);
60
+ await pick(page, f.password).first().fill(input.password);
61
+ await page.locator('[data-sw-auth="submit"]').first().click();
62
+ return;
63
+ }
64
+ // One action at a time: the mode control reveals the other.
65
+ const mode = pick(page, f.mode).first();
66
+ if (await mode.isVisible())
67
+ await mode.click();
68
+ await wanted.waitFor({ state: 'visible', timeout: FIND_MS }).catch(() => { throw missing(`${action} action`, action === 'sign-up' ? f.signUp : f.signIn); });
69
+ }
70
+ await pick(page, f.email).first().fill(input.email);
71
+ const password = pick(page, f.password).first();
72
+ await password.waitFor({ state: 'visible', timeout: FIND_MS }).catch(() => { throw missing('password field', f.password); });
73
+ await password.fill(input.password);
74
+ await wanted.click();
75
+ }
76
+ // ---------------------------------------------------------------- sign-up through the app's form
77
+ //
78
+ // signUp/verify/signIn/signOut drive the app's own pages. The developer credential stays in this
79
+ // process and is used only on the control plane: to read the captured code for the exact address
80
+ // (GET /email/test-inbox) and to delete the exact account ids this test created. The browser and
81
+ // the app only ever see the person's own email, password and code, typed into the app's form.
82
+ const marks = new WeakMap();
83
+ /** When the last emailed sign-in code for a person was read (the platform sends at most one a minute). */
84
+ const lastSignInCode = new WeakMap();
85
+ const CODE_GAP_MS = 61_000;
86
+ class StepError extends Error {
87
+ }
88
+ const hook = (page, name) => page.locator(`[data-sw-auth="${name}"]`);
89
+ async function pageSays(page) {
90
+ if (page.isClosed())
91
+ return '';
92
+ try {
93
+ const text = await page.locator('[data-sw-auth="error"], [role="alert"]').first().textContent({ timeout: 500 });
94
+ return scrub((text ?? '').trim()).slice(0, 300);
95
+ }
96
+ catch {
97
+ return '';
98
+ }
99
+ }
100
+ /** Run one named step; a failure says which step, what the page showed, and the cause, scrubbed. */
101
+ async function step(page, name, work) {
102
+ try {
103
+ return await span(name, {}, work);
104
+ }
105
+ catch (error) {
106
+ if (error instanceof StepError)
107
+ throw error;
108
+ const said = await pageSays(page);
109
+ const cause = scrub(error instanceof Error ? error.message : String(error)).slice(0, 600);
110
+ throw new StepError(`${name} failed${said ? `; the page says "${said}"` : ''}: ${cause}`);
111
+ }
112
+ }
113
+ async function enterStarterCode(page, code) {
114
+ await hook(page, 'mfa-code').fill(code);
115
+ await hook(page, 'mfa-submit').click();
116
+ }
117
+ /** The app's own auth response (the packaged /api/auth route or any route ending the same way). */
118
+ function authResponse(page, origin, suffix) {
119
+ return page.waitForResponse((response) => {
120
+ if (response.request().method() !== 'POST')
121
+ return false;
122
+ const url = new URL(response.url());
123
+ return url.origin === origin && url.pathname.endsWith(suffix);
124
+ }, { timeout: 30_000 }).catch((error) => error instanceof Error ? error : new Error(String(error)));
125
+ }
126
+ async function outcome(pending, what) {
127
+ const response = await pending;
128
+ if (response instanceof Error)
129
+ throw new Error(`no ${what} response from the app within 30 s (${scrub(response.message.split('\n')[0])})`);
130
+ let body = null;
131
+ try {
132
+ body = await response.json();
133
+ }
134
+ catch { /* not JSON */ }
135
+ const data = (body?.data && typeof body.data === 'object' ? body.data : body);
136
+ const user = data?.user;
137
+ const raw = typeof body?.error === 'string' ? body.error : typeof body?.code === 'string' ? body.code : '';
138
+ return { ok: response.ok(), status: response.status(), code: /^[A-Z_]+$/.test(raw) ? raw : 'none',
139
+ id: typeof user?.id === 'string' && user.id ? user.id : null, mfa: data?.mfa_required === true };
140
+ }
141
+ async function inbox(run, address, wait) {
142
+ const { client, projectId } = await run.control();
143
+ const body = await run.timed('test inbox', () => client.call('GET', '/email/test-inbox', undefined, { project_id: projectId, address, limit: 20, ...(wait ? { wait_ms: wait.ms ?? 10_000, since: wait.since } : {}) }));
144
+ return messagesAfter(body.messages, address, 0);
145
+ }
146
+ /** What the test inbox already holds for this address, so a code is only ever one sent after this point. */
147
+ async function inboxMark(run, address) {
148
+ const messages = await inbox(run, address);
149
+ return { seen: new Set(messages.map(message => message.id)), since: Math.max(0, ...messages.map(message => Date.parse(message.created_at))) };
150
+ }
151
+ /** Codes in messages to exactly this address that arrived after the mark, newest first, consumed
152
+ * from the mark. One long-poll of at most `ms`. */
153
+ async function takeCodes(run, address, mark, ms) {
154
+ const fresh = (await inbox(run, address, { since: mark.since, ms })).filter(message => !mark.seen.has(message.id));
155
+ for (const message of fresh) {
156
+ mark.seen.add(message.id);
157
+ mark.since = Math.max(mark.since, Date.parse(message.created_at));
158
+ }
159
+ const codes = fresh.flatMap(message => message.verification_code ? [message.verification_code] : []);
160
+ rememberSecrets(...codes);
161
+ return codes;
162
+ }
163
+ /** Like takeCodes, waiting up to 25 s for at least one. */
164
+ async function freshCodes(run, address, mark, what) {
165
+ const deadline = Date.now() + 25_000;
166
+ for (;;) {
167
+ const codes = await takeCodes(run, address, mark, 10_000);
168
+ if (codes.length)
169
+ return codes;
170
+ if (Date.now() > deadline)
171
+ throw new Error(`${what}: no code reached the project's test inbox for ${address} within 25 s. The test inbox holds at most a limited number of messages for 7 days; when it is full, new mail is not stored.`);
172
+ }
173
+ }
174
+ export async function signUp(run, page, options) {
175
+ if (options.domain !== undefined && options.email !== undefined)
176
+ throw new Error('signUp: pass domain or email, not both.');
177
+ const email = options.email !== undefined ? admitReservedAddress(options.email) : generatedAddress(options.domain);
178
+ const password = generatedPassword();
179
+ rememberSecrets(password);
180
+ run.allowTime(20_000);
181
+ run.pages.add(page);
182
+ const { target, projectId } = await run.control();
183
+ const mark = await inboxMark(run, email);
184
+ const attempt = { email, record: recordAttempt(run.root, projectId, email), id: null, submitted: false, refused: false };
185
+ run.attempts.push(attempt);
186
+ const onRequest = (request) => {
187
+ if (request.method() === 'POST' && new URL(request.url()).pathname.endsWith('/auth/signup'))
188
+ attempt.submitted = true;
189
+ };
190
+ page.on('request', onRequest);
191
+ const signedUp = authResponse(page, target.origin, '/auth/signup');
192
+ try {
193
+ await step(page, 'signUp: fill and submit the sign-up form', async () => {
194
+ await openSignedOut(page, options.form);
195
+ if (options.steps)
196
+ await options.steps(page, { email, password });
197
+ else
198
+ await submitForm(page, 'sign-up', { email, password }, options.form);
199
+ });
200
+ const result = await step(page, 'signUp: wait for the sign-up response', () => outcome(signedUp, 'sign-up'));
201
+ if (!result.ok) {
202
+ // Only "already registered" proves nothing was created. Any other failure can come after the
203
+ // platform committed the account (the app's own route failing late), so it is reported at
204
+ // cleanup as possibly existing, never assumed absent and never deleted by address.
205
+ const exists = result.status === 409 || result.code === 'AUTH_EMAIL_EXISTS';
206
+ attempt.refused = exists;
207
+ const said = await pageSays(page);
208
+ throw new StepError(exists
209
+ ? `signUp: ${email} is already registered in this project. signUp never uses, resets or deletes an existing account; choose another address.`
210
+ : `signUp: the app answered the sign-up with HTTP ${result.status} ${result.code}${said ? `; the page says "${said}"` : ''}`);
211
+ }
212
+ let id = result.id;
213
+ let verified = false;
214
+ if (result.mfa) {
215
+ // The project requires emailed sign-in codes: the first code goes to the new address, and
216
+ // entering it verifies that address and signs the person in.
217
+ const [code] = await step(page, 'signUp: read the emailed sign-up code', () => freshCodes(run, email, mark, 'signUp'));
218
+ const challenged = authResponse(page, target.origin, '/auth/mfa/challenge');
219
+ await step(page, 'signUp: enter the emailed sign-up code', () => (options.codeSteps ?? enterStarterCode)(page, code));
220
+ const done = await step(page, 'signUp: wait for the code step response', () => outcome(challenged, 'sign-up code'));
221
+ if (!done.ok)
222
+ throw new StepError(`signUp: the app refused the emailed code (HTTP ${done.status} ${done.code})`);
223
+ id = done.id;
224
+ verified = true;
225
+ }
226
+ if (!id)
227
+ throw new StepError('signUp: the sign-up succeeded but its response carried no account id, so the account cannot be cleaned up by id');
228
+ attempt.id = id;
229
+ recordId(attempt.record, id);
230
+ await step(page, 'signUp: wait for the signed-in page', () => signedIn(page, options.form));
231
+ await run.attach(page);
232
+ const person = { id, email, password, verified };
233
+ marks.set(person, mark);
234
+ if (result.mfa)
235
+ lastSignInCode.set(person, Date.now());
236
+ return person;
237
+ }
238
+ finally {
239
+ page.off('request', onRequest);
240
+ }
241
+ }
242
+ export async function verify(run, page, person) {
243
+ run.allowTime(20_000);
244
+ await run.attach(page);
245
+ const mark = marks.get(person) ?? await inboxMark(run, person.email);
246
+ // A code the project sent at sign-up is used if it is already there (or arrives within 2 s);
247
+ // otherwise ask the app for one, as its own verify-email step does.
248
+ let codes = await step(page, 'verify: read a code sent at sign-up', () => takeCodes(run, person.email, mark, 2_000));
249
+ if (!codes.length) {
250
+ const sent = await step(page, 'verify: ask the app to email a code', () => page.request.post('/api/auth/request-email-verification', { data: {} }));
251
+ if (!sent.ok())
252
+ throw new StepError(`verify: the app did not send a code (HTTP ${sent.status()} ${await errorCode(sent)})`);
253
+ codes = await step(page, 'verify: read the emailed code', () => freshCodes(run, person.email, mark, 'verify'));
254
+ }
255
+ let last = '';
256
+ for (const code of codes) {
257
+ // The platform stores the captured message just before it installs the code, so for a moment
258
+ // the code can read as "no pending verification" (404). Only that answer is retried, briefly;
259
+ // a wrong or expired code (401/400) is never retried.
260
+ let confirmed = await step(page, 'verify: enter the code in the app', () => page.request.post('/api/auth/verify-email', { data: { code } }));
261
+ for (let wait = 0; confirmed.status() === 404 && wait < 8; wait++) {
262
+ timelineMark('wait', { ms: 250, why: 'verify: code not installed yet (404)' });
263
+ await new Promise(resolve => setTimeout(resolve, 250));
264
+ confirmed = await step(page, 'verify: enter the code in the app', () => page.request.post('/api/auth/verify-email', { data: { code } }));
265
+ }
266
+ if (confirmed.ok()) {
267
+ const state = await page.request.get('/api/auth/verify-email');
268
+ if (state.ok() && (await state.json()).email_verified === true) {
269
+ person.verified = true;
270
+ return;
271
+ }
272
+ throw new StepError(`verify: the app accepted the code but still reports ${person.email} as unverified (HTTP ${state.status()})`);
273
+ }
274
+ last = `HTTP ${confirmed.status()} ${await errorCode(confirmed)}`;
275
+ }
276
+ throw new StepError(`verify: the app refused the emailed code (${last})`);
277
+ }
278
+ async function errorCode(response) {
279
+ try {
280
+ const body = await response.json();
281
+ return typeof body.error === 'string' && /^[A-Z_]+$/.test(body.error) ? body.error : 'none';
282
+ }
283
+ catch {
284
+ return 'none';
285
+ }
286
+ }
287
+ export async function signIn(run, page, person, options) {
288
+ rememberSecrets(person.password);
289
+ run.allowTime(20_000);
290
+ run.pages.add(page);
291
+ const { target } = await run.control();
292
+ const mark = await inboxMark(run, person.email);
293
+ const submit = async () => {
294
+ const signedIn = authResponse(page, target.origin, '/auth/login');
295
+ await step(page, 'signIn: fill and submit the sign-in form', async () => {
296
+ await openSignedOut(page, options.form);
297
+ if (options.steps)
298
+ await options.steps(page, { email: person.email, password: person.password });
299
+ else
300
+ await submitForm(page, 'sign-in', person, options.form);
301
+ });
302
+ return step(page, 'signIn: wait for the sign-in response', () => outcome(signedIn, 'sign-in'));
303
+ };
304
+ let result = await submit();
305
+ // A project that requires email codes sends at most one code per account per minute. Signing back
306
+ // in within a minute of the last code is refused (429) before a code is sent, so wait out the rest
307
+ // of that minute, as the person would, and submit once more.
308
+ if (result.status === 429 && (result.code === 'AUTH_MFA_SEND_LIMITED' || /code was sent recently/i.test(await pageSays(page)))) {
309
+ const wait = Math.max(0, CODE_GAP_MS - (Date.now() - (lastSignInCode.get(person) ?? 0)));
310
+ const waitMs = Math.min(wait, CODE_GAP_MS);
311
+ run.allowTime(waitMs + 10_000);
312
+ timelineMark('wait', { ms: waitMs, why: 'signIn: one emailed code a minute' });
313
+ await page.waitForTimeout(waitMs);
314
+ result = await submit();
315
+ }
316
+ if (!result.ok) {
317
+ const said = await pageSays(page);
318
+ throw new StepError(`signIn: the app refused the sign-in (HTTP ${result.status} ${result.code})${said ? `; the page says "${said}"` : ''}`);
319
+ }
320
+ if (result.mfa) {
321
+ const [code] = await step(page, 'signIn: read the emailed sign-in code', () => freshCodes(run, person.email, mark, 'signIn'));
322
+ lastSignInCode.set(person, Date.now());
323
+ const challenged = authResponse(page, target.origin, '/auth/mfa/challenge');
324
+ await step(page, 'signIn: enter the emailed sign-in code', () => (options.codeSteps ?? enterStarterCode)(page, code));
325
+ result = await step(page, 'signIn: wait for the code step response', () => outcome(challenged, 'sign-in code'));
326
+ if (!result.ok)
327
+ throw new StepError(`signIn: the app refused the emailed code (HTTP ${result.status} ${result.code})`);
328
+ }
329
+ if (result.id && result.id !== person.id)
330
+ throw new StepError('signIn: the app signed in a different account than this person');
331
+ await step(page, 'signIn: wait for the signed-in page', () => signedIn(page, options.form));
332
+ await run.attach(page);
333
+ }
334
+ export async function signOut(run, page, options) {
335
+ run.pages.add(page);
336
+ await step(page, 'signOut', async () => {
337
+ if (options.steps)
338
+ await options.steps(page);
339
+ else {
340
+ const control = options.form?.signOut ?? DEFAULT_FORM.signOut;
341
+ const action = pick(page, control).first();
342
+ await action.waitFor({ state: 'visible', timeout: FIND_MS }).catch(() => {
343
+ throw new StepError(`signOut: no sign-out control (${describe(control)}) on this page within ${FIND_MS / 1000} s. Add data-sw-auth="sign-out" to it, or pass { form: { signOut: '<selector>' } }.`);
344
+ });
345
+ await action.click();
346
+ }
347
+ await authState(page, 'signed-out');
348
+ });
349
+ }
350
+ //# sourceMappingURL=form-auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"form-auth.js","sourceRoot":"","sources":["../../src/lib/form-auth.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAqB,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EAAE,IAAI,IAAI,YAAY,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AA6CxH,MAAM,CAAC,MAAM,OAAO,GAAG,KAAK,CAAC;AAC7B,MAAM,CAAC,MAAM,YAAY,GAAqD;IAC5E,KAAK,EAAE,wBAAwB,EAAE,QAAQ,EAAE,2BAA2B;IACtE,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,0BAA0B;IACtE,IAAI,EAAE,uBAAuB,EAAE,OAAO,EAAE,2BAA2B;CACpE,CAAC;AACF,MAAM,IAAI,GAAG,CAAC,IAAU,EAAE,OAAgB,EAAW,EAAE,CAAC,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAA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,EAAE,OAAO,IAAI,YAAY,CAAC,OAAO,CAAC;YAC9D,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,KAAK,EAAE,CAAC;YAC3C,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE;gBACtE,MAAM,IAAI,SAAS,CAAC,iCAAiC,QAAQ,CAAC,OAAO,CAAC,yBAAyB,OAAO,GAAG,IAAI,qFAAqF,CAAC,CAAC;YACtM,CAAC,CAAC,CAAC;YACH,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QACvB,CAAC;QACD,MAAM,SAAS,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -1,4 +1,4 @@
1
- export declare const AGENT_WORKFLOW = "## Build, deploy, test\n\nEnough to start a typical app: declare access and use the browser client; docs are for exceptions.\n\n| Requirement | Declaration below |\n| --- | --- |\n| Each user sees only their own rows | notes: owner() |\n| Team: owner adds members; members read/write; creator rights | teams/team_members/tasks: owner() + member(); role-owner delete branch |\n| Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain |\n| Public pages from private drafts | pages: conditional publicRead |\n| Share one record read-only | shared_notes/note_shares: read-only grant() |\n\ndb/schema.ts is declaration only: imports, constants/spreads, default schema;\nno helpers/expressions. id() is random text; owner() stamps user_id. client.read\nincludes the key. Inside anyOf(), owner() takes only column/read: it stamps the\ncreator, not create/delete options; member() gates placement (non-member create is\nrefused), while creators or the allowed branch can delete. Other fields: timestamp({ default: 'now' }), text({ nullable: true });\nindexes: [['team_id']].\n\n```ts\nimport { schema, table, id, text, owner, member, anyOf, serverOnly, parent, appRole, boolean, grant } from 'somewhere/db';\nexport default schema({\n notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },\n }),\n teams: table({ id: id(), name: text(), owner_id: text() }, {\n scope: member({ group: 'id', membership: 'team_members', member_user: 'user_id', member_group: 'team_id' }),\n client: { read: ['id', 'name'] },\n }),\n team_members: table({ id: id(), team_id: text(), user_id: text(), role: text() }, {\n scope: serverOnly(), unique: [['team_id', 'user_id']],\n }),\n tasks: table({ id: id(), team_id: text({ references: 'teams' }), title: text() }, {\n scope: anyOf(owner(), member({ group: 'team_id', membership: 'team_members',\n member_user: 'user_id', member_group: 'team_id', operations: ['read', 'create', 'update'] }),\n member({ group: 'team_id', membership: 'team_members', member_user: 'user_id',\n member_group: 'team_id', where: { role: 'owner' }, operations: ['delete'] })),\n client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },\n }),\n tickets: table({ id: id(), subject: text() }, {\n scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),\n client: { read: true, create: ['subject'], update: ['subject'] },\n }),\n messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: parent({ via: 'ticket_id' }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {\n scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],\n publicRead: { where: { published: true } } },\n }),\n note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {\n scope: owner(), unique: [['note_id', 'grantee_id']],\n }),\n shared_notes: table({ id: id(), title: text() }, {\n scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),\n client: { read: ['id', 'title'], create: ['title'], update: ['title'] },\n }),\n}, { appRoles: { staff: { emailDomain: 'staff.example' } } });\n```\n\nWho is staff is your app's decision; the platform enforces what the role may do.\nFirst choice, as above: emailDomain. The role holds once the person verifies an address\nat that domain; no grant code. An email ending alone proves nothing: anyone can sign up\nas anyone@your-domain without owning that mailbox. Without verification, grant only from\nsomething the visitor cannot choose, such as an invitation your app issued, checked inside\nthe sign-up route: somewhere docs sw.auth --section server-assigned-app-roles-setroles.\nmessages use parent(): owner() would hide staff replies from the customer.\nPublish pages in an owner-checked endpoint. Share with caller-scoped\nsw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.\nBrowser calls THROW, not { error }; catch below.\nBrowser list: max 100, paginate after; no order (sort locally or in an endpoint).\n\n```ts\nimport { data } from 'somewhere:data';\nexport async function save(title: string) {\n try { await data.notes.create({ title }); return null; }\n catch (e) { return e instanceof Error ? e.message : 'Save failed'; }\n}\nexport const list = (after?: string) => data.notes.list({ limit: 100, after });\n```\n\nTeams without verification: own membership table + member(); sw.groups and domain\nroles need VERIFIED emails. Members read/create/update tasks; creators or team owners delete while members.\nRestrictions narrow operations, not grant read.\nComment author or team owner deletes: declare it as tasks do (owner() plus member() where role owner, delete).\nCreate the team and its owner membership atomically:\n\n```ts\n// api/teams.ts\nexport default sw.endpoint({\n auth: 'required', body: { name: 'string' },\n handler: async ({ user, params, body }, sw) => {\n const id = crypto.randomUUID();\n await sw.db.server.tx([\n { op: 'insert', table: 'teams', values: { id, name: body.name, owner_id: user.id } },\n { op: 'insert', table: 'team_members', values: { id: crypto.randomUUID(), team_id: id, user_id: user.id, role: 'owner' } },\n ]);\n return { id, email: user.email };\n },\n});\n```\n\n```ts\n// api/teams/[id]/members.ts \u2014 only the team owner adds a member\nexport default sw.endpoint({\n auth: 'required', body: { email: 'string' },\n handler: async ({ user, params, body }, sw) => {\n const { data: teams } = await sw.db.from('teams', { where: { id: params.id, owner_id: user.id }, limit: 1 });\n if (!teams[0]) return Response.json({ error: 'Team owner required' }, { status: 403 });\n const { users: [target] } = await sw.auth.server.listUsers({ emails: [body.email] });\n if (!target) return Response.json({ error: 'Account not found' }, { status: 404 });\n await sw.db.server.insert('team_members', {\n id: crypto.randomUUID(), team_id: params.id, user_id: target.id, role: 'member',\n }, { onConflict: 'ignore' });\n return { ok: true };\n },\n});\n```\n\nDo not hand-write access to app-read/write data: declare who may read/write it.\nserverOnly() fits job/import/audit/counter state and protected membership ledgers.\nGrant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates\n(e.g. expiry) or per-role writable fields (split tables or check that write).\n\nBuild src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.\nAuth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.\napi/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;\nGET/DELETE: named exports.\n\n```ts\nexport const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });\n```\n\nsw.db applies caller scopes; sw.db.server bypasses them: authorize first.\nCaller-scoped sw.db.insert needs no client.create grant: client limits only the browser.\nReads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).\nFilter: { id: { in: ids } }; unique: [['a', 'b']] in schema.\nWrites: insert(table, values), update(table, { where, set }), remove(table, { where }).\ntx takes an ARRAY of write intents, never a callback; pre-generate related IDs.\n\nBrowser: fetch(path, { method: 'POST', credentials: 'same-origin',\nheaders: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).\nAccess cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts\nneed Origin equal to the app URL.\n\nPublish: npx @somewhere-cloud/cli deploy, then somewhere test for the rules you changed.\nOne somewhere test run drives the UI and calls the API: signUp(page) uses your sign-up form\n(then signOut, signIn with its password, verify with the emailed code), newUser() acts as\nseveral people, and ready(page, 'signed-in' | 'signed-out') waits for the session check.\nYou do not need a separate browser script.\nStart from the starter's tests/account, phone and access specs: one journey per test, its own people.\nOne somewhere test runs every spec, old and new together; somewhere deploy --test deploys, then runs them once.\nAfter fixing a test, run only what failed: somewhere test --failed (passed results on this release are kept).\nDo not rerun a suite that is already green on this release.\nDeploy raw source, no frontend build; type errors stop upload.\nnewUser() gives a signed-in page/API client; make people at once: await Promise.all([newUser(), newUser()]).\nnewUser({ role: 'staff' }) holds a role declared in appRoles, granted with your developer key.\nnewUser() takes no chosen email. Test users are verified and visible to this project's server user lookup.\nEmail-domain role: signUp(page, { domain: 'staff.example' }), then verify(page, person); newPage() for a second person.\nRefusals: await expectRefused(person, 'notes', { operation: 'update', id, values }, { allowed: owner }) or\nexpectRefused(person, 'POST /api/x', body, { allowed }). allowed is someone the same request succeeds for;\nan empty list, a null get or a 404 counts as refused only then. person/allowed: page, newUser() or anonymous.\nsomewhere test --phone runs every test again at 390x844.\nFor the complete owner-adds-member-by-email test and its endpoints, run\nsomewhere docs test and follow Two users sharing through the app.\nDiagnose with somewhere errors and somewhere logs.\n\nOn demand:\n- Server paging: `somewhere docs sw.db --section server-read-paging`\n\n## Testing shared access\n\nWith the teams and membership endpoints above, the owner adds a fixture by email\nand that fixture reads the shared team row:\n\n```ts\n// tests/team.spec.ts\nimport { test, expect, data } from '@somewhere-cloud/cli/testing';\ntest('owner adds a second user by email', async ({ newUser }) => {\n const owner = await newUser();\n const bob = await newUser();\n const name = `Shared team ${crypto.randomUUID()}`;\n const created = await owner.request.post('/api/teams', { data: { name } });\n expect(created.ok()).toBeTruthy();\n const { id } = await created.json();\n const added = await owner.request.post(`/api/teams/${id}/members`, { data: { email: bob.email } });\n expect(added.ok()).toBeTruthy();\n const response = await data(bob.request, 'teams', { operation: 'get', id });\n expect(response.ok()).toBeTruthy();\n expect((await response.json()).data).toMatchObject({ id, name });\n});\n```\n";
1
+ export declare const AGENT_WORKFLOW = "## Build, deploy, test\n\nEnough to start a typical app: declare access and use the browser client; docs are for exceptions.\n\n| Requirement | Declaration below |\n| --- | --- |\n| Each user sees only their own rows | notes: owner() |\n| Team: owner invites members; members read/write; creator or team owner deletes | tasks: anyOf(owner(), group()); sw.groups endpoints below |\n| Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain (or grantableBy) |\n| Public pages from private drafts | pages: conditional publicRead |\n| Share one record read-only | shared_notes/note_shares: read-only grant() |\n\ndb/schema.ts is declaration only: imports, constants/spreads, default schema;\nno helpers/expressions. id() is random text; owner() stamps user_id. client.read\nincludes the key. Inside anyOf(), owner() takes only column/read: it stamps the\ncreator, not create/delete options; group() gates placement (non-member create is\nrefused); inside anyOf an operation missing from roles allows no group role. Other fields: timestamp({ default: 'now' }), text({ nullable: true });\nindexes: [['team_id']].\n\n```ts\nimport { schema, table, id, text, owner, group, anyOf, parent, appRole, boolean, grant } from 'somewhere/db';\nexport default schema({\n notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },\n }),\n tasks: table({ id: id(), team_id: text(), title: text() }, {\n scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['owner', 'admin', 'member'],\n create: ['owner', 'admin', 'member'], update: ['owner', 'admin', 'member'], delete: ['owner'] } })),\n client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },\n }),\n tickets: table({ id: id(), subject: text() }, {\n scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),\n client: { read: true, create: ['subject'], update: ['subject'] },\n }),\n messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: parent({ via: 'ticket_id' }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {\n scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],\n publicRead: { where: { published: true } } },\n }),\n note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {\n scope: owner(), unique: [['note_id', 'grantee_id']],\n }),\n shared_notes: table({ id: id(), title: text() }, {\n scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),\n client: { read: ['id', 'title'], create: ['title'], update: ['title'] },\n }),\n}, { appRoles: { staff: { emailDomain: 'staff.example' } } });\n```\n\nWho is staff is your app's decision; the platform enforces what the role may do.\nFirst choice, as above: emailDomain. The role holds once the person verifies an address\nat that domain; no grant code. An email ending alone proves nothing: anyone can sign up\nas anyone@your-domain without owning that mailbox. Without verification, grant only from\nsomething the visitor cannot choose, such as an invitation your app issued, checked inside\nthe sign-up route: single use, bound to one account, its link delivered only to that person:\nsomewhere docs sw.auth --section server-assigned-app-roles-setroles.\nmessages use parent(): owner() would hide staff replies from the customer.\nPublish pages in an owner-checked endpoint. Share with caller-scoped\nsw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.\nBrowser calls THROW, not { error }; catch below.\nBrowser list: max 100, paginate after; no order (sort locally or in an endpoint).\n\n```ts\nimport { data } from 'somewhere:data';\nexport async function save(title: string) {\n try { await data.notes.create({ title }); return null; }\n catch (e) { return e instanceof Error ? e.message : 'Save failed'; }\n}\nexport const list = (after?: string) => data.notes.list({ limit: 100, after });\n```\n\nTeams are built-in groups: the platform keeps the team, invitations, roster, removal,\nleaving, last owner. Starting a team needs a signed-in user; joining needs a verified\nemail (a password sign-up joins once it enters its emailed code). The browser cannot call\nsw.groups: pass each call through an endpoint. A parent() child's delete follows the task\n(creator or team owner), so \"comment author or team owner deletes\" is an endpoint.\nStaff making others staff: appRoles { staff: { grantableBy: ['staff'] } } and\nsw.groups.appRoles.grant(request, userId, 'staff') in an endpoint (never to oneself).\nComplete apps and specs: somewhere docs sw.groups --section team-example or staff-example.\n\n```ts\n// api/teams.ts \u2014 GET my teams (completes invitations to me); POST starts one I own\nconst refusal = (e: { code: string; message: string; status: number }) =>\n Response.json({ error: e.code, message: e.message }, { status: e.status });\nexport const GET = sw.endpoint({ auth: 'required', handler: async ({ request }, sw) => {\n const page = await sw.groups.list(request, { limit: 100 });\n return page.error ? refusal(page.error) : { teams: page.data.items, next_cursor: page.data.next_cursor };\n} });\nexport default sw.endpoint({ auth: 'required', body: { name: 'string' }, handler: async ({ request, body }, sw) => {\n const made = await sw.groups.create(request, { name: body.name });\n return made.error ? refusal(made.error) : { id: made.data.id };\n} });\n```\n\n```ts\n// api/teams/[id]/invitations.ts \u2014 owners invite; others 403; a member's address 409 ALREADY_MEMBER\nexport default sw.endpoint({ auth: 'required', body: { email: 'string' }, handler: async ({ request, params, body }, sw) => {\n const sent = await sw.groups.invite(request, params.id, { email: body.email, role: 'member', redirect_uri: '/' });\n return sent.error ? Response.json({ error: sent.error.code }, { status: sent.error.status }) : { delivery: sent.data.delivery };\n} });\n```\n\nSame shape: sw.groups.get/members(request, id), remove(request, id, userId), leave(request, id)\n(last owner: 409 LAST_OWNER), delete(request, id) by owners.\n\nDo not hand-write access to app-read/write data: declare who may read/write it.\nserverOnly() fits job/import/audit/counter state.\nGrant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates\n(e.g. expiry) or per-role writable fields (split tables or check that write).\n\nBuild src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.\nAuth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.\napi/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;\nGET/DELETE: named exports.\n\n```ts\nexport const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });\n```\n\nsw.db applies caller scopes; sw.db.server bypasses them: authorize first.\nCaller-scoped sw.db.insert needs no client.create grant: client limits only the browser.\nReads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).\nFilter: { id: { in: ids } }; unique: [['a', 'b']] in schema.\nWrites: insert(table, values), update(table, { where, set }), remove(table, { where }).\ntx takes an ARRAY of write intents, never a callback; pre-generate related IDs.\n\nBrowser: fetch(path, { method: 'POST', credentials: 'same-origin',\nheaders: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).\nAccess cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts\nneed Origin equal to the app URL.\n\nTest with an ordinary Playwright script: the journeys you changed and your access boundaries.\nRun it only after a successful deploy: npx @somewhere-cloud/cli deploy && node tests/app-check.mjs\n(the starter's short example; one result file, and the exit code is the verdict). Rerun only to answer a question.\nHelpers from @somewhere-cloud/cli/script (import or require): openAppTest() then app.signUp/signIn/signOut(page)\nthrough your form, app.data(page, { table, operation, id, values, where }) as that person,\napp.expectRefused(page, request, { allowed: ownerPage }), captureResponses, dataReady, launchOptions.\nA rebuilt sign-in form keeps data-sw-auth=\"email\", \"password\", \"sign-up\", \"sign-in\" on its controls,\nor pass app.signUp(page, { form: { email, password, signUp, signIn } }) with your own selectors.\nDeploy raw source, no frontend build; type errors stop upload.\nEmail-domain role: app.signUp(page, { domain: 'staff.example' }), then app.verify(page, person).\nThe complete team spec, with removal and leaving: somewhere docs sw.groups --section team-example.\nDiagnose with somewhere errors and somewhere logs.\n\nOn demand:\n- Server paging: `somewhere docs sw.db --section server-read-paging`\n\n## Testing shared access\n\nWith the team endpoints above, the owner invites a fixture by email; test users are verified,\nso its next GET /api/teams shows the team. A test user who still owns a team is not deleted:\ndelete the team last (api/teams/[id].ts DELETE: sw.groups.delete). Group calls take\nabout a second, so raise the timeout:\n\n```ts\n// tests/team.spec.ts\nimport { test, expect } from '@somewhere-cloud/cli/testing';\ntest.describe.configure({ timeout: 90_000 });\ntest('owner invites a second user by email', async ({ newUser }) => {\n const [owner, bob] = await Promise.all([newUser(), newUser()]);\n const { id } = await (await owner.request.post('/api/teams', { data: { name: 'Shared team' } })).json();\n expect((await owner.request.post(`/api/teams/${id}/invitations`, { data: { email: bob.email } })).ok()).toBeTruthy();\n const { teams } = await (await bob.request.get('/api/teams')).json();\n expect(teams).toContainEqual(expect.objectContaining({ id, role: 'member' }));\n expect((await owner.request.delete(`/api/teams/${id}`)).status()).toBe(204);\n});\n```\n";
2
2
  export declare const SKILLS_POINTER = "Task-specific skills: `.agents/skills/`. Inspect/update with somewhere skills status/update.";
3
3
  export declare const DECLARED_ACCESS_POINTER = "";
4
4
  /** One line telling agents the app's data and code can leave:
@@ -7,5 +7,5 @@ export declare const DECLARED_ACCESS_POINTER = "";
7
7
  export declare const PORTABILITY_POINTER = "Data/code export limits: `somewhere docs portability`.";
8
8
  /** One line: using the app from Claude as its signed-in user (MCP tools). */
9
9
  export declare const MCP_POINTER = "Use this app from Claude as its signed-in user (MCP tools): `somewhere docs sw.endpoint --section mcp-tools-for-claude`.";
10
- export declare const INIT_AGENTS_MD = "# somewhere.cloud project contract\n## Build, deploy, test\n\nEnough to start a typical app: declare access and use the browser client; docs are for exceptions.\n\n| Requirement | Declaration below |\n| --- | --- |\n| Each user sees only their own rows | notes: owner() |\n| Team: owner adds members; members read/write; creator rights | teams/team_members/tasks: owner() + member(); role-owner delete branch |\n| Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain |\n| Public pages from private drafts | pages: conditional publicRead |\n| Share one record read-only | shared_notes/note_shares: read-only grant() |\n\ndb/schema.ts is declaration only: imports, constants/spreads, default schema;\nno helpers/expressions. id() is random text; owner() stamps user_id. client.read\nincludes the key. Inside anyOf(), owner() takes only column/read: it stamps the\ncreator, not create/delete options; member() gates placement (non-member create is\nrefused), while creators or the allowed branch can delete. Other fields: timestamp({ default: 'now' }), text({ nullable: true });\nindexes: [['team_id']].\n\n```ts\nimport { schema, table, id, text, owner, member, anyOf, serverOnly, parent, appRole, boolean, grant } from 'somewhere/db';\nexport default schema({\n notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },\n }),\n teams: table({ id: id(), name: text(), owner_id: text() }, {\n scope: member({ group: 'id', membership: 'team_members', member_user: 'user_id', member_group: 'team_id' }),\n client: { read: ['id', 'name'] },\n }),\n team_members: table({ id: id(), team_id: text(), user_id: text(), role: text() }, {\n scope: serverOnly(), unique: [['team_id', 'user_id']],\n }),\n tasks: table({ id: id(), team_id: text({ references: 'teams' }), title: text() }, {\n scope: anyOf(owner(), member({ group: 'team_id', membership: 'team_members',\n member_user: 'user_id', member_group: 'team_id', operations: ['read', 'create', 'update'] }),\n member({ group: 'team_id', membership: 'team_members', member_user: 'user_id',\n member_group: 'team_id', where: { role: 'owner' }, operations: ['delete'] })),\n client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },\n }),\n tickets: table({ id: id(), subject: text() }, {\n scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),\n client: { read: true, create: ['subject'], update: ['subject'] },\n }),\n messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: parent({ via: 'ticket_id' }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {\n scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],\n publicRead: { where: { published: true } } },\n }),\n note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {\n scope: owner(), unique: [['note_id', 'grantee_id']],\n }),\n shared_notes: table({ id: id(), title: text() }, {\n scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),\n client: { read: ['id', 'title'], create: ['title'], update: ['title'] },\n }),\n}, { appRoles: { staff: { emailDomain: 'staff.example' } } });\n```\n\nWho is staff is your app's decision; the platform enforces what the role may do.\nFirst choice, as above: emailDomain. The role holds once the person verifies an address\nat that domain; no grant code. An email ending alone proves nothing: anyone can sign up\nas anyone@your-domain without owning that mailbox. Without verification, grant only from\nsomething the visitor cannot choose, such as an invitation your app issued, checked inside\nthe sign-up route: somewhere docs sw.auth --section server-assigned-app-roles-setroles.\nmessages use parent(): owner() would hide staff replies from the customer.\nPublish pages in an owner-checked endpoint. Share with caller-scoped\nsw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.\nBrowser calls THROW, not { error }; catch below.\nBrowser list: max 100, paginate after; no order (sort locally or in an endpoint).\n\n```ts\nimport { data } from 'somewhere:data';\nexport async function save(title: string) {\n try { await data.notes.create({ title }); return null; }\n catch (e) { return e instanceof Error ? e.message : 'Save failed'; }\n}\nexport const list = (after?: string) => data.notes.list({ limit: 100, after });\n```\n\nTeams without verification: own membership table + member(); sw.groups and domain\nroles need VERIFIED emails. Members read/create/update tasks; creators or team owners delete while members.\nRestrictions narrow operations, not grant read.\nComment author or team owner deletes: declare it as tasks do (owner() plus member() where role owner, delete).\nCreate the team and its owner membership atomically:\n\n```ts\n// api/teams.ts\nexport default sw.endpoint({\n auth: 'required', body: { name: 'string' },\n handler: async ({ user, params, body }, sw) => {\n const id = crypto.randomUUID();\n await sw.db.server.tx([\n { op: 'insert', table: 'teams', values: { id, name: body.name, owner_id: user.id } },\n { op: 'insert', table: 'team_members', values: { id: crypto.randomUUID(), team_id: id, user_id: user.id, role: 'owner' } },\n ]);\n return { id, email: user.email };\n },\n});\n```\n\n```ts\n// api/teams/[id]/members.ts \u2014 only the team owner adds a member\nexport default sw.endpoint({\n auth: 'required', body: { email: 'string' },\n handler: async ({ user, params, body }, sw) => {\n const { data: teams } = await sw.db.from('teams', { where: { id: params.id, owner_id: user.id }, limit: 1 });\n if (!teams[0]) return Response.json({ error: 'Team owner required' }, { status: 403 });\n const { users: [target] } = await sw.auth.server.listUsers({ emails: [body.email] });\n if (!target) return Response.json({ error: 'Account not found' }, { status: 404 });\n await sw.db.server.insert('team_members', {\n id: crypto.randomUUID(), team_id: params.id, user_id: target.id, role: 'member',\n }, { onConflict: 'ignore' });\n return { ok: true };\n },\n});\n```\n\nDo not hand-write access to app-read/write data: declare who may read/write it.\nserverOnly() fits job/import/audit/counter state and protected membership ledgers.\nGrant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates\n(e.g. expiry) or per-role writable fields (split tables or check that write).\n\nBuild src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.\nAuth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.\napi/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;\nGET/DELETE: named exports.\n\n```ts\nexport const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });\n```\n\nsw.db applies caller scopes; sw.db.server bypasses them: authorize first.\nCaller-scoped sw.db.insert needs no client.create grant: client limits only the browser.\nReads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).\nFilter: { id: { in: ids } }; unique: [['a', 'b']] in schema.\nWrites: insert(table, values), update(table, { where, set }), remove(table, { where }).\ntx takes an ARRAY of write intents, never a callback; pre-generate related IDs.\n\nBrowser: fetch(path, { method: 'POST', credentials: 'same-origin',\nheaders: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).\nAccess cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts\nneed Origin equal to the app URL.\n\nPublish: npx @somewhere-cloud/cli deploy, then somewhere test for the rules you changed.\nOne somewhere test run drives the UI and calls the API: signUp(page) uses your sign-up form\n(then signOut, signIn with its password, verify with the emailed code), newUser() acts as\nseveral people, and ready(page, 'signed-in' | 'signed-out') waits for the session check.\nYou do not need a separate browser script.\nStart from the starter's tests/account, phone and access specs: one journey per test, its own people.\nOne somewhere test runs every spec, old and new together; somewhere deploy --test deploys, then runs them once.\nAfter fixing a test, run only what failed: somewhere test --failed (passed results on this release are kept).\nDo not rerun a suite that is already green on this release.\nDeploy raw source, no frontend build; type errors stop upload.\nnewUser() gives a signed-in page/API client; make people at once: await Promise.all([newUser(), newUser()]).\nnewUser({ role: 'staff' }) holds a role declared in appRoles, granted with your developer key.\nnewUser() takes no chosen email. Test users are verified and visible to this project's server user lookup.\nEmail-domain role: signUp(page, { domain: 'staff.example' }), then verify(page, person); newPage() for a second person.\nRefusals: await expectRefused(person, 'notes', { operation: 'update', id, values }, { allowed: owner }) or\nexpectRefused(person, 'POST /api/x', body, { allowed }). allowed is someone the same request succeeds for;\nan empty list, a null get or a 404 counts as refused only then. person/allowed: page, newUser() or anonymous.\nsomewhere test --phone runs every test again at 390x844.\nFor the complete owner-adds-member-by-email test and its endpoints, run\nsomewhere docs test and follow Two users sharing through the app.\nDiagnose with somewhere errors and somewhere logs.\n\nOn demand:\n- Server paging: `somewhere docs sw.db --section server-read-paging`\n\n## Testing shared access\n\nWith the teams and membership endpoints above, the owner adds a fixture by email\nand that fixture reads the shared team row:\n\n```ts\n// tests/team.spec.ts\nimport { test, expect, data } from '@somewhere-cloud/cli/testing';\ntest('owner adds a second user by email', async ({ newUser }) => {\n const owner = await newUser();\n const bob = await newUser();\n const name = `Shared team ${crypto.randomUUID()}`;\n const created = await owner.request.post('/api/teams', { data: { name } });\n expect(created.ok()).toBeTruthy();\n const { id } = await created.json();\n const added = await owner.request.post(`/api/teams/${id}/members`, { data: { email: bob.email } });\n expect(added.ok()).toBeTruthy();\n const response = await data(bob.request, 'teams', { operation: 'get', id });\n expect(response.ok()).toBeTruthy();\n expect((await response.json()).data).toMatchObject({ id, name });\n});\n```\n\nTask-specific skills: `.agents/skills/`. Inspect/update with somewhere skills status/update.\nData/code export limits: `somewhere docs portability`.\nUse this app from Claude as its signed-in user (MCP tools): `somewhere docs sw.endpoint --section mcp-tools-for-claude`.\n";
10
+ export declare const INIT_AGENTS_MD = "# somewhere.cloud project contract\n## Build, deploy, test\n\nEnough to start a typical app: declare access and use the browser client; docs are for exceptions.\n\n| Requirement | Declaration below |\n| --- | --- |\n| Each user sees only their own rows | notes: owner() |\n| Team: owner invites members; members read/write; creator or team owner deletes | tasks: anyOf(owner(), group()); sw.groups endpoints below |\n| Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain (or grantableBy) |\n| Public pages from private drafts | pages: conditional publicRead |\n| Share one record read-only | shared_notes/note_shares: read-only grant() |\n\ndb/schema.ts is declaration only: imports, constants/spreads, default schema;\nno helpers/expressions. id() is random text; owner() stamps user_id. client.read\nincludes the key. Inside anyOf(), owner() takes only column/read: it stamps the\ncreator, not create/delete options; group() gates placement (non-member create is\nrefused); inside anyOf an operation missing from roles allows no group role. Other fields: timestamp({ default: 'now' }), text({ nullable: true });\nindexes: [['team_id']].\n\n```ts\nimport { schema, table, id, text, owner, group, anyOf, parent, appRole, boolean, grant } from 'somewhere/db';\nexport default schema({\n notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },\n }),\n tasks: table({ id: id(), team_id: text(), title: text() }, {\n scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['owner', 'admin', 'member'],\n create: ['owner', 'admin', 'member'], update: ['owner', 'admin', 'member'], delete: ['owner'] } })),\n client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },\n }),\n tickets: table({ id: id(), subject: text() }, {\n scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),\n client: { read: true, create: ['subject'], update: ['subject'] },\n }),\n messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: parent({ via: 'ticket_id' }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {\n scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],\n publicRead: { where: { published: true } } },\n }),\n note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {\n scope: owner(), unique: [['note_id', 'grantee_id']],\n }),\n shared_notes: table({ id: id(), title: text() }, {\n scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),\n client: { read: ['id', 'title'], create: ['title'], update: ['title'] },\n }),\n}, { appRoles: { staff: { emailDomain: 'staff.example' } } });\n```\n\nWho is staff is your app's decision; the platform enforces what the role may do.\nFirst choice, as above: emailDomain. The role holds once the person verifies an address\nat that domain; no grant code. An email ending alone proves nothing: anyone can sign up\nas anyone@your-domain without owning that mailbox. Without verification, grant only from\nsomething the visitor cannot choose, such as an invitation your app issued, checked inside\nthe sign-up route: single use, bound to one account, its link delivered only to that person:\nsomewhere docs sw.auth --section server-assigned-app-roles-setroles.\nmessages use parent(): owner() would hide staff replies from the customer.\nPublish pages in an owner-checked endpoint. Share with caller-scoped\nsw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.\nBrowser calls THROW, not { error }; catch below.\nBrowser list: max 100, paginate after; no order (sort locally or in an endpoint).\n\n```ts\nimport { data } from 'somewhere:data';\nexport async function save(title: string) {\n try { await data.notes.create({ title }); return null; }\n catch (e) { return e instanceof Error ? e.message : 'Save failed'; }\n}\nexport const list = (after?: string) => data.notes.list({ limit: 100, after });\n```\n\nTeams are built-in groups: the platform keeps the team, invitations, roster, removal,\nleaving, last owner. Starting a team needs a signed-in user; joining needs a verified\nemail (a password sign-up joins once it enters its emailed code). The browser cannot call\nsw.groups: pass each call through an endpoint. A parent() child's delete follows the task\n(creator or team owner), so \"comment author or team owner deletes\" is an endpoint.\nStaff making others staff: appRoles { staff: { grantableBy: ['staff'] } } and\nsw.groups.appRoles.grant(request, userId, 'staff') in an endpoint (never to oneself).\nComplete apps and specs: somewhere docs sw.groups --section team-example or staff-example.\n\n```ts\n// api/teams.ts \u2014 GET my teams (completes invitations to me); POST starts one I own\nconst refusal = (e: { code: string; message: string; status: number }) =>\n Response.json({ error: e.code, message: e.message }, { status: e.status });\nexport const GET = sw.endpoint({ auth: 'required', handler: async ({ request }, sw) => {\n const page = await sw.groups.list(request, { limit: 100 });\n return page.error ? refusal(page.error) : { teams: page.data.items, next_cursor: page.data.next_cursor };\n} });\nexport default sw.endpoint({ auth: 'required', body: { name: 'string' }, handler: async ({ request, body }, sw) => {\n const made = await sw.groups.create(request, { name: body.name });\n return made.error ? refusal(made.error) : { id: made.data.id };\n} });\n```\n\n```ts\n// api/teams/[id]/invitations.ts \u2014 owners invite; others 403; a member's address 409 ALREADY_MEMBER\nexport default sw.endpoint({ auth: 'required', body: { email: 'string' }, handler: async ({ request, params, body }, sw) => {\n const sent = await sw.groups.invite(request, params.id, { email: body.email, role: 'member', redirect_uri: '/' });\n return sent.error ? Response.json({ error: sent.error.code }, { status: sent.error.status }) : { delivery: sent.data.delivery };\n} });\n```\n\nSame shape: sw.groups.get/members(request, id), remove(request, id, userId), leave(request, id)\n(last owner: 409 LAST_OWNER), delete(request, id) by owners.\n\nDo not hand-write access to app-read/write data: declare who may read/write it.\nserverOnly() fits job/import/audit/counter state.\nGrant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates\n(e.g. expiry) or per-role writable fields (split tables or check that write).\n\nBuild src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.\nAuth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.\napi/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;\nGET/DELETE: named exports.\n\n```ts\nexport const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });\n```\n\nsw.db applies caller scopes; sw.db.server bypasses them: authorize first.\nCaller-scoped sw.db.insert needs no client.create grant: client limits only the browser.\nReads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).\nFilter: { id: { in: ids } }; unique: [['a', 'b']] in schema.\nWrites: insert(table, values), update(table, { where, set }), remove(table, { where }).\ntx takes an ARRAY of write intents, never a callback; pre-generate related IDs.\n\nBrowser: fetch(path, { method: 'POST', credentials: 'same-origin',\nheaders: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).\nAccess cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts\nneed Origin equal to the app URL.\n\nTest with an ordinary Playwright script: the journeys you changed and your access boundaries.\nRun it only after a successful deploy: npx @somewhere-cloud/cli deploy && node tests/app-check.mjs\n(the starter's short example; one result file, and the exit code is the verdict). Rerun only to answer a question.\nHelpers from @somewhere-cloud/cli/script (import or require): openAppTest() then app.signUp/signIn/signOut(page)\nthrough your form, app.data(page, { table, operation, id, values, where }) as that person,\napp.expectRefused(page, request, { allowed: ownerPage }), captureResponses, dataReady, launchOptions.\nA rebuilt sign-in form keeps data-sw-auth=\"email\", \"password\", \"sign-up\", \"sign-in\" on its controls,\nor pass app.signUp(page, { form: { email, password, signUp, signIn } }) with your own selectors.\nDeploy raw source, no frontend build; type errors stop upload.\nEmail-domain role: app.signUp(page, { domain: 'staff.example' }), then app.verify(page, person).\nThe complete team spec, with removal and leaving: somewhere docs sw.groups --section team-example.\nDiagnose with somewhere errors and somewhere logs.\n\nOn demand:\n- Server paging: `somewhere docs sw.db --section server-read-paging`\n\n## Testing shared access\n\nWith the team endpoints above, the owner invites a fixture by email; test users are verified,\nso its next GET /api/teams shows the team. A test user who still owns a team is not deleted:\ndelete the team last (api/teams/[id].ts DELETE: sw.groups.delete). Group calls take\nabout a second, so raise the timeout:\n\n```ts\n// tests/team.spec.ts\nimport { test, expect } from '@somewhere-cloud/cli/testing';\ntest.describe.configure({ timeout: 90_000 });\ntest('owner invites a second user by email', async ({ newUser }) => {\n const [owner, bob] = await Promise.all([newUser(), newUser()]);\n const { id } = await (await owner.request.post('/api/teams', { data: { name: 'Shared team' } })).json();\n expect((await owner.request.post(`/api/teams/${id}/invitations`, { data: { email: bob.email } })).ok()).toBeTruthy();\n const { teams } = await (await bob.request.get('/api/teams')).json();\n expect(teams).toContainEqual(expect.objectContaining({ id, role: 'member' }));\n expect((await owner.request.delete(`/api/teams/${id}`)).status()).toBe(204);\n});\n```\n\nTask-specific skills: `.agents/skills/`. Inspect/update with somewhere skills status/update.\nData/code export limits: `somewhere docs portability`.\nUse this app from Claude as its signed-in user (MCP tools): `somewhere docs sw.endpoint --section mcp-tools-for-claude`.\n";
11
11
  export declare const INIT_CLAUDE_MD = "Read AGENTS.md for project instructions.\n";