Into the app앱 안으로

A bundle on disk is not a bundle in your APK. Staging is the step between.

디스크의 번들은 APK 안의 번들이 아닙니다. 스테이징이 그 사이의 단계입니다.

What staging does스테이징이 하는 일

stagePythonBundleAndroid, …Ios and …Desktop each copy a bundle's python/ directory into build/pythonStaging/<platform>/python/. stagePythonBundle runs all three.

stagePythonBundleAndroid, …Ios, …Desktop 은 각각 번들의 python/ 디렉터리를 build/pythonStaging/<platform>/python/ 로 복사합니다. stagePythonBundle 은 셋을 모두 실행합니다.

  • Only python/ travels: the manifest is build metadata.python/ 만 옮깁니다: 매니페스트는 빌드 메타데이터입니다.
  • The previous payload is deleted first, so a module you removed stops shipping.이전 페이로드를 먼저 지우므로, 지운 모듈은 더 이상 실리지 않습니다.
  • The payload is a declared input: change your Python and the next build re-stages.페이로드가 선언된 입력이라, Python 을 바꾸면 다음 빌드가 다시 스테이징합니다.
  • Everything stays under build/; nothing is generated into src/.모든 것이 build/ 아래에 있고, src/ 에는 아무것도 생성하지 않습니다.

Which bundle goes where어느 번들이 어디로

A packaging step takes one directory, so one variant is chosen per destination: only from variants of the active build type:

패키징 단계는 디렉터리 하나를 받으므로 목적지마다 변형 하나를 고릅니다; 활성 빌드 타입의 변형 중에서만.

Destination목적지Chosen variant고르는 변형Handed to넘겨받는 곳
Desktop데스크톱the one whose triple is the host's, else the first declared호스트와 트리플이 같은 것, 없으면 처음 선언된 것the JVM target's processResources → jarJVM 타깃의 processResources → jarpartial부분
AndroidAndroidthe first declared처음 선언된 것android.sourceSets.main.assets → APKandroid.sourceSets.main.assets → APKpartial부분
iOSiOSthe first declared처음 선언된 것stagePythonBundleIosForXcode prints the path; an Xcode build phase copies itstagePythonBundleIosForXcode 가 경로를 출력하고 Xcode 빌드 단계가 복사합니다partial부분

Without a declared platform variant, every destination gets the single host bundle and the build logs that it did so. A destination with no matching variant stages nothing rather than a bundle built for another platform.

선언된 플랫폼 변형이 없으면 모든 목적지가 호스트 번들 하나를 받고, 빌드가 그 사실을 기록합니다. 맞는 변형이 없는 목적지는 다른 플랫폼용 번들 대신 아무것도 스테이징하지 않습니다.

iOS: the Xcode build phaseiOS: Xcode 빌드 단계

