@somewhere-cloud/cli 0.38.83 → 0.38.85

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 (46) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/commands/deploy.js +25 -2
  3. package/dist/commands/deploy.js.map +1 -1
  4. package/dist/commands/test.js +13 -99
  5. package/dist/commands/test.js.map +1 -1
  6. package/dist/lib/deploy-tests.d.ts +27 -0
  7. package/dist/lib/deploy-tests.js +49 -0
  8. package/dist/lib/deploy-tests.js.map +1 -0
  9. package/dist/lib/form-accounts.d.ts +2 -2
  10. package/dist/lib/form-accounts.js +8 -5
  11. package/dist/lib/form-accounts.js.map +1 -1
  12. package/dist/lib/init-agent-guide.d.ts +2 -2
  13. package/dist/lib/init-agent-guide.js +19 -29
  14. package/dist/lib/init-agent-guide.js.map +1 -1
  15. package/dist/lib/init-feature-template.js +5 -5
  16. package/dist/lib/init-feature-template.js.map +1 -1
  17. package/dist/lib/init-green-template.js +3 -0
  18. package/dist/lib/init-green-template.js.map +1 -1
  19. package/dist/lib/init-test-template.d.ts +4 -1
  20. package/dist/lib/init-test-template.js +122 -42
  21. package/dist/lib/init-test-template.js.map +1 -1
  22. package/dist/lib/playwright-fixtures.d.ts +26 -9
  23. package/dist/lib/playwright-fixtures.js +119 -56
  24. package/dist/lib/playwright-fixtures.js.map +1 -1
  25. package/dist/lib/test-diagnostics.js +2 -1
  26. package/dist/lib/test-diagnostics.js.map +1 -1
  27. package/dist/lib/test-ledger.d.ts +73 -0
  28. package/dist/lib/test-ledger.js +261 -0
  29. package/dist/lib/test-ledger.js.map +1 -0
  30. package/dist/lib/test-reporter.d.ts +2 -0
  31. package/dist/lib/test-reporter.js +74 -6
  32. package/dist/lib/test-reporter.js.map +1 -1
  33. package/dist/lib/test-run.d.ts +35 -0
  34. package/dist/lib/test-run.js +136 -0
  35. package/dist/lib/test-run.js.map +1 -0
  36. package/dist/lib/test-target.d.ts +4 -1
  37. package/dist/lib/test-target.js +12 -3
  38. package/dist/lib/test-target.js.map +1 -1
  39. package/dist/lib/test-timeline.d.ts +10 -0
  40. package/dist/lib/test-timeline.js +50 -0
  41. package/dist/lib/test-timeline.js.map +1 -0
  42. package/dist/testing.d.ts +1 -1
  43. package/dist/testing.js.map +1 -1
  44. package/npm-shrinkwrap.json +2 -2
  45. package/package.json +1 -1
  46. package/src/testing.ts +1 -1
@@ -1,56 +1,136 @@
1
- const session = `import { test, expect, ready } from '@somewhere-cloud/cli/testing';
1
+ // The starter's journeys: small, independent specs an agent adapts instead of writing from nothing.
2
+ // Each one makes its own people (at the same time, with Promise.all), shares nothing with the others,
3
+ // runs alone or in any order, and waits on what the app does, never on a fixed sleep.
4
+ const FORM_ACCOUNT = `import { test, expect } from '@somewhere-cloud/cli/testing';
2
5
 
