@astrale-os/adapter-cloudflare 0.1.8 → 0.1.9

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 (71) hide show
  1. package/dist/assets-pack.d.ts +1 -1
  2. package/dist/assets-pack.js +1 -1
  3. package/dist/build.d.ts +15 -0
  4. package/dist/build.d.ts.map +1 -0
  5. package/dist/build.js +15 -0
  6. package/dist/build.js.map +1 -0
  7. package/dist/client.d.ts +9 -0
  8. package/dist/client.d.ts.map +1 -1
  9. package/dist/client.js +10 -1
  10. package/dist/client.js.map +1 -1
  11. package/dist/cloudflare.d.ts +15 -3
  12. package/dist/cloudflare.d.ts.map +1 -1
  13. package/dist/cloudflare.js +52 -18
  14. package/dist/cloudflare.js.map +1 -1
  15. package/dist/codegen/worker.d.ts +26 -6
  16. package/dist/codegen/worker.d.ts.map +1 -1
  17. package/dist/codegen/worker.js +67 -54
  18. package/dist/codegen/worker.js.map +1 -1
  19. package/dist/codegen/wrangler.d.ts +11 -2
  20. package/dist/codegen/wrangler.d.ts.map +1 -1
  21. package/dist/codegen/wrangler.js +11 -5
  22. package/dist/codegen/wrangler.js.map +1 -1
  23. package/dist/index.d.ts +6 -3
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +5 -2
  26. package/dist/index.js.map +1 -1
  27. package/dist/params.d.ts +30 -30
  28. package/dist/params.d.ts.map +1 -1
  29. package/dist/parse-output.d.ts +1 -1
  30. package/dist/parse-output.js +1 -1
  31. package/package.json +6 -2
  32. package/src/assets-pack.ts +1 -1
  33. package/src/build.ts +15 -0
  34. package/src/client.ts +11 -1
  35. package/src/cloudflare.ts +53 -18
  36. package/src/codegen/worker.ts +76 -59
  37. package/src/codegen/wrangler.ts +15 -5
  38. package/src/index.ts +6 -3
  39. package/src/params.ts +32 -31
  40. package/src/parse-output.ts +1 -1
  41. package/template/.agents/skills/astrale-cli/SKILL.md +25 -11
  42. package/template/.agents/skills/astrale-domain/SKILL.md +46 -29
  43. package/template/.env.example +8 -0
  44. package/template/README.md +24 -9
  45. package/template/astrale.config.ts +27 -33
  46. package/template/client/README.md +2 -2
  47. package/template/client/tsconfig.json +1 -1
  48. package/template/client/vite.config.ts +3 -3
  49. package/template/client/vitest.config.ts +1 -1
  50. package/template/core/keys.ts +28 -0
  51. package/template/{methods → core}/note.ts +42 -25
  52. package/template/deps.ts +25 -0
  53. package/template/domain.ts +33 -0
  54. package/template/env.ts +11 -0
  55. package/template/integrations/summary/heuristic.ts +25 -0
  56. package/template/integrations/summary/http.ts +69 -0
  57. package/template/integrations/summary/port.ts +21 -0
  58. package/template/integrations/summary/registry.ts +52 -0
  59. package/template/package.json +2 -3
  60. package/template/runtime/index.ts +62 -0
  61. package/template/schema/index.ts +2 -0
  62. package/template/schema/note.ts +5 -2
  63. package/template/tsconfig.json +13 -2
  64. package/template/views/note.ts +1 -1
  65. package/dist/astrale.d.ts +0 -27
  66. package/dist/astrale.d.ts.map +0 -1
  67. package/dist/astrale.js +0 -222
  68. package/dist/astrale.js.map +0 -1
  69. package/src/astrale.ts +0 -259
  70. package/template/methods/index.ts +0 -66
  71. package/template/schema/compiled.ts +0 -14