stagePythonBundleIosForXcode runs stagePythonBundleIos and prints exactly one line, PYTHON_PAYLOAD_DIR=<absolute path>, even under --quiet. It fails, naming why, when no iOS variant of the active build type exists or the staged directory is empty (no package configured). It never copies into the .app. The phase that does is owned by python-multiplatform (its #59); this plugin only stages and exposes the path. Wiring the phase by hand, without python-multiplatform, it is:

stagePythonBundleIosForXcode 는 stagePythonBundleIos 를 실행한 뒤 --quiet 에서도 정확히 한 줄, PYTHON_PAYLOAD_DIR=<절대 경로> 를 출력합니다. 활성 빌드 타입의 iOS 변형이 없거나 스테이징 디렉터리가 비어 있으면(패키지 미설정) 이유를 밝히며 실패합니다. .app 안으로는 절대 복사하지 않습니다. 복사하는 단계는 python-multiplatform(#59)이 소유하며, 이 플러그인은 스테이징과 경로 노출만 합니다. 사용하는 python-multiplatform 없이 손으로 배선한다면 단계는 다음과 같습니다:

set -euo pipefail
out=$(./gradlew -q :app:stagePythonBundleIosForXcode)
dir=$(printf '%s\n' "$out" | sed -n 's/^PYTHON_PAYLOAD_DIR=//p')
[ -n "$dir" ] && [ -d "$dir" ] || { echo "error: no Python payload dir from Gradle" >&2; exit 1; }
rsync -a --delete "$dir/" "$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/python/"

With python-multiplatform, its tools/xcode/install-python.sh is the one phase that copies python/ (and the stdlib): give it the directory this task prints as PYTHON_PAYLOAD_DIR, as usage-example's usage-example/src/iosMain/install-python-phase.sh does, and do not add the snippet above as well. Only one Xcode phase may copy python/, because each rsync --deletes the same directory. The snippet above is for wiring by hand without python-multiplatform.

python-multiplatform 을 쓰면 그쪽 tools/xcode/install-python.sh 가 python/(와 stdlib)을 복사하는 유일한 단계입니다. 이 태스크가 출력한 디렉터리를 PYTHON_PAYLOAD_DIR 로 넘기세요(샘플의 usage-example/src/iosMain/install-python-phase.sh 처럼). 위 스니펫을 함께 넣지 마세요. 둘 다 같은 디렉터리를 rsync --delete 하므로 python/ 을 복사하는 Xcode 단계는 하나여야 합니다. 위 스니펫은 python-multiplatform 없이 손으로 배선할 때를 위한 것입니다.

Do not shorten it to dir=$(./gradlew … | sed …) && rsync …: the pipeline's status is sed's, so a failed Gradle leaves dir empty and rsync --delete "/" runs.

dir=$(./gradlew … | sed …) && rsync … 처럼 줄이면 안 됩니다. 파이프라인의 종료 상태는 sed 의 것이라, Gradle 이 실패하면 dir 이 비어 rsync --delete "/" 가 실행됩니다.

After staging스테이징 이후

Putting the staged python/ on sys.path when the app starts is the runtime's job: python-multiplatform's side of the boundary, not this plugin's.

앱이 시작할 때 스테이징된 python/ 을 sys.path 에 올리는 것은 런타임의 일입니다: 이 플러그인이 아니라 python-multiplatform 쪽 경계입니다.

WASM: cross-origin isolation and its limitsWASM: 교차 출처 격리와 그 한계

WASM runs free-threaded CPython 3.15t with pthreads. WebAssembly threads require SharedArrayBuffer, which browsers only expose when self.crossOriginIsolated === true: Cross-Origin-Opener-Policy: same-origin together with Cross-Origin-Embedder-Policy: require-corp (or credentialless via -Ppython.wasm.coep=credentialless), plus Cross-Origin-Resource-Policy: same-origin on the app's own assets. Cross-origin isolation is on by default for every WASM app this plugin builds:

WASM 은 pthreads 기반 자유 스레드 CPython 3.15t 로 실행됩니다. WebAssembly 스레드는 SharedArrayBuffer 가 필요하며, 브라우저는 self.crossOriginIsolated === true 일 때만 이를 열어 줍니다: Cross-Origin-Opener-Policy: same-origin 과 Cross-Origin-Embedder-Policy: require-corp(또는 -Ppython.wasm.coep=credentialless 로 고르는 credentialless), 그리고 앱 자체 자산의 Cross-Origin-Resource-Policy: same-origin 입니다. 이 플러그인이 빌드하는 모든 WASM 앱에는 교차 출처 격리가 기본으로 켜집니다:

  • Dev server headers: every wasmJs*Webpack task writes webpack.config.d/python-cross-origin-isolation.js so the local webpack dev server sends all three headers automatically.개발 서버 헤더: 모든 wasmJs*Webpack 태스크가 webpack.config.d/python-cross-origin-isolation.js 를 기록해 로컬 webpack 개발 서버가 세 헤더를 자동으로 보냅니다.
  • Static host headers (_headers): stageWasmCrossOriginIsolation emits a Cloudflare Pages and Netlify _headers file into the WASM browser distribution root.정적 호스트 헤더(_headers): stageWasmCrossOriginIsolation 이 Cloudflare Pages 와 Netlify 형식의 _headers 파일을 WASM 브라우저 배포 루트에 생성합니다.
  • Service-worker fallback (coi-serviceworker.js) and check page (coi-check.html): for hosts that cannot set HTTP headers (such as GitHub Pages), coi-serviceworker.js intercepts fetches and re-serves responses with COOP, COEP and CORP. Its cost is one reload on the first visit, and it has no effect when service workers are unavailable (non-HTTPS origins other than localhost, or webviews with service workers disabled). At startup the runtime checks self.crossOriginIsolated and fails immediately rather than failing later inside a thread; coi-check.html tests the same invariant on its own.서비스 워커 폴백(coi-serviceworker.js)과 점검 페이지(coi-check.html): GitHub Pages 처럼 HTTP 헤더를 설정할 수 없는 호스트를 위해, coi-serviceworker.js 가 요청을 가로채 COOP, COEP, CORP 헤더를 붙여 응답합니다. 그 비용은 첫 방문 시 1회 새로고침이며, 서비스 워커를 쓸 수 없는 환경에서는 효과가 없습니다(localhost 이외의 비-HTTPS 출처나 서비스 워커가 꺼진 웹뷰). 시작 시 런타임이 self.crossOriginIsolated 를 확인해 스레드 안에서 뒤늦게 죽는 대신 즉시 실패하며, coi-check.html 로도 같은 조건을 바로 점검할 수 있습니다.

Browser limits of cross-origin isolation교차 출처 격리의 브라우저 제약

Surface영역What cross-origin isolation changes교차 출처 격리로 달라지는 점What to do대응 방법
Third-party <iframe>제3자 <iframe>Embedded cross-origin documents must opt in with CORP/COEP headers, or the browser refuses to load them.내장된 교차 출처 문서가 CORP/COEP 헤더로 동의하지 않으면 브라우저가 로드를 거부합니다.Serve the framed document with Cross-Origin-Embedder-Policy and Cross-Origin-Resource-Policy: cross-origin, or open it in a top-level navigation instead of an iframe.iframe 문서에 Cross-Origin-Embedder-Policy 와 Cross-Origin-Resource-Policy: cross-origin 을 설정하거나, iframe 대신 최상위 탐색으로 여세요.
Popup OAuth and payment flows팝업 기반 OAuth 및 결제 흐름Under Cross-Origin-Opener-Policy: same-origin, cross-origin popups lose window.opener (it becomes null), so postMessage handshakes back to the opener break.Cross-Origin-Opener-Policy: same-origin 아래에서는 교차 출처 팝업의 window.opener 가 null 이 되어, 부모 창으로의 postMessage 핸드셰이크가 끊깁니다.Use full-page redirect OAuth/payment flows, or configure the host with same-origin-allow-popups where the browser's isolation rules permit it.전체 페이지 리다이렉트 방식의 OAuth/결제 흐름을 쓰거나, 브라우저 격리 규칙이 허용하는 범위에서 호스트에 same-origin-allow-popups 를 설정하세요.
External images, scripts, fonts and media외부 이미지, 스크립트, 글꼴, 미디어Under Cross-Origin-Embedder-Policy: require-corp, any cross-origin subresource without a Cross-Origin-Resource-Policy or CORS header is blocked.Cross-Origin-Embedder-Policy: require-corp 아래에서는 Cross-Origin-Resource-Policy 나 CORS 헤더가 없는 교차 출처 하위 리소스가 차단됩니다.Add crossorigin attributes and serve CORS/CORP headers on the asset host, or build with -Ppython.wasm.coep=credentialless so no-cookie cross-origin requests load without CORP.crossorigin 속성을 붙이고 자산 호스트에서 CORS/CORP 헤더를 내려주거나, 쿠키 없는 교차 출처 요청을 CORP 없이 로드하도록 -Ppython.wasm.coep=credentialless 로 빌드하세요.

Header snippets for other hosts다른 호스트를 위한 헤더 설정 예시

Cloudflare Pages and Netlify read the generated _headers file directly. For nginx, Apache, Firebase Hosting or Vercel, add the same headers in the host configuration:

Cloudflare Pages 와 Netlify 는 생성된 _headers 파일을 바로 읽습니다. nginx, Apache, Firebase Hosting, Vercel 에서는 호스트 설정에 같은 헤더를 추가하세요:

# nginx
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "same-origin" always;

# Apache (.htaccess)
Header always set Cross-Origin-Opener-Policy "same-origin"
Header always set Cross-Origin-Embedder-Policy "require-corp"
Header always set Cross-Origin-Resource-Policy "same-origin"

# Firebase Hosting (firebase.json) / Vercel (vercel.json)
# Set headers on "/(.*)" -> Cross-Origin-Opener-Policy: same-origin,
# Cross-Origin-Embedder-Policy: require-corp, Cross-Origin-Resource-Policy: same-origin