3
- test('a new person signs up through the form, signs out and signs back in', async ({ page, signUp, signOut, signIn }) => {
6
+ // A visitor signs up through the app's own form, signs out and signs back in.
7
+ test('sign up, sign out and sign back in', async ({ page, signUp, signOut, signIn }) => {
4
8
  const person = await signUp(page);
5
9
  await expect(page.getByText(person.email)).toBeVisible();
6
10
  await signOut(page);
7
11
  await signIn(page, person);
8
12
  await expect(page.getByText(person.email)).toBeVisible();
9
13
  });
14
+ `;
15
+ // The minimal starter has no sign-in screens yet: these steps call its auth route from the page.
16
+ // Once the app has a form, drop the steps (starter form) or replace them with the form's own steps.
17
+ const ROUTE_ACCOUNT = `import { test, expect, type FormSteps } from '@somewhere-cloud/cli/testing';
18
+
19
+ // This app has no sign-in screens yet, so these steps use its auth route from the page.
20
+ // When you add a form, replace them with your form's steps: fill, submit.
21
+ const viaAuthRoute = (path: string): FormSteps => async (page, { email, password }) => {
22
+ if (page.url() === 'about:blank') await page.goto('/');
23
+ await page.evaluate(async ([path, body]) => {
24
+ const response = await fetch(path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
25
+ await response.text(); // read the answer, as a form would
26
+ }, [path, { email, password }] as const);
27
+ };
28
+ const signedInAs = async (page: import('@playwright/test').Page) => (await (await page.request.get('/api/auth/me')).json()).user;
10
29
 
11
- test('session and sign-out', async ({ newUser }) => {
12
- const user = await newUser();
13
- const me = await user.request.get('/api/auth/me');
14
- expect(me.status()).toBe(200);
15
- expect((await me.json()).user.id).toBe(user.id);
16
- await user.page.goto('/');
17
- await ready(user.page, 'signed-in');
18
- expect((await user.request.post('/api/auth/logout', { data: {} })).status()).toBe(200);
19
- expect((await (await user.request.get('/api/auth/me')).json()).user).toBeNull();
20
- await user.page.reload();
21
- await ready(user.page, 'signed-out');
30
+ test('sign up, sign out and sign back in', async ({ page, signUp, signOut, signIn }) => {
31
+ const person = await signUp(page, { steps: viaAuthRoute('/api/auth/signup') });
32
+ expect((await signedInAs(page)).email).toBe(person.email);
33
+ await signOut(page, { steps: async page => { expect((await page.request.post('/api/auth/logout', { data: {} })).ok()).toBe(true); } });
34
+ expect(await signedInAs(page)).toBeNull();
35
+ await signIn(page, person, { steps: viaAuthRoute('/api/auth/login') });
36
+ expect((await signedInAs(page)).email).toBe(person.email);
22
37
  });
23
38
  `;
24
- const isolation = `
25
- test('owners can read only their own notes', async ({ newUser }) => {
26
- const owner = await newUser();
27
- const outsider = await newUser();
28
- const title = 'isolation-' + crypto.randomUUID();
29
- const created = await data(owner.request, 'notes', { operation: 'create', values: { title, body: 'test row' } });
30
- expect(created.status()).toBe(200);
31
- const row = (await created.json()).data as { id: number; title: string };
32
- expect(row.title).toBe(title);
33
- const own = await data(owner.request, 'notes', { operation: 'get', id: row.id });
34
- expect(own.status()).toBe(200);
35
- expect((await own.json()).data.title).toBe(title);
36
- const updatedTitle = title + '-owner';
37
- const updated = await data(owner.request, 'notes', { operation: 'update', id: row.id, values: { title: updatedTitle } });
38
- expect(updated.status()).toBe(200);
39
- expect((await (await data(owner.request, 'notes', { operation: 'get', id: row.id })).json()).data.title).toBe(updatedTitle);
40
- const list = await data(outsider.request, 'notes', { operation: 'list', where: { title: updatedTitle } });
41
- expect(list.status()).toBe(200);
42
- expect((await list.json()).data, 'another user must not see the owner row').toEqual([]);
43
- // Hidden rows read as not there (200, data null); prove absence and a refused write.
44
- const hidden = await data(outsider.request, 'notes', { operation: 'get', id: row.id });
45
- expect(hidden.status()).toBe(200);
46
- expect((await hidden.json()).data).toBeNull();
47
- await expectRefused(await data(outsider.request, 'notes', { operation: 'update', id: row.id, values: { title: 'changed' } }), 404, 'DATA_NOT_FOUND');
48
- const unchanged = await data(owner.request, 'notes', { operation: 'get', id: row.id });
49
- expect(unchanged.status()).toBe(200);
50
- expect((await unchanged.json()).data.title).toBe(updatedTitle);
39
+ const FORM_PHONE = (privateData) => `import { test, expect } from '@somewhere-cloud/cli/testing';
40
+
41
+ // One pass at phone width. Adapt: do the app's main action here, as a person on a phone would.
42
+ test.use({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
43
+
44
+ test('phone: ${privateData ? 'sign up, add a note and sign out' : 'sign up and sign out'}', async ({ page, signUp, signOut }) => {
45
+ const person = await signUp(page);
46
+ await expect(page.getByText(person.email)).toBeVisible();
47
+ ${privateData ? ` const title = 'phone ' + crypto.randomUUID();
48
+ await page.getByLabel('Title').fill(title);
49
+ await page.getByRole('button', { name: 'Add note' }).click();
50
+ await expect(page.getByRole('heading', { name: title })).toBeVisible();
51
+ ` : ''} await signOut(page);
51
52
  });
52
53
  `;
53
- export function starterTests(privateData = false) {
54
- return [{ path: 'tests/app.spec.ts', content: session.replace('test, expect, ready', privateData ? 'test, expect, ready, data, expectRefused' : 'test, expect, ready') + (privateData ? isolation : '') }];
54
+ const ROUTE_PHONE = `import { test, expect } from '@somewhere-cloud/cli/testing';
55
+
56
+ // One pass at phone width. Adapt: do the app's main action here, as a person on a phone would.
57
+ test.use({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
58
+
59
+ test('phone: the page shows the greeting from its function', async ({ page }) => {
60
+ await page.goto('/');
61
+ await expect(page.getByText('Your full-stack app is ready.')).toBeVisible();
62
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
63
+ });
64
+ `;
65
+ // Two people, one role-holder: the access journeys. In the private-data starter the first one runs
66
+ // against its notes; elsewhere both say exactly what to fill in and are skipped until then.
67
+ const ACCESS = (variant) => `import { test, expect, data, expectRefused } from '@somewhere-cloud/cli/testing';
68
+
69
+ // Adapt: a table whose rows belong to the person who made them, values to create one, and a change.
70
+ const OWNED = ${variant === 'notes'
71
+ ? `{ table: 'notes', values: { title: 'private ' + crypto.randomUUID() }, change: { title: 'changed' } }`
72
+ : `{ table: '', values: {} as Record<string, unknown>, change: {} as Record<string, unknown> }`};
73
+ // Adapt: a role from appRoles in db/schema.ts, a table only that role may use, and values to create a row.
74
+ const ROLE = { role: '', table: '', values: {} as Record<string, unknown> };
75
+
76
+ test('one person cannot see or change another person\\'s rows', async ({ newUser }) => {
77
+ test.skip(!OWNED.table, 'Fill in OWNED at the top of tests/access.spec.ts');
78
+ const [owner, other] = await Promise.all([newUser(), newUser()]);
79
+ ${variant === 'notes' ? ` // The owner adds the row through the app's own form.
80
+ await owner.page.goto('/');
81
+ await owner.page.getByLabel('Title').fill(OWNED.values.title);
82
+ await owner.page.getByRole('button', { name: 'Add note' }).click();
83
+ await expect(owner.page.getByRole('heading', { name: OWNED.values.title })).toBeVisible();
84
+ const listed = await data(owner.request, OWNED.table, { operation: 'list', where: { title: OWNED.values.title } });
85
+ const { id } = (await listed.json()).data[0];
86
+ // The other person's own list loads without it.
87
+ await other.page.goto('/');
88
+ await expect(other.page.getByText('No notes yet.')).toBeVisible();
89
+ ` : ` const created = await data(owner.request, OWNED.table, { operation: 'create', values: OWNED.values });
90
+ expect(created.status()).toBe(200);
91
+ const { id } = (await created.json()).data;
92
+ `} // Every way the other person could reach the row is refused; the owner is the positive control.
93
+ await Promise.all([
94
+ expectRefused(other, OWNED.table, { operation: 'get', id }, { allowed: owner }),
95
+ expectRefused(other, OWNED.table, { operation: 'list', where: { id } }, { allowed: owner }),
96
+ expectRefused(other, OWNED.table, { operation: 'update', id, values: OWNED.change }, { allowed: owner }),
97
+ expectRefused(other, OWNED.table, { operation: 'delete', id }, { allowed: owner }),
98
+ ]);
99
+ // Nothing they tried changed it.
100
+ const after = await data(owner.request, OWNED.table, { operation: 'get', id });
101
+ expect((await after.json()).data).toMatchObject(OWNED.values);
102
+ });
103
+
104
+ test('a role-holder may use what a non-holder is refused', async ({ newUser }) => {
105
+ test.skip(!ROLE.role, 'Fill in ROLE at the top of tests/access.spec.ts');
106
+ const [holder, person] = await Promise.all([newUser({ role: ROLE.role }), newUser()]);
107
+ const created = await data(holder.request, ROLE.table, { operation: 'create', values: ROLE.values });
108
+ expect(created.status()).toBe(200);
109
+ const { id } = (await created.json()).data;
110
+ await Promise.all([
111
+ expectRefused(person, ROLE.table, { operation: 'get', id }, { allowed: holder }),
112
+ expectRefused(person, ROLE.table, { operation: 'create', values: ROLE.values }, { allowed: holder }),
113
+ expectRefused(person, ROLE.table, { operation: 'delete', id }, { allowed: holder }),
114
+ ]);
115
+ expect((await (await data(holder.request, ROLE.table, { operation: 'get', id })).json()).data).toMatchObject(ROLE.values);
116
+ });
117
+ ${variant === 'minimal' ? `
118
+ test('visitors cannot read the server-only greetings table', async ({ anonymous }) => {
119
+ await expectRefused(anonymous, 'greetings', { operation: 'list' });
120
+ });
121
+ ` : ''}`;
122
+ export function starterTests(options = {}) {
123
+ if (options.minimal) {
124
+ return [
125
+ { path: 'tests/account.spec.ts', content: ROUTE_ACCOUNT },
126
+ { path: 'tests/phone.spec.ts', content: ROUTE_PHONE },
127
+ { path: 'tests/access.spec.ts', content: ACCESS('minimal') },
128
+ ];
129
+ }
130
+ return [
131
+ { path: 'tests/account.spec.ts', content: FORM_ACCOUNT },
132
+ { path: 'tests/phone.spec.ts', content: FORM_PHONE(Boolean(options.privateData)) },
133
+ { path: 'tests/access.spec.ts', content: ACCESS(options.privateData ? 'notes' : 'none') },
134
+ ];
55
135
  }
56
136
  //# sourceMappingURL=init-test-template.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"init-test-template.js","sourceRoot":"","sources":["../../src/lib/init-test-template.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;CAsBf,CAAC;AACF,MAAM,SAAS,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BjB,CAAC;AACF,MAAM,UAAU,YAAY,CAAC,WAAW,GAAG,KAAK;IAC9C,OAAO,CAAC,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,qBAAqB,EAAE,WAAW,CAAC,CAAC,CAAC,0CAA0C,CAAC,CAAC,CAAC,qBAAqB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AAC7M,CAAC"}
1
+ {"version":3,"file":"init-test-template.js","sourceRoot":"","sources":["../../src/lib/init-test-template.ts"],"names":[],"mappings":"AAEA,oGAAoG;AACpG,sGAAsG;AACtG,sFAAsF;AAEtF,MAAM,YAAY,GAAG;;;;;;;;;;CAUpB,CAAC;AAEF,iGAAiG;AACjG,oGAAoG;AACpG,MAAM,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;CAqBrB,CAAC;AAEF,MAAM,UAAU,GAAG,CAAC,WAAoB,EAAE,EAAE,CAAC;;;;;eAK9B,WAAW,CAAC,CAAC,CAAC,kCAAkC,CAAC,CAAC,CAAC,sBAAsB;;;EAGtF,WAAW,CAAC,CAAC,CAAC;;;;CAIf,CAAC,CAAC,CAAC,EAAE;;CAEL,CAAC;AAEF,MAAM,WAAW,GAAG;;;;;;;;;;CAUnB,CAAC;AAEF,mGAAmG;AACnG,4FAA4F;AAC5F,MAAM,MAAM,GAAG,CAAC,OAAqC,EAAE,EAAE,CAAC;;;gBAG1C,OAAO,KAAK,OAAO;IACjC,CAAC,CAAC,uGAAuG;IACzG,CAAC,CAAC,6FAA6F;;;;;;;EAO/F,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC;;;;;;;;;;CAUvB,CAAC,CAAC,CAAC;;;CAGH;;;;;;;;;;;;;;;;;;;;;;;;;EAyBC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC;;;;CAIzB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;AAET,MAAM,UAAU,YAAY,CAAC,UAAwD,EAAE;IACrF,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QACpB,OAAO;YACL,EAAE,IAAI,EAAE,uBAAuB,EAAE,OAAO,EAAE,aAAa,EAAE;YACzD,EAAE,IAAI,EAAE,qBAAqB,EAAE,OAAO,EAAE,WAAW,EAAE;YACrD,EAAE,IAAI,EAAE,sBAAsB,EAAE,OAAO,EAAE,MAAM,CAAC,SAAS,CAAC,EAAE;SAC7D,CAAC;IACJ,CAAC;IACD,OAAO;QACL,EAAE,IAAI,EAAE,uBAAuB,EAAE,OAAO,EAAE,YAAY,EAAE;QACxD,EAAE,IAAI,EAAE,qBAAqB,EAAE,OAAO,EAAE,UAAU,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,EAAE;QAClF,EAAE,IAAI,EAAE,sBAAsB,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE;KAC1F,CAAC;AACJ,CAAC"}
@@ -9,6 +9,11 @@ export interface TestUser {
9
9
  page: Page;
10
10
  request: APIRequestContext;
11
11
  }
12
+ /** `role`: an app role declared in db/schema.ts appRoles, granted to this user with your developer
13
+ * credential (the same grant as somewhere's app-roles grant) before newUser returns. */
14
+ export interface NewUserOptions {
15
+ role?: string;
16
+ }
12
17
  /** An ordinary account made through the app's own sign-up form. `verified` is true once its
13
18
  * address was verified with a captured code (verify(), or a project that requires email codes). */
14
19
  export interface Person {
@@ -36,9 +41,11 @@ export interface SignInOptions {
36
41
  }
37
42
  interface Fixtures {
38
43
  _evidence: void;
39
- newUser: () => Promise<TestUser>;
40
44
  anonymous: APIRequestContext;
41
45
  _forms: FormRun;
46
+ /** A fresh signed-in test user. Make several at once: `await Promise.all([newUser(), newUser()])`.
47
+ * `{ role }` grants that app role (declared in db/schema.ts appRoles) before it returns. */
48
+ newUser: (options?: NewUserOptions) => Promise<TestUser>;
42
49
  /** Another signed-out page on the app, in its own browser context (a second person for signUp). */
43
50
  newPage: () => Promise<Page>;
44
51
  signUp: (page: Page, options?: SignUpOptions) => Promise<Person>;
@@ -54,17 +61,27 @@ export declare const expect: typeof import('@playwright/test').expect;
54
61
  type Person_ = Page | {
55
62
  request: APIRequestContext;
56
63
  } | APIRequestContext;
64
+ /** `allowed`: someone the same request succeeds for. It is the positive control that turns an
65
+ * empty list, a null get or a 404 into proof of refusal (otherwise those look exactly like an
66
+ * empty table, a missing row or a missing route). */
67
+ export interface RefusalOptions {
68
+ allowed?: Person_;
69
+ }
57
70
  /**
58
- * Prove a refusal in one call: act as `person` against a table (with a data request) or an
59
- * endpoint ('METHOD /path', with a JSON body), and pass only if it was refused. Knows every shape
60
- * a refusal takes: a hidden row reads as 200 data:null, a hidden list as 200 with no rows, a
61
- * refused update/delete as 404, a closed table, operation or role as 403, an endpoint as
62
- * 401/403/404. A malformed request or stale contract (400/409) never counts.
63
- *
64
- * The older form expectRefused(response, status, code) checks one exact status and code.
71
+ * Prove a refusal: act as `person` against a table (with a data request) or an endpoint
72
+ * ('METHOD /path', with a JSON body), and pass only if it was refused.
73
+ * - 401 or 403 counts as refused on its own.
74
+ * - A 200 with no rows, a get with data:null, or a 404 counts only with `{ allowed }`: the same
75
+ * read must return data for them, the row a write targeted must exist for them before and be
76
+ * unchanged after, and an endpoint must succeed for them.
77
+ * - A malformed request or a stale contract (400/409) never counts.
78
+ * With `allowed`, the control always runs (after the person's attempt), so an endpoint call
79
+ * runs twice. The older form expectRefused(response, status, code) checks one exact status and code.
65
80
  */
66
- export declare function expectRefused(person: Person_, target: string, request?: unknown): Promise<void>;
81
+ export declare function expectRefused(person: Person_, target: string, request?: unknown, options?: RefusalOptions): Promise<void>;
67
82
  export declare function expectRefused(response: APIResponse, status: number, code: string): Promise<void>;
83
+ /** Test seam: a stand-in request client that data() accepts. */
84
+ export declare function _fixtureClientForTests(client: APIRequestContext, digest: string): APIRequestContext;
68
85
  export declare function data(client: APIRequestContext, table: string, request: DataRequest): Promise<APIResponse>;
69
86
  export declare function ready(page: Page, state?: 'ready' | 'signed-in' | 'signed-out' | Locator): Promise<void>;
70
87
  interface Attempt {
@@ -5,6 +5,7 @@ import { ApiClient } from './client.js';
5
5
  import { getToken, loadProjectConfig } from './config.js';
6
6
  import { buildStorageState, createTestIdentities, expiryOf, messagesAfter } from './test-identities.js';
7
7
  import { diagnostics, rememberSecrets, scrub, describeError, timed, titled } from './test-diagnostics.js';
8
+ import { mark as timelineMark, markProcessStart, span, trackPage } from './test-timeline.js';
8
9
  import { admitReservedAddress, deleteAccount, forgetRecord, generatedAddress, generatedPassword, recordAttempt, recordId } from './form-accounts.js';
9
10
  let loaded;
10
11
  const digests = new WeakMap();
@@ -41,7 +42,9 @@ function runner() {
41
42
  const contexts = [];
42
43
  const partialIds = [];
43
44
  try {
44
- await use(async () => {
45
+ await use(async (options = {}) => {
46
+ if (options.role !== undefined && (typeof options.role !== 'string' || !/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(options.role)))
47
+ throw new Error('newUser({ role }): name a role declared in db/schema.ts appRoles.');
45
48
  let created;
46
49
  try {
47
50
  created = await timed(info, 'test-user creation', () => createTestIdentities(client, projectId, 'user', 1, 'pw'));
@@ -54,11 +57,15 @@ function runner() {
54
57
  owned.push(...created.issued);
55
58
  const issued = created.issued[0];
56
59
  rememberSecrets(issued.access_token, issued.refresh_token);
60
+ const granted = options.role === undefined ? undefined : timed(info, 'role grant', () => client.call('POST', '/auth/app-roles/grant', { project_id: projectId, user_id: issued.user.id, role: options.role }))
61
+ .catch((error) => { throw new Error(`newUser({ role: '${options.role}' }): the role was not granted: ${error instanceof Error ? scrub(error.message) : String(error)}`); });
57
62
  const context = await browser.newContext({ baseURL: origin, viewport, isMobile, hasTouch, extraHTTPHeaders: { Origin: origin }, storageState: buildStorageState(origin, host, issued, expiryOf(issued, created.receivedAt)) });
58
63
  contexts.push(context);
64
+ await granted;
59
65
  constrain(context.request, origin, info);
60
66
  digests.set(context.request, target.contractDigest);
61
67
  const page = await timed(info, 'page creation', () => context.newPage());
68
+ trackPage(page, titled(info.project.name, info.title));
62
69
  page.on('load', () => { void page.evaluate("performance.getEntriesByType('navigation')[0]?.duration ?? 0").then(ms => { diagnostics(info).timings['page load'] = ms; }).catch(() => { }); });
63
70
  return { id: issued.user.id, email: issued.user.email, page, request: context.request };
64
71
  });
@@ -68,7 +75,7 @@ function runner() {
68
75
  for (const context of contexts)
69
76
  try {
70
77
  rememberSecrets(...(await context.cookies()).map(cookie => cookie.value));
71
- if (info.status !== info.expectedStatus) {
78
+ if (info.status !== info.expectedStatus && !diagnostics(info).screenshot) {
72
79
  const page = context.pages()[0];
73
80
  if (page && !/auth|login|signup|reset/i.test(new URL(page.url()).pathname)) {
74
81
  const path = info.outputPath('failure.png');
@@ -80,26 +87,25 @@ function runner() {
80
87
  catch {
81
88
  failures.push('Failure screenshot capture failed');
82
89
  }
83
- finally {
90
+ const ids = [...new Set([...owned.map(identity => identity.user.id), ...partialIds])];
91
+ // Contexts close while the exact ids are deleted. The DELETE answer names the ids it removed;
92
+ // only when it does not name every one is the list read back to confirm.
93
+ await Promise.all([
94
+ ...contexts.map(context => context.close().catch(() => { failures.push('Browser context cleanup failed'); })),
95
+ ids.length ? (async () => {
84
96
  try {
85
- await context.close();
97
+ const deleted = await timed(info, 'test-user deletion', () => client.call('DELETE', '/auth/test-users', { project_id: projectId, ids }));
98
+ if (ids.every(id => deleted.ids?.includes(id)))
99
+ return;
100
+ const remaining = await timed(info, 'cleanup confirmation', () => client.call('GET', '/auth/test-users', undefined, { project_id: projectId }));
101
+ if (remaining.identities.some(identity => ids.includes(identity.id)))
102
+ failures.push('Test user cleanup unconfirmed');
86
103
  }
87
104
  catch {
88
- failures.push('Browser context cleanup failed');
105
+ failures.push('Test user cleanup unconfirmed; app rows remain');
89
106
  }
90
- }
91
- const ids = [...new Set([...owned.map(identity => identity.user.id), ...partialIds])];
92
- if (ids.length) {
93
- try {
94
- await timed(info, 'test-user deletion', () => client.call('DELETE', '/auth/test-users', { project_id: projectId, ids }));
95
- const remaining = await timed(info, 'cleanup confirmation', () => client.call('GET', '/auth/test-users', undefined, { project_id: projectId }));
96
- if (remaining.identities.some(identity => ids.includes(identity.id)))
97
- failures.push('Test user cleanup unconfirmed');
98
- }
99
- catch {
100
- failures.push('Test user cleanup unconfirmed; app rows remain');
101
- }
102
- }
107
+ })() : Promise.resolve(),
108
+ ]);
103
109
  if (failures.length)
104
110
  throw new Error(failures.join('; '));
105
111
  }
@@ -123,13 +129,14 @@ function runner() {
123
129
  await context.close();
124
130
  }
125
131
  },
126
- newPage: async ({ browser, baseURL, viewport, isMobile, hasTouch, _forms }, use) => {
132
+ newPage: async ({ browser, baseURL, viewport, isMobile, hasTouch, _forms }, use, info) => {
127
133
  const contexts = [];
128
134
  try {
129
135
  await use(async () => {
130
136
  const context = await browser.newContext({ baseURL, viewport, isMobile, hasTouch });
131
137
  contexts.push(context);
132
138
  const page = await context.newPage();
139
+ trackPage(page, titled(info.project.name, info.title));
133
140
  _forms.pages.add(page);
134
141
  return page;
135
142
  });
@@ -142,6 +149,7 @@ function runner() {
142
149
  // Depends on page so its teardown (screenshots, cookie scrubbing) runs while the page is open.
143
150
  _forms: async ({ page }, use, info) => {
144
151
  const run = new FormRun(info);
152
+ trackPage(page, titled(info.project.name, info.title));
145
153
  run.pages.add(page);
146
154
  try {
147
155
  await use(run);
@@ -150,10 +158,10 @@ function runner() {
150
158
  await run.finish();
151
159
  }
152
160
  },
153
- signUp: async ({ _forms }, use) => { await use((page, options) => signUp(_forms, page, options ?? {})); },
154
- verify: async ({ _forms }, use) => { await use((page, person) => verify(_forms, page, person)); },
155
- signIn: async ({ _forms }, use) => { await use((page, person, options) => signIn(_forms, page, person, options ?? {})); },
156
- signOut: async ({ _forms }, use) => { await use((page, options) => signOut(_forms, page, options ?? {})); },
161
+ signUp: async ({ _forms }, use, info) => { await use((page, options) => span('signUp', { test: titled(info.project.name, info.title) }, () => signUp(_forms, page, options ?? {}))); },
162
+ verify: async ({ _forms }, use, info) => { await use((page, person) => span('verify', { test: titled(info.project.name, info.title) }, () => verify(_forms, page, person))); },
163
+ signIn: async ({ _forms }, use, info) => { await use((page, person, options) => span('signIn', { test: titled(info.project.name, info.title) }, () => signIn(_forms, page, person, options ?? {}))); },
164
+ signOut: async ({ _forms }, use, info) => { await use((page, options) => span('signOut', { test: titled(info.project.name, info.title) }, () => signOut(_forms, page, options ?? {}))); },
157
165
  });
158
166
  loaded = { test, expect: pw.expect };
159
167
  return loaded;
@@ -182,6 +190,7 @@ function constrain(client, origin, info) {
182
190
  catch { }
183
191
  }
184
192
  diagnostics(info).request = { method: String(options.method ?? 'GET').toUpperCase(), path: scrub(url.pathname), status: response.status(), code };
193
+ timelineMark('app-request', { test: titled(info.project.name, info.title), method: String(options.method ?? 'GET').toUpperCase(), path: scrub(url.pathname), status: response.status() });
185
194
  return response;
186
195
  } });
187
196
  }
@@ -196,6 +205,10 @@ const eager = (() => { try {
196
205
  catch {
197
206
  return undefined;
198
207
  } })();
208
+ if (eager) {
209
+ markProcessStart('playwright');
210
+ timelineMark('fixtures:loaded');
211
+ }
199
212
  export const test = eager?.test ?? new Proxy((() => { }), {
200
213
  apply: (_target, receiver, args) => Reflect.apply(runner().test, receiver, args),
201
214
  get: (_target, key) => Reflect.get(runner().test, key),
@@ -204,9 +217,9 @@ export const expect = eager?.expect ?? new Proxy((() => { }), {
204
217
  apply: (_target, receiver, args) => Reflect.apply(runner().expect, receiver, args),
205
218
  get: (_target, key) => Reflect.get(runner().expect, key),
206
219
  });
207
- export async function expectRefused(first, second, third) {
220
+ export async function expectRefused(first, second, third, options) {
208
221
  if (typeof second === 'string')
209
- return refusedAs(first, second, third);
222
+ return refusedAs(first, second, third, options ?? {});
210
223
  const response = first;
211
224
  const status = second, code = third;
212
225
  const actual = response.status();
@@ -233,55 +246,101 @@ async function bodyOf(response) {
233
246
  const raw = typeof json?.error === 'string' ? json.error : '';
234
247
  return { code: /^[A-Z_]+$/.test(raw) ? raw : 'none', message: typeof json?.message === 'string' ? scrub(json.message).slice(0, 300) : '', json };
235
248
  }
236
- async function refusedAs(person, target, request) {
249
+ const INCONCLUSIVE = 'looks the same as an empty table, a missing row or a missing route, so it proves nothing on its own. Pass { allowed: <someone the same request succeeds for> } as the positive control.';
250
+ function seen(status, code, message) {
251
+ const kind = status === 400 ? 'a malformed request' : status === 409 ? 'a stale data contract' : `HTTP ${status}`;
252
+ return `${kind} (${status} ${code}${message ? `: ${message}` : ''})`;
253
+ }
254
+ async function refusedAs(person, target, request, options) {
237
255
  const client = clientOf(person);
256
+ const allowed = options.allowed === undefined ? undefined : clientOf(options.allowed);
238
257
  const endpoint = ENDPOINT.exec(target);
239
258
  if (endpoint) {
240
259
  const [, method, path] = endpoint;
241
- const response = await client.fetch(path, { method, ...(method === 'GET' || request === undefined ? {} : { data: request }) });
260
+ const send = (as) => as.fetch(path, { method, ...(method === 'GET' || request === undefined ? {} : { data: request }) });
261
+ const response = await send(client);
242
262
  const status = response.status();
243
- if ([401, 403, 404].includes(status))
244
- return;
245
263
  const { code, message } = await bodyOf(response);
246
- const said = `${target} answered HTTP ${status} ${code}${message ? ` (${message})` : ''}`;
264
+ const said = `${target} answered ${seen(status, code, message)}`;
247
265
  if (status < 400)
248
266
  throw new Error(`expectRefused: ${said}: it was allowed, not refused.`);
249
267
  if (status === 400 || status === 422)
250
268
  throw new Error(`expectRefused: ${said}: the endpoint rejected the input, which says nothing about who is asking. Send a body it accepts from someone who may.`);
251
- throw new Error(`expectRefused: ${said}: a refusal is 401, 403 or 404.`);
269
+ if (![401, 403, 404].includes(status))
270
+ throw new Error(`expectRefused: ${said}: a refusal is 401, 403 or 404.`);
271
+ if (status === 404 && !allowed)
272
+ throw new Error(`expectRefused: ${said}: a 404 ${INCONCLUSIVE}`);
273
+ if (allowed) {
274
+ const control = await send(allowed);
275
+ const c = await bodyOf(control);
276
+ if (control.status() >= 300)
277
+ throw new Error(`expectRefused: ${said}, but the allowed person got ${seen(control.status(), c.code, c.message)} too, so the route or input is wrong and the refusal is not proven.`);
278
+ }
279
+ return;
252
280
  }
253
281
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(target))
254
282
  throw new Error(`expectRefused: "${target}" is neither a table name nor 'METHOD /path'.`);
255
283
  if (!request || typeof request !== 'object' || typeof request.operation !== 'string') {
256
284
  throw new Error(`expectRefused: pass a data request for table ${target}, for example { operation: 'get', id }.`);
257
285
  }
258
- if (!digests.has(client))
259
- throw new Error('expectRefused: act as a page that signed up or signed in (signUp/signIn), a newUser() user, or anonymous.');
286
+ for (const as of [client, ...(allowed ? [allowed] : [])]) {
287
+ if (!digests.has(as))
288
+ throw new Error('expectRefused: act as (and pass allowed as) a page that signed up or signed in (signUp/signIn), a newUser() user, or anonymous.');
289
+ }
260
290
  const operation = request.operation;
291
+ const reading = operation === 'get' || operation === 'list' || operation === 'relation_list';
292
+ const writing = operation === 'update' || operation === 'delete';
293
+ const id = request.id;
294
+ const rowOf = async (as) => {
295
+ const response = await data(as, target, { operation: 'get', id: id });
296
+ const body = await bodyOf(response);
297
+ if (response.status() !== 200)
298
+ throw new Error(`expectRefused: the allowed person could not read ${target} ${String(id)} (${seen(response.status(), body.code, body.message)}), so it is not a control for this row.`);
299
+ return body.json?.data ?? null;
300
+ };
301
+ let before = '';
302
+ if (writing && allowed) {
303
+ const row = await rowOf(allowed);
304
+ before = JSON.stringify(row);
305
+ if (row === null)
306
+ throw new Error(`expectRefused: ${target} ${String(id)} does not exist for the allowed person, so there is nothing to refuse. Create the row first.`);
307
+ }
261
308
  const response = await data(client, target, request);
262
309
  const status = response.status();
263
310
  const { code, message, json } = await bodyOf(response);
264
- const said = `${operation} on ${target} answered HTTP ${status} ${code}${message ? ` (${message})` : ''}`;
311
+ const said = `${operation} on ${target} answered ${seen(status, code, message)}`;
265
312
  if (status === 400 || status === 409)
266
- throw new Error(`expectRefused: ${said}. The request was malformed or the app's data contract changed, so nothing ran and this proves nothing about access.`);
267
- if (status === 401 || status === 403)
268
- return;
269
- if (status === 404 && code === 'DATA_NOT_FOUND')
270
- return;
271
- if (status === 200) {
272
- const rows = json?.data;
273
- if ((operation === 'get') && rows === null)
274
- return;
275
- if ((operation === 'list' || operation === 'relation_list') && Array.isArray(rows) && rows.length === 0)
276
- return;
277
- if (operation === 'list' || operation === 'relation_list')
278
- throw new Error(`expectRefused: ${said}: this person read ${Array.isArray(rows) ? rows.length : 'some'} row(s).`);
279
- if (operation === 'get')
280
- throw new Error(`expectRefused: ${said}: this person read the row.`);
313
+ throw new Error(`expectRefused: ${said}. Nothing ran, so this proves nothing about access.`);
314
+ const rows = json?.data;
315
+ const empty = status === 200 && ((operation === 'get' && rows === null) || ((operation === 'list' || operation === 'relation_list') && Array.isArray(rows) && rows.length === 0));
316
+ const missing = status === 404 && code === 'DATA_NOT_FOUND';
317
+ if (status === 200 && !empty) {
318
+ if (reading)
319
+ throw new Error(`expectRefused: ${said}: this person read ${Array.isArray(rows) ? `${rows.length} row(s)` : 'the row'}.`);
281
320
  throw new Error(`expectRefused: ${said}: the ${operation} was allowed.`);
282
321
  }
283
- throw new Error(`expectRefused: ${said}: not a refusal.`);
322
+ if (status !== 401 && status !== 403 && !empty && !missing)
323
+ throw new Error(`expectRefused: ${said}: not a refusal.`);
324
+ if ((empty || missing) && !allowed)
325
+ throw new Error(`expectRefused: ${said}: ${empty ? 'an empty answer' : 'a 404'} ${INCONCLUSIVE}`);
326
+ if (!allowed)
327
+ return;
328
+ if (reading) {
329
+ const control = await data(allowed, target, request);
330
+ const c = await bodyOf(control);
331
+ const got = c.json?.data;
332
+ const found = control.status() === 200 && (operation === 'get' ? got !== null && got !== undefined : Array.isArray(got) && got.length > 0);
333
+ if (!found)
334
+ throw new Error(`expectRefused: ${said}, but the allowed person got ${control.status() === 200 ? 'nothing' : seen(control.status(), c.code, c.message)} for the same request, so there was nothing to refuse.`);
335
+ }
336
+ else if (writing) {
337
+ const after = await rowOf(allowed);
338
+ if (JSON.stringify(after) !== before)
339
+ throw new Error(`expectRefused: ${said}, but ${target} ${String(id)} ${after === null ? 'is gone' : 'changed'} for the allowed person afterwards.`);
340
+ }
284
341
  }
342
+ /** Test seam: a stand-in request client that data() accepts. */
343
+ export function _fixtureClientForTests(client, digest) { digests.set(client, digest); return client; }
285
344
  export function data(client, table, request) {
286
345
  if (!digests.has(client))
287
346
  throw new Error('Use a newUser or anonymous fixture client');
@@ -289,7 +348,7 @@ export function data(client, table, request) {
289
348
  }
290
349
  export async function ready(page, state = 'ready') {
291
350
  const locator = typeof state === 'string' ? page.locator(state === 'ready' ? '[data-app-state="signed-in"], [data-app-state="signed-out"]' : `[data-app-state="${state}"]`) : state;
292
- await locator.waitFor({ state: 'visible' });
351
+ await span('ready', { state: typeof state === 'string' ? state : 'locator' }, () => locator.waitFor({ state: 'visible' }));
293
352
  }
294
353
  // ---------------------------------------------------------------- sign-up through the app's form
295
354
  //
@@ -356,14 +415,16 @@ class FormRun {
356
415
  failures.push('Failure screenshot capture failed');
357
416
  }
358
417
  }
359
- for (const attempt of this.attempts) {
418
+ // Each account is deleted by its exact id; the deletions run at the same time.
419
+ await Promise.all(this.attempts.map(async (attempt) => {
360
420
  if (attempt.id) {
361
421
  const { client, projectId } = await this.control();
362
422
  const id = attempt.id;
363
- if (await timed(this.info, 'sign-up account deletion', () => deleteAccount(client, projectId, id)))
423
+ const refused = await timed(this.info, 'sign-up account deletion', () => deleteAccount(client, projectId, id));
424
+ if (refused === null)
364
425
  forgetRecord(attempt.record);
365
426
  else
366
- failures.push(`Could not delete the form sign-up account ${attempt.email}; its record is kept and the next somewhere test retries`);
427
+ failures.push(`Could not delete the form sign-up account ${attempt.email} (${refused}); its record is kept and the next somewhere test retries`);
367
428
  }
368
429
  else if (attempt.submitted && !attempt.refused) {
369
430
  // Never delete by address: the account may exist, but this run never learned its id.
@@ -372,7 +433,7 @@ class FormRun {
372
433
  }
373
434
  else
374
435
  forgetRecord(attempt.record);
375
- }
436
+ }));
376
437
  if (failures.length)
377
438
  throw new Error(failures.join('; '));
378
439
  }
@@ -394,7 +455,7 @@ async function pageSays(page) {
394
455
  /** Run one named step; a failure says which step, what the page showed, and the cause, scrubbed. */
395
456
  async function step(page, name, work) {
396
457
  try {
397
- return await work();
458
+ return await span(name, {}, work);
398
459
  }
399
460
  catch (error) {
400
461
  if (error instanceof StepError)
@@ -574,6 +635,7 @@ async function verify(run, page, person) {
574
635
  // a wrong or expired code (401/400) is never retried.
575
636
  let confirmed = await step(page, 'verify: enter the code in the app', () => page.request.post('/api/auth/verify-email', { data: { code } }));
576
637
  for (let wait = 0; confirmed.status() === 404 && wait < 8; wait++) {
638
+ timelineMark('wait', { ms: 250, why: 'verify: code not installed yet (404)' });
577
639
  await new Promise(resolve => setTimeout(resolve, 250));
578
640
  confirmed = await step(page, 'verify: enter the code in the app', () => page.request.post('/api/auth/verify-email', { data: { code } }));
579
641
  }
@@ -625,6 +687,7 @@ async function signIn(run, page, person, options) {
625
687
  const waitMs = Math.min(wait, CODE_GAP_MS);
626
688
  if (run.info.timeout > 0)
627
689
  run.info.setTimeout(run.info.timeout + waitMs + 10_000);
690
+ timelineMark('wait', { ms: waitMs, why: 'signIn: one emailed code a minute' });
628
691
  await page.waitForTimeout(waitMs);
629
692
  result = await submit();
630
693
  }