@@ -0,0 +1,25 @@
1
+ /**
2
+ * env → handler dependency container — the ONE place the worker env becomes the
3
+ * typed `ctx.deps` every method reads. `defineDomain({ deps })` mounts it; the
4
+ * generated worker imports it. Runs ONCE per cold isolate (NOT per request), so
5
+ * it's where ports/clients are wired once instead of being re-derived in every
6
+ * handler.
7
+ *
8
+ * The summarizer port is resolved ON-REQUEST (lazy `summarizer()` via the
9
+ * registry), not here — so this stays a cheap synchronous wiring step and a
10
+ * worker never validates a provider's env until a handler actually uses it.
11
+ *
12
+ * Omit the `deps` field in `domain.ts` for the trivial case (handlers then get
13
+ * raw `Env`). Transform here the moment a handler should depend on a PORT
14
+ * instead of raw config — that's the whole point of this seam.
15
+ */
16
+ import { buildSummarizerRegistry, type SummarizerRegistry } from './integrations/summary/registry'
17
+ import type { Env } from './env'
18
+
19
+ /** Typed dependency container handed to every method as `ctx.deps`. */
20
+ export interface Deps extends SummarizerRegistry {}
21
+
22
+ /** Map the worker env to the handler deps (the seam `defineDomain({ deps })` mounts). */
23
+ export function deps(env: Env): Deps {
24
+ return buildSummarizerRegistry(env)
25
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * domain.ts — the WORKER-SAFE domain definition: what the domain IS (its
3
+ * `schema`, `methods`, `deps`, `views`, `functions`, `client`) plus its identity
4
+ * (`origin` defaults to `schema.domain`; `postInstall`). Everything is wired
5
+ * EXPLICITLY here — a renamed or mistyped module is a compile error at this
6
+ * call, never a silently-missing route. The handlers live in `runtime/` (the
7
+ * composition root), the pure logic in `core/`, the external-API ports in
8
+ * `integrations/` — but the worker only ever sees this one wired definition.
9
+ *
10
+ * The generated worker (`.astrale/worker.gen.ts`) imports THIS and spreads it,
11
+ * so your folder layout is invisible to it — reorganize freely; only this wiring
12
+ * has to stay put. The deploy adapter is attached separately in
13
+ * `astrale.config.ts` via `deploy(domain, …)`, keeping its node-only code
14
+ * (wrangler, filesystem) out of the worker bundle.
15
+ */
16
+ import { defineDomain } from '@astrale-os/sdk'
17
+
18
+ import { deps } from './deps'
19
+ import { functions } from './functions'
20
+ import { methods } from './runtime'
21
+ import { schema } from './schema'
22
+ import { views } from './views'
23
+
24
+ export const domain = defineDomain({
25
+ schema,
26
+ methods,
27
+ deps,
28
+ views,
29
+ functions,
30
+ client: { dir: 'client' },
31
+ postInstall: `/:${schema.domain}:class.Note:seed`,
32
+ requires: [],
33
+ })
package/template/env.ts CHANGED
@@ -18,5 +18,16 @@ export interface Env {
18
18
  SELF?: { fetch(request: Request): Promise<Response> }
19
19
  /** Dev-only: forward /ui/* to a running Vite dev server. */
20
20
  VIEW_DEV_URL?: string
21
+
22
+ // ── Summarizer (the example external-API integration) ─────────────
23
+ /** Which summarizer adapter to bind: `heuristic` (default, no secret) | `http`. */
24
+ NOTE_SUMMARIZER?: string
25
+ /** `http` only — bearer token for the OpenAI-compatible upstream (a secret). */
26
+ SUMMARIZER_API_KEY?: string
27
+ /** `http` only — OpenAI-compatible base URL (e.g. https://api.openai.com/v1). */
28
+ SUMMARIZER_BASE_URL?: string
29
+ /** `http` only — model id (default gpt-4o-mini). */
30
+ SUMMARIZER_MODEL?: string
31
+
21
32
  [key: string]: unknown
22
33
  }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Heuristic summarizer — the ZERO-CONFIG default adapter. No network, no
3
+ * secrets: a fresh scaffold summarizes notes out of the box on `pnpm dev`.
4
+ * It takes the first sentence (clamped), which is good enough to demonstrate
5
+ * the seam; flip `NOTE_SUMMARIZER=http` (see `registry.ts`) for a real model.
6
+ */
7
+ import type { Summarizer } from './port'
8
+
9
+ const DEFAULT_MAX_LENGTH = 140
10
+
11
+ /** Build the local, dependency-free summarizer. */
12
+ export function createHeuristicSummarizer(opts: { maxLength?: number } = {}): Summarizer {
13
+ const maxLength = opts.maxLength ?? DEFAULT_MAX_LENGTH
14
+ return {
15
+ summarize(body) {
16
+ const trimmed = body.trim()
17
+ // First sentence, else the whole (clamped) body.
18
+ const firstSentence = trimmed.split(/(?<=[.!?])\s/)[0] ?? trimmed
19
+ const text = firstSentence || trimmed
20
+ const summary =
21
+ text.length <= maxLength ? text : `${text.slice(0, maxLength - 1).trimEnd()}…`
22
+ return Promise.resolve(summary)
23
+ },
24
+ }
25
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * HTTP summarizer — the REAL external-API adapter: a single OpenAI-compatible
3
+ * `POST /chat/completions` call. This is the shape your domain's external calls
4
+ * take — config + secret from `env`, a timeout via `AbortSignal`, upstream
5
+ * detail preserved in `cause`. Selected by `NOTE_SUMMARIZER=http` (registry.ts);
6
+ * the default stays the no-network `heuristic` adapter so a fresh scaffold needs
7
+ * no secret.
8
+ *
9
+ * `baseUrl` is anything OpenAI-compatible — `https://api.openai.com/v1`, a
10
+ * Workers-AI gateway, or your OWN `ai-gateway` domain's `/v1` surface. On a soft
11
+ * upstream failure it falls back to the heuristic rather than throwing: a flaky
12
+ * summarizer must never block creating a note (see the port contract).
13
+ */
14
+ import { createHeuristicSummarizer } from './heuristic'
15
+ import type { Summarizer } from './port'
16
+
17
+ export interface HttpSummarizerConfig {
18
+ /** Bearer token for the upstream (a secret — ships via `.env.<env>`). */
19
+ apiKey: string
20
+ /** OpenAI-compatible base URL, e.g. `https://api.openai.com/v1`. */
21
+ baseUrl: string
22
+ /** Model id, e.g. `gpt-4o-mini`. */
23
+ model: string
24
+ /** Upstream request timeout in ms (default 15000). */
25
+ timeoutMs?: number
26
+ }
27
+
28
+ const DEFAULT_TIMEOUT_MS = 15_000
29
+ const SYSTEM_PROMPT = 'Summarize the user note in one short sentence. Reply with the summary only.'
30
+
31
+ /** Build the OpenAI-compatible HTTP summarizer (with a heuristic fallback). */
32
+ export function createHttpSummarizer(config: HttpSummarizerConfig): Summarizer {
33
+ const fallback = createHeuristicSummarizer()
34
+ const endpoint = `${config.baseUrl.replace(/\/+$/, '')}/chat/completions`
35
+ return {
36
+ async summarize(body) {
37
+ try {
38
+ const res = await fetch(endpoint, {
39
+ method: 'POST',
40
+ headers: {
41
+ 'content-type': 'application/json',
42
+ authorization: `Bearer ${config.apiKey}`,
43
+ },
44
+ body: JSON.stringify({
45
+ model: config.model,
46
+ messages: [
47
+ { role: 'system', content: SYSTEM_PROMPT },
48
+ { role: 'user', content: body },
49
+ ],
50
+ }),
51
+ signal: AbortSignal.timeout(config.timeoutMs ?? DEFAULT_TIMEOUT_MS),
52
+ })
53
+ if (!res.ok) {
54
+ throw new Error(`summarizer upstream returned ${res.status}`, {
55
+ cause: await res.text().catch(() => undefined),
56
+ })
57
+ }
58
+ const data = (await res.json()) as {
59
+ choices?: Array<{ message?: { content?: string } }>
60
+ }
61
+ const text = data.choices?.[0]?.message?.content?.trim()
62
+ return text || (await fallback.summarize(body))
63
+ } catch {
64
+ // Soft-fail: never block a note create on the summarizer.
65
+ return fallback.summarize(body)
66
+ }
67
+ },
68
+ }
69
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Summarizer — the PORT between the domain's logic and whatever produces a
3
+ * note's one-line summary. This is the external-API seam every real domain has
4
+ * (here: an LLM/summarization API), reduced to the narrowest interface the
5
+ * logic needs.
6
+ *
7
+ * `core/` logic depends on THIS interface only — never on `fetch`, an SDK, or
8
+ * `env`. Adapters in this folder implement it: `heuristic.ts` (the zero-config
9
+ * default, no network) and `http.ts` (a real OpenAI-compatible call). The
10
+ * registry picks one from `env`; the handler logic only ever sees the resolved
11
+ * port. Swap or add a provider = one adapter + one arm in `registry.ts`.
12
+ */
13
+ export interface Summarizer {
14
+ /**
15
+ * Produce a short, single-line summary of `body`. Called once per note
16
+ * create/seed, so keep it fast and resilient. Adapters MUST resolve to a
17
+ * usable string (fall back to a heuristic rather than throwing on a soft
18
+ * upstream failure) — a flaky summarizer should never block creating a note.
19
+ */
20
+ summarize(body: string): Promise<string>
21
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Summarizer registry — the ONE place the worker env becomes the live
3
+ * `Summarizer` port. Adding a provider = one more arm in `selectSummarizer`;
4
+ * handler logic only ever sees the resolved port.
5
+ *
6
+ * Selection is ON-REQUEST: the provider is chosen + built lazily on the first
7
+ * handler that calls `summarizer()`, then cached for the isolate — NOT at
8
+ * `deps()` construction. A worker left on the default never validates the HTTP
9
+ * provider's env, and a per-request override could slot in here later.
10
+ */
11
+ import type { Env } from '../../env'
12
+ import { createHeuristicSummarizer } from './heuristic'
13
+ import { createHttpSummarizer } from './http'
14
+ import type { Summarizer } from './port'
15
+
16
+ export interface SummarizerRegistry {
17
+ /** Resolve the configured summarizer port (lazy + cached per isolate). */
18
+ summarizer(): Summarizer
19
+ }
20
+
21
+ /** Build the registry from the worker env (the port is built lazily + cached). */
22
+ export function buildSummarizerRegistry(env: Env): SummarizerRegistry {
23
+ let cached: Summarizer | undefined
24
+ return {
25
+ summarizer() {
26
+ return (cached ??= selectSummarizer(env))
27
+ },
28
+ }
29
+ }
30
+
31
+ const DEFAULT_HTTP_MODEL = 'gpt-4o-mini'
32
+
33
+ /** Bind the abstract summarizer port to the configured concrete adapter. */
34
+ function selectSummarizer(env: Env): Summarizer {
35
+ const provider = (env.NOTE_SUMMARIZER || 'heuristic').toLowerCase()
36
+
37
+ if (provider === 'http') {
38
+ if (!env.SUMMARIZER_API_KEY || !env.SUMMARIZER_BASE_URL) {
39
+ throw new Error(
40
+ 'NOTE_SUMMARIZER=http requires SUMMARIZER_API_KEY and SUMMARIZER_BASE_URL',
41
+ )
42
+ }
43
+ return createHttpSummarizer({
44
+ apiKey: env.SUMMARIZER_API_KEY,
45
+ baseUrl: env.SUMMARIZER_BASE_URL,
46
+ model: env.SUMMARIZER_MODEL || DEFAULT_HTTP_MODEL,
47
+ })
48
+ }
49
+
50
+ // Default: the zero-config local heuristic (no network, no secret).
51
+ return createHeuristicSummarizer()
52
+ }
@@ -14,11 +14,10 @@
14
14
  "typecheck": "tsgo --noEmit"
15
15
  },
16
16
  "dependencies": {
17
- "@astrale-os/adapter-cloudflare": ">=0.1.7 <1.0.0",
18
- "@astrale-os/devkit": ">=0.1.6 <1.0.0",
17
+ "@astrale-os/adapter-cloudflare": ">=0.1.9 <1.0.0",
19
18
  "@astrale-os/kernel-core": ">=0.4.3 <1.0.0",
20
19
  "@astrale-os/kernel-dsl": ">=0.1.2 <1.0.0",
21
- "@astrale-os/sdk": ">=0.1.5 <1.0.0",
20
+ "@astrale-os/sdk": ">=0.1.7 <1.0.0",
22
21
  "@hono/node-server": "^1.19.0",
23
22
  "zod": "^4.3.6"
24
23
  },
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Runtime composition root — the ONLY place request context (kernel/self/params/
3
+ * auth) and `deps` meet the per-feature logic. Each `execute` resolves the port
4
+ * it needs (`deps.summarizer()`, on-request) and delegates to the transport-
5
+ * agnostic functions in `core/`. No business logic lives here.
6
+ *
7
+ * - `createNote` is interface-hosted (static) → `remoteInterfaceMethods`.
8
+ * - `reference` is class-hosted (instance) → `remoteMethod` + `remoteClassMethods`.
9
+ * - `seed` is class-hosted (static) — the `postInstall` bootstrap.
10
+ *
11
+ * SDK-level `authorize` is an additive throw-to-deny check (returns void). For
12
+ * finer worker checks see `assertPerm` / `requireOwnership` from `@astrale-os/sdk`.
13
+ *
14
+ * Exports the `methods` map the domain definition (`domain.ts`) wires in.
15
+ */
16
+ import {
17
+ remoteClassMethods,
18
+ remoteInterfaceMethods,
19
+ remoteMethod,
20
+ type SchemaMethodsImpl,
21
+ } from '@astrale-os/sdk'
22
+
23
+ import { createNote, reference, seed } from '../core/note'
24
+ import type { Deps } from '../deps'
25
+ import { schema } from '../schema'
26
+
27
+ const method = remoteMethod<Deps>()
28
+ const interfaceMethods = remoteInterfaceMethods<Deps>()
29
+ const classMethods = remoteClassMethods<Deps>()
30
+
31
+ const NoteOpsMethods = interfaceMethods(schema, 'NoteOps', {
32
+ createNote: {
33
+ authorize: async () => undefined,
34
+ execute: ({ kernel, params, deps }) => {
35
+ if (!kernel) throw new Error('createNote requires a kernel credential')
36
+ return createNote(kernel, deps.summarizer(), params)
37
+ },
38
+ },
39
+ })
40
+
41
+ const referenceMethod = method(schema, 'Note', 'reference', {
42
+ authorize: async () => undefined,
43
+ execute: ({ kernel, self, params }) => {
44
+ if (!kernel) throw new Error('reference requires a kernel credential')
45
+ return reference(kernel, self.path.raw, params)
46
+ },
47
+ })
48
+
49
+ const seedMethod = method(schema, 'Note', 'seed', {
50
+ authorize: async () => undefined,
51
+ execute: ({ kernel, deps }) => {
52
+ if (!kernel) throw new Error('seed requires a kernel credential')
53
+ return seed(kernel, deps.summarizer())
54
+ },
55
+ })
56
+
57
+ const NoteMethods = classMethods(schema, 'Note', { reference: referenceMethod, seed: seedMethod })
58
+
59
+ export const methods: SchemaMethodsImpl<typeof schema, Deps> = {
60
+ interface: { NoteOps: NoteOpsMethods },
61
+ class: { Note: NoteMethods },
62
+ }
@@ -9,6 +9,7 @@
9
9
  * them in the `interfaces` / `classes` maps below.
10
10
  */
11
11
  import { defineSchema, KernelSchema } from '@astrale-os/kernel-core'
12
+ import { compileDomain, type Domain } from '@astrale-os/kernel-core/domain'
12
13
 
13
14
  import { Note, NoteOps, references } from './note'
14
15
 
@@ -17,5 +18,6 @@ export const schema = defineSchema('astrale-domain.example.dev', {
17
18
  classes: { Note, references },
18
19
  imports: [KernelSchema],
19
20
  })
21
+ export const D: Domain<typeof schema> = compileDomain(schema)
20
22
 
21
23
  export * from './note'
@@ -41,6 +41,9 @@ export const Note = nodeClass({
41
41
  props: {
42
42
  title: z.string(),
43
43
  body: z.string(),
44
+ // One-line summary, stamped at create/seed time from the `Summarizer` port
45
+ // (see integrations/summary/) — the external-API seam wired through `deps`.
46
+ summary: z.string().optional(),
44
47
  },
45
48
  methods: {
46
49
  reference: fn({
@@ -58,7 +61,7 @@ export const Note = nodeClass({
58
61
  })
59
62
 
60
63
  export const references = edgeClass(
61
- { as: 'from_note', types: [Note] },
62
- { as: 'to_note', types: [Note] },
64
+ { as: 'from_note', types: [Note], cardinality: '0..*' },
65
+ { as: 'to_note', types: [Note], cardinality: '0..*' },
63
66
  { props: { reason: z.string().optional() } },
64
67
  )
@@ -12,6 +12,17 @@
12
12
  "esModuleInterop": true,
13
13
  "resolveJsonModule": true
14
14
  },
15
- "include": ["schema", "methods", "views", "functions", "env.ts", "astrale.config.ts"],
16
- "exclude": ["node_modules", ".astrale", "dist-client"]
15
+ "include": [
16
+ "schema",
17
+ "core",
18
+ "integrations",
19
+ "runtime",
20
+ "views",
21
+ "functions",
22
+ "deps.ts",
23
+ "env.ts",
24
+ "domain.ts",
25
+ "astrale.config.ts"
26
+ ],
27
+ "exclude": ["node_modules", ".astrale", ".dist"]
17
28
  }
@@ -3,7 +3,7 @@
3
3
  * an inline-HTML `render` like `welcome`). Because it declares `mount` rather
4
4
  * than `render`, the View node's iframe binding points at `<serving url>/ui/note`
5
5
  * — the SDK stamps it from the worker's live URL when it builds the install
6
- * bundle. The Cloudflare adapter serves `/ui/*` from `../dist-client` (built by
6
+ * bundle. The Cloudflare adapter serves `/ui/*` from `../.dist` (built by
7
7
  * `client/` with base `/ui/`) via the Worker's `ASSETS` binding.
8
8
  *
9
9
  * `viewFor: selfOf(Note)` attaches a `view_for` edge to the `Note` class
package/dist/astrale.d.ts DELETED
@@ -1,27 +0,0 @@
1
- /**
2
- * `astrale(envs)` — the Astrale-managed deployment adapter.
3
- *
4
- * Ships the domain THROUGH the platform instead of to the author's own cloud
5
- * account: `deploy` builds the same single-module workerd bundle the Cloudflare
6
- * adapter ships (shared codegen + `wrangler deploy --dry-run`), then publishes
7
- * it via the admin domain's catalog — `DomainPublished.register` →
8
- * `::release { bundleBase64 }` (the worker stages the bytes in the platform
9
- * registry) → `::install { instanceId, source: { kind: 'package' } }`, which
10
- * deploys it as a host-local Service next to the target instance and installs
11
- * the domain on it. No Cloudflare account, no wrangler auth — the only
12
- * credential is the author's Astrale identity, supplied by the `astrale` CLI
13
- * session this adapter shells out to (the same trust source as
14
- * `astrale instance install`).
15
- *
16
- * `watch` is identical to the Cloudflare adapter's local dev (wrangler dev on
17
- * localhost) — managed deploys change WHERE the worker runs, not how you
18
- * iterate locally.
19
- *
20
- * Managed deploys ship the client SPA (served under `/ui` by the box) and
21
- * runtime secrets (dotenv map on the install call, encrypted at rest
22
- * platform-side; platform-managed env keys always win precedence).
23
- */
24
- import type { DomainAdapter } from '@astrale-os/devkit';
25
- import type { AstraleParams } from './params';
26
- export declare function astrale(envs: Record<string, AstraleParams>): DomainAdapter<AstraleParams>;
27
- //# sourceMappingURL=astrale.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"astrale.d.ts","sourceRoot":"","sources":["../src/astrale.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAQvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAY7C,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,GAAG,aAAa,CAAC,aAAa,CAAC,CAmJzF"}
package/dist/astrale.js DELETED
@@ -1,222 +0,0 @@
1
- /**
2
- * `astrale(envs)` — the Astrale-managed deployment adapter.
3
- *
4
- * Ships the domain THROUGH the platform instead of to the author's own cloud
5
- * account: `deploy` builds the same single-module workerd bundle the Cloudflare
6
- * adapter ships (shared codegen + `wrangler deploy --dry-run`), then publishes
7
- * it via the admin domain's catalog — `DomainPublished.register` →
8
- * `::release { bundleBase64 }` (the worker stages the bytes in the platform
9
- * registry) → `::install { instanceId, source: { kind: 'package' } }`, which
10
- * deploys it as a host-local Service next to the target instance and installs
11
- * the domain on it. No Cloudflare account, no wrangler auth — the only
12
- * credential is the author's Astrale identity, supplied by the `astrale` CLI
13
- * session this adapter shells out to (the same trust source as
14
- * `astrale instance install`).
15
- *
16
- * `watch` is identical to the Cloudflare adapter's local dev (wrangler dev on
17
- * localhost) — managed deploys change WHERE the worker runs, not how you
18
- * iterate locally.
19
- *
20
- * Managed deploys ship the client SPA (served under `/ui` by the box) and
21
- * runtime secrets (dotenv map on the install call, encrypted at rest
22
- * platform-side; platform-managed env keys always win precedence).
23
- */
24
- import { defineAdapter, loadDotenvFile } from '@astrale-os/devkit';
25
- import { spawn } from 'node:child_process';
26
- import { existsSync } from 'node:fs';
27
- import { readFile } from 'node:fs/promises';
28
- import { join } from 'node:path';
29
- import { packAssets } from './assets-pack';
30
- import { buildClient } from './client';
31
- import { logTo, prepare } from './cloudflare';
32
- import { runWranglerBundle, runWranglerDev } from './wrangler-cli';
33
- const DEFAULT_PORT = 8787;
34
- const DEFAULT_ADMIN_URL = 'https://admin.eu.astrale.ai/api';
35
- const DEFAULT_REGION = 'eu';
36
- const ADMIN_ORIGIN = 'admin.astrale.ai';
37
- export function astrale(envs) {
38
- return defineAdapter({
39
- name: 'astrale',
40
- envs,
41
- // Local dev is unchanged: wrangler dev on localhost. Managed deploys change
42
- // WHERE the worker ships, not the inner loop.
43
- async watch(params, ctx) {
44
- const { configPath } = await prepare({
45
- ...(params.vars ? { vars: params.vars } : {}),
46
- ...(params.host ? { host: params.host } : {}),
47
- port: params.port ?? DEFAULT_PORT,
48
- }, ctx, 'dev');
49
- const handle = await runWranglerDev({
50
- projectDir: ctx.projectDir,
51
- configPath,
52
- port: params.port ?? DEFAULT_PORT,
53
- remote: false,
54
- autoPickPort: params.port === undefined,
55
- ...(params.host ? { ip: '0.0.0.0' } : {}),
56
- onReload: ctx.onReload,
57
- onLog: logTo(),
58
- });
59
- return { url: params.host ?? handle.url, stop: handle.stop };
60
- },
61
- // Config hot-regen for the local dev loop: same codegen as `watch` (the
62
- // running `wrangler dev` reloads its generated config + entry itself) —
63
- // the params mapping must stay identical to `watch`'s prepare call.
64
- async regenerate(params, ctx) {
65
- await prepare({
66
- ...(params.vars ? { vars: params.vars } : {}),
67
- ...(params.host ? { host: params.host } : {}),
68
- port: params.port ?? DEFAULT_PORT,
69
- }, ctx, 'dev');
70
- },
71
- async deploy(params, ctx) {
72
- const log = logTo();
73
- if (!params.instance) {
74
- throw new Error(`astrale adapter: this env has no "instance" — managed deploys need the target ` +
75
- `instance slug (e.g. prod: { instance: '<your-instance-slug>' }).`);
76
- }
77
- // Build + pack the client SPA: managed services serve it under /ui (the
78
- // platform stages the archive and the box downloads it at Service.init).
79
- let assetsGz = null;
80
- if (ctx.clientDir) {
81
- await buildClient(ctx.clientDir, ctx.projectDir, log);
82
- assetsGz = packAssets(join(ctx.projectDir, 'dist-client'));
83
- if (assetsGz)
84
- log(`packed client SPA (${assetsGz.length} bytes gz) — /ui ships managed`);
85
- }
86
- // 1. Codegen + bundle: the exact worker module a Cloudflare deploy would
87
- // ship, produced locally with `wrangler deploy --dry-run` (no auth).
88
- // `clientDir` is stripped: managed packages don't ship SPA assets yet,
89
- // and leaving it in would put a dangling `assets.directory` (the
90
- // unbuilt dist-client) into the generated config.
91
- const { clientDir: _omitted, ...bundleCtx } = ctx;
92
- const { configPath } = await prepare({}, bundleCtx, 'dev');
93
- const outDir = join(ctx.projectDir, '.astrale', 'dist-managed');
94
- const bundlePath = await runWranglerBundle({
95
- projectDir: ctx.projectDir,
96
- configPath,
97
- outDir,
98
- onLog: log,
99
- });
100
- const bundle = await readFile(bundlePath);
101
- // 2. Publish through the platform, authenticated by the author's astrale
102
- // CLI session. The release payload rides STDIN — a bundle is megabytes
103
- // of base64, far past argv limits.
104
- const name = params.name ?? packageNameFor(ctx.domain.origin);
105
- const adminUrl = params.adminUrl ?? DEFAULT_ADMIN_URL;
106
- const version = `0.0.0-managed.${Date.now()}`;
107
- log(`registering "${name}" (${ctx.domain.origin}) in the platform catalog…`);
108
- await astraleCall(ctx.projectDir, params, adminUrl, {
109
- path: `/${ADMIN_ORIGIN}/class.DomainPublished/register`,
110
- data: { origin: ctx.domain.origin, name },
111
- });
112
- log(`publishing ${name}@${version} (${bundle.length} bytes)…`);
113
- await astraleCall(ctx.projectDir, params, adminUrl, {
114
- path: `/admin/domains/${name}::release`,
115
- data: {
116
- version,
117
- bundleBase64: bundle.toString('base64'),
118
- makeCurrent: true,
119
- ...(assetsGz ? { assetsGzBase64: assetsGz.toString('base64') } : {}),
120
- },
121
- viaStdin: true,
122
- });
123
- // Author runtime secrets: read the env's dotenv locally, ship the map on
124
- // the INSTALL call (never the release — secrets are per instance, never
125
- // catalog-resident). Rides stdin so values never appear in argv.
126
- let secrets;
127
- if (params.secrets) {
128
- secrets = loadDotenvFile(join(ctx.projectDir, params.secrets));
129
- log(`shipping ${Object.keys(secrets).length} secret(s) from ${params.secrets}…`);
130
- }
131
- log(`installing on instance "${params.instance}"…`);
132
- const installed = (await astraleCall(ctx.projectDir, params, adminUrl, {
133
- path: `/admin/domains/${name}::install`,
134
- data: {
135
- instanceId: params.instance,
136
- source: { kind: 'package' },
137
- ...(secrets ? { secrets } : {}),
138
- },
139
- viaStdin: true,
140
- }));
141
- if (installed.error || installed.state !== 'installed') {
142
- throw new Error(`managed install failed: state=${installed.state ?? '?'} error=${installed.error ?? '?'}`);
143
- }
144
- if (!installed.serviceSlug) {
145
- throw new Error('managed install returned no serviceSlug — cannot derive the service URL');
146
- }
147
- const region = params.region ?? DEFAULT_REGION;
148
- const url = `https://${installed.serviceSlug}.svc.${region}.astrale.ai`;
149
- return {
150
- url,
151
- // Managed deploys already installed on the instance — override the
152
- // devkit's default "install on an instance" footer with the truth.
153
- nextSteps: ` installed on "${params.instance}" — call it:\n` +
154
- ` astrale call "/${ctx.domain.origin}/..." -i ${params.instance}`,
155
- };
156
- },
157
- secretsFile(params) {
158
- return params.secrets;
159
- },
160
- });
161
- }
162
- /** Catalog package name from the origin: first DNS label (e.g. `my-notes.example.dev` → `my-notes`). */
163
- function packageNameFor(origin) {
164
- const label = origin.split('.')[0] ?? origin;
165
- return label.toLowerCase().replace(/[^a-z0-9-]+/g, '-');
166
- }
167
- /**
168
- * Invoke the user's `astrale` CLI for one platform call and parse its JSON
169
- * output. The CLI owns identity (IdP session, audience scoping, delegation
170
- * minting) — reimplementing that here would fork the trust path.
171
- */
172
- async function astraleCall(projectDir, params, adminUrl, call) {
173
- // Saga-sized timeout: a COLD managed install (fresh service on the host)
174
- // runs runtime staging + serve probes and regularly exceeds the CLI's 30s
175
- // default — which doesn't just fail the client, it can kill the saga
176
- // mid-flight. Same budget as `astrale instance create`.
177
- const args = ['call', call.path, '--url', adminUrl, '--json', '--timeout', '240000'];
178
- if (params.identity)
179
- args.push('--as', params.identity);
180
- const payload = JSON.stringify(call.data);
181
- if (!call.viaStdin)
182
- args.push('--data', payload);
183
- const { code, out } = await new Promise((resolve, reject) => {
184
- const child = spawn(astraleBin(projectDir), args, {
185
- cwd: projectDir,
186
- stdio: [call.viaStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
187
- });
188
- let out = '';
189
- child.stdout?.on('data', (b) => (out += b.toString()));
190
- child.stderr?.on('data', (b) => (out += b.toString()));
191
- child.on('exit', (c) => resolve({ code: c ?? 1, out }));
192
- child.on('error', reject);
193
- if (call.viaStdin) {
194
- child.stdin?.write(payload);
195
- child.stdin?.end();
196
- }
197
- });
198
- if (code !== 0) {
199
- // Only suggest re-login for AUTH-shaped failures — a timeout or audience
200
- // error pointed at "auth login" sends users chasing the wrong fix.
201
- const authShaped = /AUTH_ERROR|expired|not signed in|credential/i.test(out);
202
- throw new Error(`astrale call ${call.path} failed (exit ${code}): ${out.trim().slice(0, 500)}` +
203
- (authShaped ? `\nIs the astrale CLI installed and signed in? (astrale auth login)` : ''));
204
- }
205
- try {
206
- return JSON.parse(out);
207
- }
208
- catch {
209
- throw new Error(`astrale call ${call.path}: could not parse CLI output: ${out.slice(0, 300)}`);
210
- }
211
- }
212
- /** The user's astrale CLI: ~/.astrale/bin/astrale when present, else PATH. */
213
- function astraleBin(_projectDir) {
214
- const home = process.env.HOME;
215
- if (home) {
216
- const installed = join(home, '.astrale', 'bin', 'astrale');
217
- if (existsSync(installed))
218
- return installed;
219
- }
220
- return 'astrale';
221
- }
222
- //# sourceMappingURL=astrale.js.map