@uiwwsw/next-test-mode 0.6.0
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.
- package/CHANGELOG.md +70 -0
- package/LICENSE +21 -0
- package/README.md +170 -0
- package/bin/test-mode.mjs +164 -0
- package/dist/browser.d.ts +7 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +455 -0
- package/dist/browser.js.map +1 -0
- package/dist/client.d.ts +14 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +92 -0
- package/dist/client.js.map +1 -0
- package/dist/core.d.ts +160 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +741 -0
- package/dist/core.js.map +1 -0
- package/dist/fetch.d.ts +16 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/fetch.js +212 -0
- package/dist/fetch.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/draft-handler.d.ts +30 -0
- package/dist/internal/draft-handler.d.ts.map +1 -0
- package/dist/internal/draft-handler.js +80 -0
- package/dist/internal/draft-handler.js.map +1 -0
- package/dist/internal/lifecycle.d.ts +7 -0
- package/dist/internal/lifecycle.d.ts.map +1 -0
- package/dist/internal/lifecycle.js +65 -0
- package/dist/internal/lifecycle.js.map +1 -0
- package/dist/internal/next-request.d.ts +11 -0
- package/dist/internal/next-request.d.ts.map +1 -0
- package/dist/internal/next-request.js +22 -0
- package/dist/internal/next-request.js.map +1 -0
- package/dist/internal/overrides.d.ts +25 -0
- package/dist/internal/overrides.d.ts.map +1 -0
- package/dist/internal/overrides.js +111 -0
- package/dist/internal/overrides.js.map +1 -0
- package/dist/internal/paths.d.ts +3 -0
- package/dist/internal/paths.d.ts.map +1 -0
- package/dist/internal/paths.js +22 -0
- package/dist/internal/paths.js.map +1 -0
- package/dist/internal/server-context.d.ts +4 -0
- package/dist/internal/server-context.d.ts.map +1 -0
- package/dist/internal/server-context.js +6 -0
- package/dist/internal/server-context.js.map +1 -0
- package/dist/internal/ssr-state.d.ts +8 -0
- package/dist/internal/ssr-state.d.ts.map +1 -0
- package/dist/internal/ssr-state.js +48 -0
- package/dist/internal/ssr-state.js.map +1 -0
- package/dist/internal/storage.d.ts +6 -0
- package/dist/internal/storage.d.ts.map +1 -0
- package/dist/internal/storage.js +70 -0
- package/dist/internal/storage.js.map +1 -0
- package/dist/internal/symbols.d.ts +3 -0
- package/dist/internal/symbols.d.ts.map +1 -0
- package/dist/internal/symbols.js +3 -0
- package/dist/internal/symbols.js.map +1 -0
- package/dist/next.d.ts +9 -0
- package/dist/next.d.ts.map +1 -0
- package/dist/next.js +32 -0
- package/dist/next.js.map +1 -0
- package/dist/node.d.ts +27 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +144 -0
- package/dist/node.js.map +1 -0
- package/dist/server.d.ts +20 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +36 -0
- package/dist/server.js.map +1 -0
- package/dist/setup.d.ts +14 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +66 -0
- package/dist/setup.js.map +1 -0
- package/dist/types.d.ts +179 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/docs/architecture.md +116 -0
- package/docs/guide.md +171 -0
- package/docs/migration.md +26 -0
- package/docs/releasing.md +41 -0
- package/docs/server-rendering.md +136 -0
- package/docs/story-test-design.md +252 -0
- package/package.json +136 -0
- package/src/browser.ts +593 -0
- package/src/client.ts +114 -0
- package/src/core.ts +1161 -0
- package/src/fetch.ts +271 -0
- package/src/index.ts +5 -0
- package/src/internal/draft-handler.ts +113 -0
- package/src/internal/lifecycle.ts +81 -0
- package/src/internal/next-request.ts +31 -0
- package/src/internal/overrides.ts +141 -0
- package/src/internal/paths.ts +27 -0
- package/src/internal/server-context.ts +6 -0
- package/src/internal/ssr-state.ts +48 -0
- package/src/internal/storage.ts +75 -0
- package/src/internal/symbols.ts +2 -0
- package/src/next.ts +49 -0
- package/src/node.ts +213 -0
- package/src/server.ts +52 -0
- package/src/setup.ts +69 -0
- package/src/types.ts +240 -0
- package/templates/test-mode/README.md +30 -0
- package/templates/test-mode/config.ts +25 -0
- package/templates/test-mode/features/auth.ts +23 -0
- package/templates/test-mode/index.ts +11 -0
- package/templates/test-mode/install.ts +13 -0
- package/templates/test-mode/stories/auth.stories.ts +10 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.6.0 — Next Test Mode
|
|
4
|
+
|
|
5
|
+
- Rename the npm package to `@uiwwsw/next-test-mode` and repository to `uiwwsw/next-test-mode`; retain the old package for existing installs and document migration.
|
|
6
|
+
- Add Next App Router Draft Mode coordination with unchanged fetch call sites: CSR, SSR, SSG, ISR, force-static, generated routes and cached fetch previews.
|
|
7
|
+
- Generate server/client instrumentation plus a guarded Draft POST route; migrate unchanged 0.5.0 hooks with `init --migrate`. Production stays disabled unless explicitly enabled for QA.
|
|
8
|
+
- Isolate request state and control/authorization fetches; serialize rapid Console changes, preserve pre-existing CMS Draft sessions and restore ordinary caches on clear.
|
|
9
|
+
- Replace the public demo with a real Next.js app featuring four render modes, Console/JSON editing, HTTP errors and mobile layouts.
|
|
10
|
+
- Add production, Cache Components and disabled-build integration checks. Document the version-sensitive Draft provider bridge, Next 16.3.5 compatibility and Node 20.9 minimum.
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
## 0.5.0 — 2026-09-14
|
|
14
|
+
|
|
15
|
+
- Keep existing browser and server `fetch()` call sites: one-call browser setup, a Node request wrapper, and a Next.js 16 Node instrumentation adapter.
|
|
16
|
+
- Add `npx @uiwwsw/test-mode init --next` to generate first-time setup, detect src/TypeScript projects, and preserve existing instrumentation files.
|
|
17
|
+
- Opt in to SSR JSON synchronization: Console `mock` / `patch` values survive reloads and refresh server-rendered HTML automatically. Session cookies are limited to 3,500 encoded bytes; rejected changes preserve working state.
|
|
18
|
+
- Isolate server state and counters per request. Keep overrides outside Next fetch caching and avoid browser hydration attribute changes.
|
|
19
|
+
- Add a public interactive SSR demo, raw-HTML and concurrent-visitor regressions, plus a real Next.js app installation test in CI.
|
|
20
|
+
- Preserve low-level APIs and the default memory-only lifetime of browser JSON overrides. Explain automatic setup, lifecycle, framework support and cache boundaries in the README and guides.
|
|
21
|
+
|
|
22
|
+
## 0.4.1 — 2026-09-14
|
|
23
|
+
|
|
24
|
+
- Lead the README, npm presentation and live demo with three benefits: unchanged browser fetch call sites after bootstrap setup, isolated reusable scenario files, and immediate console data experiments.
|
|
25
|
+
- Show the same application API call with different test data, and explain when to keep an experiment temporary or move it into an app-owned test-mode folder.
|
|
26
|
+
- Refresh the banner and recorded demo while retaining explicit CSR/SSR and persistence boundaries. Runtime APIs are unchanged.
|
|
27
|
+
|
|
28
|
+
## 0.4.0 — 2026-09-14
|
|
29
|
+
|
|
30
|
+
- Define test mode as console-first API response overrides for UI debugging, with an explicit CSR/SSR support matrix and updated playground guidance.
|
|
31
|
+
- Add `createServerTestMode` and the `./server` entry point: a fresh runtime and fetch per incoming server request, selected from registered cookie entries, with isolated counters and server-authored overrides.
|
|
32
|
+
- Add `cookieHeader: false` to the fetch adapter so outgoing API authentication cookies cannot override an already captured request selection. Existing string/null behavior remains compatible.
|
|
33
|
+
- Include a runnable Node HTTP SSR example, Next.js integration guidance, and browser-to-server cookie handoff tests. Temporary console JSON remains local to the browser.
|
|
34
|
+
|
|
35
|
+
## 0.3.1 — 2026-09-14
|
|
36
|
+
|
|
37
|
+
- Link directly to the public Vercel playground from the README and demo documentation.
|
|
38
|
+
- Allow longer npm registry propagation during post-publication verification, avoiding a failed run after a successful publish.
|
|
39
|
+
|
|
40
|
+
## 0.3.0 — 2026-09-14
|
|
41
|
+
|
|
42
|
+
- Add immediate console response values with `test.mock`, `test.patch`, `test.overrides` and `test.reset`, backed by typed core APIs. Values are detached JSON snapshots and never persisted.
|
|
43
|
+
- Give temporary responses explicit path/method precedence, transactional input validation, mock HTTP status control and cookie-scoped server isolation.
|
|
44
|
+
- Rebuild the demo around DevTools commands and a real JSON editor, automatic request refresh, HTTP/response inspection, request counts, error handling and reset.
|
|
45
|
+
- Add a static sample API, portable demo build, and root Vercel configuration for Git import without secrets or server functions.
|
|
46
|
+
- Verify custom values, JSON errors, rapid edits, keyboard/copy flow and mobile/nested-path hosting.
|
|
47
|
+
|
|
48
|
+
## 0.2.0 — 2026-09-09
|
|
49
|
+
|
|
50
|
+
- Redesign the README and npm presentation with a custom banner, an actual four-state demo, concise onboarding and dedicated usage/release guides.
|
|
51
|
+
- Split the runtime, browser controls, fetch adapter, public types and shared helpers; add `./core`, `./browser` and `./fetch` exports without changing root imports.
|
|
52
|
+
- Preserve active scenarios on unknown story names; notify subscribers after successful dynamic registration.
|
|
53
|
+
- Make console/overlay installation transactional, teardown idempotent, and nested installation safe in either cleanup order. Continue releasing resources when an extension teardown fails.
|
|
54
|
+
- Synchronize cross-tab storage removal without resurrecting stale cookie selections.
|
|
55
|
+
- Add browser lifecycle regressions, a real local API playground, and consumer tests for every public entry point.
|
|
56
|
+
|
|
57
|
+
## 0.1.0 — 2026-09-09
|
|
58
|
+
|
|
59
|
+
First npm release of the API scenario runtime for development and QA.
|
|
60
|
+
|
|
61
|
+
- Mock and patch API responses; combine entries into named stories controlled from a browser console and page-aware overlay.
|
|
62
|
+
- Extract the fetch adapter and fix DELETE bodies, Request header replacement, empty bodies, form inputs, binary payloads, HEAD and bodyless HTTP statuses.
|
|
63
|
+
- Leave unmatched responses and streaming bodies untouched. Preserve response metadata and application headers when patching, and support JSON null patch results.
|
|
64
|
+
- Respect cancellation and restore fetch hooks safely, including nested installs.
|
|
65
|
+
- Isolate request counts by runtime; validate ambiguous features and conflicting stories; canonicalize API aliases and roll back invalid registration.
|
|
66
|
+
- Make browser subscriptions fire once and keep controls usable when persistence fails. Clean up overlay markers and pending navigation refreshes.
|
|
67
|
+
- Require explicit development/test activation and replace application-specific storage/event defaults with neutral names.
|
|
68
|
+
- Fix typed mock/patch registration for consumers and ship usable source/declaration maps.
|
|
69
|
+
- Add Node and Chromium regression tests, real tarball installation/type checks, npm lockfile and guarded GitHub Actions publication using NPM_TOKEN/provenance with OIDC support.
|
|
70
|
+
- Rewrite the README around the package's purpose, limits, configuration, request lifecycle and release process.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 uiwwsw
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/uiwwsw/next-test-mode/v0.6.0/docs/assets/hero.png" width="100%" alt="Next Test Mode — Same API calls. Your test data. CSR, SSR, ISR and SSG from one Console." />
|
|
3
|
+
</p>
|
|
4
|
+
<p align="center">
|
|
5
|
+
<strong>호출 코드는 그대로. 테스트 데이터는 따로. 확인은 콘솔에서.</strong><br />
|
|
6
|
+
Keep your fetch calls. Keep scenarios separate. Preview from DevTools.
|
|
7
|
+
</p>
|
|
8
|
+
<p align="center">
|
|
9
|
+
<a href="https://www.npmjs.com/package/@uiwwsw/next-test-mode"><img src="https://img.shields.io/npm/v/@uiwwsw/next-test-mode?style=flat-square&color=173c36" alt="npm version" /></a>
|
|
10
|
+
<a href="https://github.com/uiwwsw/next-test-mode/actions/workflows/ci.yml"><img src="https://github.com/uiwwsw/next-test-mode/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
|
|
11
|
+
<img src="https://img.shields.io/badge/Next.js-App_Router-173c36?style=flat-square" alt="Next.js App Router" />
|
|
12
|
+
<a href="https://github.com/uiwwsw/next-test-mode/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-62796f?style=flat-square" alt="MIT license" /></a>
|
|
13
|
+
</p>
|
|
14
|
+
<p align="center">
|
|
15
|
+
<a href="https://test-mode-tau.vercel.app/">Live demo ↗</a> ·
|
|
16
|
+
<a href="#quick-start">Quick start</a> ·
|
|
17
|
+
<a href="#rendering-support">지원 범위</a> ·
|
|
18
|
+
<a href="https://github.com/uiwwsw/next-test-mode/blob/main/docs/guide.md">API 가이드</a> ·
|
|
19
|
+
<a href="https://github.com/uiwwsw/next-test-mode/blob/main/docs/migration.md">기존 패키지에서 이전</a>
|
|
20
|
+
</p>
|
|
21
|
+
|
|
22
|
+
**Next Test Mode는 Next.js 앱의 API 응답을 콘솔에서 바꿔 화면 상태를 재현하는 개발·QA 도구입니다.** 빈 목록, 다른 가격, 서버 오류를 실제 화면에서 확인하세요. CSR은 브라우저 응답을 바꾸고, SSR·ISR·SSG는 **Next Draft Mode를 자동으로 연결해 해당 브라우저 세션에서 새로 렌더**합니다.
|
|
23
|
+
|
|
24
|
+
> `@uiwwsw/test-mode`의 새 이름은 **`@uiwwsw/next-test-mode`**입니다. [이전 가이드](https://github.com/uiwwsw/next-test-mode/blob/main/docs/migration.md).
|
|
25
|
+
|
|
26
|
+
## Why Next Test Mode
|
|
27
|
+
|
|
28
|
+
| 호출 코드는 그대로 | 테스트 데이터는 따로 | 확인은 콘솔에서 |
|
|
29
|
+
| :--- | :--- | :--- |
|
|
30
|
+
| 최초 설정 후 기존 `fetch()`를 계속 사용합니다. 각 API 호출부에 테스트 함수나 조건 분기를 추가할 필요가 없습니다. | 한 번 확인할 값은 콘솔에서 끝내고, 반복할 시나리오는 `src/test-mode/` 같은 전용 폴더에서 수정하고 공유합니다. | `test.patch()` 한 줄로 가격을 바꾸고 `test.mock()`으로 빈 목록·오류를 넣습니다. `test.clear()`로 원래 응답에 돌아갑니다. |
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
// 앱의 API 호출: 테스트를 켜도 이 코드는 그대로입니다.
|
|
34
|
+
const response = await fetch('https://api.example.com/api/cart');
|
|
35
|
+
const cart = await response.json();
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```js
|
|
39
|
+
// DevTools → Console: 자신의 API pathname을 사용하세요.
|
|
40
|
+
test.patch('/api/cart', { total: 9.99 });
|
|
41
|
+
// Draft Mode 연결 → 자동 새로고침 → 바뀐 데이터로 화면 확인
|
|
42
|
+
test.clear();
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Quick start
|
|
46
|
+
|
|
47
|
+
Next.js **16 App Router / Node.js 20.9+** 프로젝트 루트에서:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npm install @uiwwsw/next-test-mode
|
|
51
|
+
npx @uiwwsw/next-test-mode init
|
|
52
|
+
npm run dev
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
설치 명령이 `app/` 또는 `src/app/`, JavaScript/TypeScript를 감지해 **세 파일**을 생성합니다.
|
|
56
|
+
|
|
57
|
+
| 파일 | 하는 일 |
|
|
58
|
+
| :--- | :--- |
|
|
59
|
+
| `instrumentation.ts` 또는 `.js` | 서버의 기존 fetch에 요청별 테스트 데이터 연결 |
|
|
60
|
+
| `instrumentation-client.ts` 또는 `.js` | Console·브라우저 fetch·Draft Mode·자동 새로고침 연결 |
|
|
61
|
+
| `app/api/next-test-mode/route.ts` 또는 `.js` | Next.js의 Draft Mode 쿠키를 켜고 끄는 POST 경로 |
|
|
62
|
+
|
|
63
|
+
페이지, API 함수, Next 설정 파일은 수정하지 않습니다. 기존 사용자 파일이 있으면 변경 없이 합칠 코드를 출력합니다. 워커나 별도 서버는 필요하지 않습니다.
|
|
64
|
+
|
|
65
|
+
기본 설정은 개발 환경에서만 켜집니다. **QA 배포에서도 사용하려면 `NEXT_PUBLIC_NEXT_TEST_MODE=1`을 빌드와 실행 환경에 설정**하세요. [생성 코드와 접근 제어](https://github.com/uiwwsw/next-test-mode/blob/main/docs/server-rendering.md).
|
|
66
|
+
|
|
67
|
+
## See it in action
|
|
68
|
+
|
|
69
|
+
**[CSR](https://test-mode-tau.vercel.app/csr) · [SSR](https://test-mode-tau.vercel.app/ssr) · [ISR](https://test-mode-tau.vercel.app/isr) · [SSG](https://test-mode-tau.vercel.app/ssg)** — 같은 장바구니를 네 가지 렌더 방식으로 직접 비교하세요.
|
|
70
|
+
|
|
71
|
+
<p align="center">
|
|
72
|
+
<img src="https://raw.githubusercontent.com/uiwwsw/next-test-mode/v0.6.0/docs/assets/scenarios.gif" width="960" alt="실제 Next.js 데모: SSG 원래 가격, 콘솔 patch, SSR에서도 같은 값, HTTP 503, 원래 캐시 응답 복귀." />
|
|
73
|
+
</p>
|
|
74
|
+
|
|
75
|
+
데모의 DevTools Console에 입력하거나, 화면의 JSON 편집기에서 원하는 값을 적용하세요.
|
|
76
|
+
|
|
77
|
+
```js
|
|
78
|
+
test.patch('/api/cart.json', { total: 9.99 });
|
|
79
|
+
test.mock('/api/cart.json', { items: [], total: 0 });
|
|
80
|
+
test.mock('/api/cart.json', { message: 'Try again' }, { status: 503 });
|
|
81
|
+
test.overrides(); // 직접 입력한 값 확인
|
|
82
|
+
test.reset('/api/cart.json'); // 이 경로의 직접 입력만 제거
|
|
83
|
+
test.clear(); // 모든 입력과 시나리오 해제
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
SSR·ISR·SSG 탭에서는 **서버가 보낸 HTML 자체에 변경된 값이 들어갑니다.** 다른 브라우저 세션의 원래 응답은 유지됩니다. JSON 상태는 같은 브라우저의 탭이 공유하며 새로고침 후에도 유지됩니다. 테스트가 끝나면 `test.clear()`를 사용하세요.
|
|
87
|
+
|
|
88
|
+
## Rendering support
|
|
89
|
+
|
|
90
|
+
| 렌더 방식 | Console 변경 후 동작 |
|
|
91
|
+
| :--- | :--- |
|
|
92
|
+
| **CSR** | 브라우저 fetch 응답 교체 또는 patch, 페이지 자동 새로고침 |
|
|
93
|
+
| **SSR / Server Components** | 해당 요청의 서버 fetch에 값 적용 → 새 HTML |
|
|
94
|
+
| **SSG / `force-static`** | Draft Mode에서 정적 결과를 우회해 세션별 동적 미리보기 |
|
|
95
|
+
| **ISR** | Draft Mode에서 기존 페이지·데이터 캐시를 우회해 미리보기. 공용 ISR 결과는 변경하지 않음 |
|
|
96
|
+
| **`unstable_cache` / `use cache`** | Draft Mode의 캐시 우회 경로에서 실행되는 fetch에 적용 |
|
|
97
|
+
| **`generateStaticParams`** | 빌드에서 생성한 경로의 페이지 미리보기 지원. 콘솔로 빌드 시 경로 목록을 다시 만들지는 않음 |
|
|
98
|
+
|
|
99
|
+
`test.clear()`는 이 도구가 연 Draft Mode를 해제해 원래 캐시 경로로 복귀합니다. **SSG 파일을 다시 쓰거나 모든 방문자의 ISR 캐시를 갱신하는 기능은 아닙니다.** 이미 켜진 CMS Draft 세션은 해제하지 않습니다.
|
|
100
|
+
|
|
101
|
+
실제 production 빌드로 검증한 기준은 **Next.js 16.3.5 / App Router / Node 런타임**입니다. Pages Router, Edge, `output: 'export'`는 자동 연결 대상이 아닙니다. 직접 DB 조회, XHR·WebSocket, fetch를 거치지 않는 외부 캐시에도 별도 어댑터가 필요합니다. 캐시 내부의 요청 쿠키를 읽는 작은 Next 내부 브리지가 있어, Next 버전 업그레이드 시 production 회귀 테스트가 필요합니다. [동작 원리와 호환성](https://github.com/uiwwsw/next-test-mode/blob/main/docs/server-rendering.md).
|
|
102
|
+
|
|
103
|
+
## Try once, or keep it in a folder
|
|
104
|
+
|
|
105
|
+
**잠깐 확인할 테스트는 콘솔에서 끝내세요.** `test.mock()` / `test.patch()` → 화면 확인 → `test.clear()`. 임시 실험 때문에 파일이나 API 호출 코드를 고칠 필요가 없습니다.
|
|
106
|
+
|
|
107
|
+
**반복할 테스트는 별도 폴더에서 관리하세요.**
|
|
108
|
+
|
|
109
|
+
```text
|
|
110
|
+
src/
|
|
111
|
+
api/cart.ts # 기존 API 호출
|
|
112
|
+
test-mode/
|
|
113
|
+
catalog.ts # 브라우저·서버에서 공유할 등록 목록
|
|
114
|
+
features/cart.ts # API별 mock / patch와 데이터
|
|
115
|
+
stories/cart.stories.ts # 여러 API를 묶은 화면 시나리오
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
// src/test-mode/catalog.ts
|
|
120
|
+
import { defineMock } from '@uiwwsw/next-test-mode/core';
|
|
121
|
+
|
|
122
|
+
export const catalog = {
|
|
123
|
+
definitions: [
|
|
124
|
+
defineMock('/api/cart', () => ({ items: [], total: 0 }), {
|
|
125
|
+
caseKey: 'empty',
|
|
126
|
+
pages: ['/cart'],
|
|
127
|
+
}),
|
|
128
|
+
],
|
|
129
|
+
};
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
이 목록을 생성된 두 instrumentation의 `setupNextTestMode({ ...catalog, enabled: true })`와 `setupNextTestModeClient({ ...catalog, enabled: ... })`에 전달하면 Console에서 `test.feat.add('/api/cart:empty')`로 선택할 수 있습니다. 여러 API를 묶은 story도 `test.story('cart.empty')`로 활성화합니다. 서버에서도 쓸 정의에는 브라우저 전용 코드를 넣지 마세요. [스타터와 연결 예시](https://github.com/uiwwsw/next-test-mode/tree/main/templates/test-mode).
|
|
133
|
+
|
|
134
|
+
## Details that matter
|
|
135
|
+
|
|
136
|
+
- 직접 입력은 **GET + 정확한 pathname**에 매칭합니다. 다른 메서드는 `{ method: 'POST' }` 옵션으로 지정합니다. 여러 호스트의 같은 pathname은 함께 매칭됩니다.
|
|
137
|
+
- `patch`는 실제 응답의 최상위 필드를 덮어씁니다. 중첩 객체와 배열은 통째로 교체되며, 실제 네트워크 요청은 실행됩니다. `mock`은 매칭된 요청의 응답을 직접 만듭니다.
|
|
138
|
+
- 쿠키로 전달하는 전체 선택·JSON 상태는 URL 인코딩 후 **3,500바이트**까지입니다. 큰 응답은 작은 patch 또는 파일에 정의한 시나리오로 관리하세요. 브라우저 세션 복원 설정에 따라 쿠키도 복원될 수 있습니다.
|
|
139
|
+
- Draft 연결 실패는 Console 오류와 `next-test-mode:error` 이벤트로 알리며 자동 새로고침하지 않습니다. `ready` / `sync()`로 성공 여부를 기다릴 수 있습니다. [클라이언트 API](https://github.com/uiwwsw/next-test-mode/blob/main/docs/server-rendering.md#클라이언트-연결-상태).
|
|
140
|
+
- 테스트 쿠키는 로그인 자격이 아닙니다. QA 환경의 접근 권한은 앱이 관리합니다. 들어온 인증 쿠키를 외부 API에 자동 전달하지 않습니다.
|
|
141
|
+
- 이 패키지는 **화면 상태를 재현하는 도구**입니다. 자동 assertion·합격 판정은 Playwright나 Vitest가 담당합니다.
|
|
142
|
+
|
|
143
|
+
## Framework-independent APIs
|
|
144
|
+
|
|
145
|
+
기존 범용 core·browser·Node API도 새 이름 아래 유지합니다. Next.js는 선택적 peer이며, 범용 API는 Next 없이 설치할 수 있습니다. 외부 런타임 의존성은 없습니다.
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { setupTestMode } from '@uiwwsw/next-test-mode';
|
|
149
|
+
import { createTestMode, defineMock } from '@uiwwsw/next-test-mode/core';
|
|
150
|
+
import { createMockFetch } from '@uiwwsw/next-test-mode/fetch';
|
|
151
|
+
import { withTestMode } from '@uiwwsw/next-test-mode/node';
|
|
152
|
+
import { createServerTestMode } from '@uiwwsw/next-test-mode/server';
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
일반 브라우저 앱은 `setupTestMode({ enabled: true, refresh: () => refetch() })`를 시작 시 한 번 연결합니다. 이 범용 설정의 직접 JSON은 기본적으로 메모리에만 남습니다. Next에서는 Draft Mode를 연결하는 `init` 설정을 사용하세요. [전체 API 가이드](https://github.com/uiwwsw/next-test-mode/blob/main/docs/guide.md).
|
|
156
|
+
|
|
157
|
+
## Develop & release
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
npm ci
|
|
161
|
+
npx playwright install chromium
|
|
162
|
+
npm run ci # 타입, 런타임, tarball 설치와 소비자 타입 검사
|
|
163
|
+
npm run test:browser # 브라우저 Console·fetch·Draft 연결
|
|
164
|
+
npm run test:next # 실제 Next dev/production/Cache Components/비활성 배포
|
|
165
|
+
npm run test:demo # 네 렌더 모드와 모바일 JSON 편집기
|
|
166
|
+
npm run dev:demo # 실제 Next.js 데모
|
|
167
|
+
npm run build:demo # Vercel 배포용 Next 빌드
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
검증된 main의 릴리스 태그를 GitHub Release로 발행하면, CI를 다시 통과한 패키지가 `NPM_TOKEN`을 사용하는 Actions에서 npm provenance와 함께 배포됩니다. [배포 절차](https://github.com/uiwwsw/next-test-mode/blob/main/docs/releasing.md) · [설계](https://github.com/uiwwsw/next-test-mode/blob/main/docs/architecture.md) · [Changelog](https://github.com/uiwwsw/next-test-mode/blob/main/CHANGELOG.md).
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
existsSync,
|
|
4
|
+
lstatSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
readFileSync,
|
|
7
|
+
unlinkSync,
|
|
8
|
+
writeFileSync,
|
|
9
|
+
} from "node:fs";
|
|
10
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
11
|
+
|
|
12
|
+
const args = process.argv.slice(2);
|
|
13
|
+
const usage = "Usage: next-test-mode init [--dir <app-directory>] [--migrate]";
|
|
14
|
+
const environment =
|
|
15
|
+
"process.env.NODE_ENV === 'development' || process.env.NEXT_PUBLIC_NEXT_TEST_MODE === '1'";
|
|
16
|
+
if (!args.length || args.includes("--help") || args.includes("-h")) {
|
|
17
|
+
console.log(
|
|
18
|
+
`${usage}\nCreates Next.js App Router instrumentation and a Draft Mode route. Existing custom files are never overwritten.`,
|
|
19
|
+
);
|
|
20
|
+
} else {
|
|
21
|
+
try {
|
|
22
|
+
if (args.shift() !== "init") throw new Error(usage);
|
|
23
|
+
let directory = ".";
|
|
24
|
+
let migrate = false;
|
|
25
|
+
while (args.length) {
|
|
26
|
+
const arg = args.shift();
|
|
27
|
+
if (arg === "--dir" && args.length) directory = args.shift();
|
|
28
|
+
else if (arg === "--migrate") migrate = true;
|
|
29
|
+
else if (arg !== "--next") throw new Error(usage);
|
|
30
|
+
}
|
|
31
|
+
const root = resolve(directory);
|
|
32
|
+
const manifest = JSON.parse(
|
|
33
|
+
readFileSync(join(root, "package.json"), "utf8"),
|
|
34
|
+
);
|
|
35
|
+
if (!manifest.dependencies?.next && !manifest.devDependencies?.next)
|
|
36
|
+
throw new Error(
|
|
37
|
+
"Run this in a Next.js app, or pass --dir <app-directory>.",
|
|
38
|
+
);
|
|
39
|
+
const folder = existsSync(join(root, "app"))
|
|
40
|
+
? root
|
|
41
|
+
: existsSync(join(root, "src/app"))
|
|
42
|
+
? join(root, "src")
|
|
43
|
+
: null;
|
|
44
|
+
if (!folder)
|
|
45
|
+
throw new Error(
|
|
46
|
+
"Automatic Draft Mode setup requires a Next.js App Router app (app/ or src/app/).",
|
|
47
|
+
);
|
|
48
|
+
const extension = existsSync(join(root, "tsconfig.json")) ? "ts" : "js";
|
|
49
|
+
const snippets = {
|
|
50
|
+
instrumentation: `// Generated by @uiwwsw/next-test-mode
|
|
51
|
+
export async function register() {
|
|
52
|
+
if (process.env.NEXT_RUNTIME === 'nodejs' && (${environment})) {
|
|
53
|
+
const { setupNextTestMode } = await import('@uiwwsw/next-test-mode/next');
|
|
54
|
+
setupNextTestMode({ enabled: true });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
`,
|
|
58
|
+
"instrumentation-client": `// Generated by @uiwwsw/next-test-mode
|
|
59
|
+
import { setupNextTestModeClient } from '@uiwwsw/next-test-mode/client';
|
|
60
|
+
|
|
61
|
+
setupNextTestModeClient({ enabled: ${environment} });
|
|
62
|
+
`,
|
|
63
|
+
"app/api/next-test-mode/route": `// Generated by @uiwwsw/next-test-mode
|
|
64
|
+
import { createDraftModeHandler } from '@uiwwsw/next-test-mode/next';
|
|
65
|
+
|
|
66
|
+
export const POST = createDraftModeHandler({ enabled: ${environment} });
|
|
67
|
+
`,
|
|
68
|
+
};
|
|
69
|
+
// The old installer generated exactly these files. --migrate only replaces
|
|
70
|
+
// recognized generated content, never an application's custom hooks.
|
|
71
|
+
const legacy = {
|
|
72
|
+
instrumentation: `export async function register() {
|
|
73
|
+
if (process.env.NODE_ENV === 'development' && process.env.NEXT_RUNTIME === 'nodejs') {
|
|
74
|
+
const { setupNextTestMode } = await import('@uiwwsw/test-mode/next');
|
|
75
|
+
setupNextTestMode();
|
|
76
|
+
}
|
|
77
|
+
}`,
|
|
78
|
+
"instrumentation-client": `import { setupTestMode } from '@uiwwsw/test-mode';
|
|
79
|
+
|
|
80
|
+
setupTestMode({ enabled: process.env.NODE_ENV === 'development', ssr: true });`,
|
|
81
|
+
};
|
|
82
|
+
const exists = (path) => {
|
|
83
|
+
try {
|
|
84
|
+
lstatSync(path);
|
|
85
|
+
return true;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (error.code === "ENOENT") return false;
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const planned = Object.entries(snippets).map(([name, snippet]) => ({
|
|
92
|
+
name,
|
|
93
|
+
snippet,
|
|
94
|
+
file: join(folder, `${name}.${extension}`),
|
|
95
|
+
}));
|
|
96
|
+
const conflicts = [];
|
|
97
|
+
for (const item of planned) {
|
|
98
|
+
for (const location of [root, join(root, "src")])
|
|
99
|
+
for (const ext of [
|
|
100
|
+
"ts",
|
|
101
|
+
"js",
|
|
102
|
+
"tsx",
|
|
103
|
+
"jsx",
|
|
104
|
+
"mjs",
|
|
105
|
+
"cjs",
|
|
106
|
+
"mts",
|
|
107
|
+
"cts",
|
|
108
|
+
]) {
|
|
109
|
+
const file = join(location, `${item.name}.${ext}`);
|
|
110
|
+
if (!exists(file)) continue;
|
|
111
|
+
const stat = lstatSync(file);
|
|
112
|
+
if (stat.isSymbolicLink() || !stat.isFile() || file !== item.file) {
|
|
113
|
+
conflicts.push(relative(root, file));
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const content = readFileSync(file, "utf8");
|
|
117
|
+
if (content === item.snippet) {
|
|
118
|
+
item.skip = true;
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (
|
|
122
|
+
migrate &&
|
|
123
|
+
legacy[item.name] &&
|
|
124
|
+
[
|
|
125
|
+
legacy[item.name],
|
|
126
|
+
legacy[item.name].replaceAll(
|
|
127
|
+
"@uiwwsw/test-mode",
|
|
128
|
+
"@uiwwsw/next-test-mode",
|
|
129
|
+
),
|
|
130
|
+
].includes(content.trim())
|
|
131
|
+
)
|
|
132
|
+
item.previous = content;
|
|
133
|
+
else conflicts.push(relative(root, file));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (conflicts.length)
|
|
137
|
+
throw new Error(
|
|
138
|
+
`Existing custom setup: ${conflicts.join(", ")}.\nNo files changed. Merge these calls into your hooks, or use --migrate for unchanged 0.5.0-generated files:\n${planned.map((item) => `\n${relative(root, item.file)}:\n${item.snippet}`).join("")}`,
|
|
139
|
+
);
|
|
140
|
+
const written = [];
|
|
141
|
+
try {
|
|
142
|
+
for (const item of planned) {
|
|
143
|
+
if (item.skip) continue;
|
|
144
|
+
mkdirSync(dirname(item.file), { recursive: true });
|
|
145
|
+
writeFileSync(item.file, item.snippet, {
|
|
146
|
+
flag: item.previous === undefined ? "wx" : "w",
|
|
147
|
+
});
|
|
148
|
+
written.push(item);
|
|
149
|
+
}
|
|
150
|
+
} catch (error) {
|
|
151
|
+
for (const item of written.reverse()) {
|
|
152
|
+
if (item.previous === undefined) unlinkSync(item.file);
|
|
153
|
+
else writeFileSync(item.file, item.previous);
|
|
154
|
+
}
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
console.log(
|
|
158
|
+
`${written.length ? "Configured" : "Already configured"} Next Test Mode: ${planned.map((item) => relative(root, item.file)).join(", ")}.\nRestart your dev server, then use your API pathname in Console:\n test.patch('/api/cart', { total: 9.99 });\nDraft Mode starts automatically; test.clear() returns to ordinary cached pages.\nFor a QA production build, set NEXT_PUBLIC_NEXT_TEST_MODE=1 at build and runtime.\nCSR, SSR, ISR and SSG previews use the same fetch calls. JSON state limit: 3500 encoded bytes.`,
|
|
159
|
+
);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
console.error(error.message);
|
|
162
|
+
process.exitCode = 1;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { TestModeExtension, ToggleExtensionOptions, TestModeOverlayOptions, TestModeConsoleOptions } from "./types.js";
|
|
2
|
+
import type { TestMode } from "./core.js";
|
|
3
|
+
export type { TestModeConsoleOptions, TestModeOverlayOptions, TestModeExtension, TestModeExtensionContext, ToggleExtensionOptions, } from "./types.js";
|
|
4
|
+
export declare const createToggleExtension: ({ aliases, key, label, onDisable, onEnable, setup, storageKey, }: ToggleExtensionOptions) => TestModeExtension;
|
|
5
|
+
export declare const installConsole: (testMode: TestMode, { extensions, globalName, installExtensions: shouldInstallExtensions, namespace, }?: TestModeConsoleOptions) => () => void;
|
|
6
|
+
export declare const installTestModeOverlay: (testMode: TestMode, { datasetName, document: documentRef, extensions, globalName, installConsole: shouldInstallConsole, namespace, watermarkText, zIndex, }?: TestModeOverlayOptions) => () => void;
|
|
7
|
+
//# sourceMappingURL=browser.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAGV,iBAAiB,EACjB,sBAAsB,EACtB,sBAAsB,EACtB,sBAAsB,EAEvB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAI1C,YAAY,EACV,sBAAsB,EACtB,sBAAsB,EACtB,iBAAiB,EACjB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,qBAAqB,GAAI,kEAQnC,sBAAsB,KAAG,iBAgF3B,CAAC;AAgDF,eAAO,MAAM,cAAc,GACzB,UAAU,QAAQ,EAClB,qFAKG,sBAA2B,eA0O/B,CAAC;AAgEF,eAAO,MAAM,sBAAsB,GACjC,UAAU,QAAQ,EAClB,0IAWG,sBAA2B,eAoH/B,CAAC"}
|