@quatronic/sdk 0.7.0-rc.8 → 0.7.0-test.1a5da40

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 (106) hide show
  1. package/dist/auth/index.js +1 -1
  2. package/dist/{chunk-2AYDFLKR.js → chunk-F3NHTHFO.js} +6 -104
  3. package/dist/chunk-F3NHTHFO.js.map +1 -0
  4. package/dist/{chunk-5MNPBJYS.js → chunk-G7VPNC6M.js} +5 -11
  5. package/dist/{chunk-5MNPBJYS.js.map → chunk-G7VPNC6M.js.map} +1 -1
  6. package/dist/{chunk-ZZTO5Z3N.js → chunk-HQT57ITV.js} +2 -2
  7. package/dist/{chunk-EK6TGWWT.js → chunk-MET4SIMB.js} +2 -8
  8. package/dist/chunk-MET4SIMB.js.map +1 -0
  9. package/dist/chunk-P7HNHLW7.js +65 -0
  10. package/dist/chunk-P7HNHLW7.js.map +1 -0
  11. package/dist/chunk-QMOZDE3U.js +158 -0
  12. package/dist/chunk-QMOZDE3U.js.map +1 -0
  13. package/dist/{chunk-ROHIN74F.js → chunk-TEBDKNUB.js} +2 -2
  14. package/dist/chunk-TOBGX4CZ.js +109 -0
  15. package/dist/chunk-TOBGX4CZ.js.map +1 -0
  16. package/dist/chunk-WU7N4PET.js +20 -0
  17. package/dist/chunk-WU7N4PET.js.map +1 -0
  18. package/dist/cli/legacy/qdc-sourcemaps.js +16 -6
  19. package/dist/cli/skills-postinstall.js +133 -3
  20. package/dist/cli/skills.js +133 -3
  21. package/dist/cli/sourcemaps.js +16 -6
  22. package/dist/eslint/index.js +2 -22
  23. package/dist/eslint/index.js.map +1 -1
  24. package/dist/integrations/index.d.ts +3 -75
  25. package/dist/integrations/index.js +6 -4
  26. package/dist/mail/index.d.ts +9 -0
  27. package/dist/mail/index.js +26 -0
  28. package/dist/mail/index.js.map +1 -0
  29. package/dist/next/auth/index.d.ts +12 -0
  30. package/dist/next/auth/index.js +15 -156
  31. package/dist/next/auth/index.js.map +1 -1
  32. package/dist/next/better-auth/index.js +1 -1
  33. package/dist/next/boot/index.d.ts +33 -0
  34. package/dist/next/boot/index.js +21 -0
  35. package/dist/next/boot/index.js.map +1 -0
  36. package/dist/next/connections/index.js +3 -3
  37. package/dist/next/db/index.d.ts +18 -1
  38. package/dist/next/db/index.js +25 -0
  39. package/dist/next/db/index.js.map +1 -1
  40. package/dist/next/global-error/index.d.ts +9 -0
  41. package/dist/next/global-error/index.js +17 -0
  42. package/dist/next/global-error/index.js.map +1 -0
  43. package/dist/next/integrations/index.d.ts +2 -1
  44. package/dist/next/integrations/index.js +6 -4
  45. package/dist/next/platform/index.d.ts +19 -0
  46. package/dist/next/platform/index.js +44 -0
  47. package/dist/next/platform/index.js.map +1 -0
  48. package/dist/next/security/index.d.ts +23 -1
  49. package/dist/next/security/index.js +41 -58
  50. package/dist/next/security/index.js.map +1 -1
  51. package/dist/next/sentry/client.d.ts +0 -1
  52. package/dist/next/sentry/client.js +2 -2
  53. package/dist/next/sentry/register.js +6 -14
  54. package/dist/next/sentry/register.js.map +1 -1
  55. package/dist/next/users/index.js +7 -4
  56. package/dist/next/users/index.js.map +1 -1
  57. package/dist/node/boot/index.d.ts +9 -0
  58. package/dist/node/boot/index.js +13 -0
  59. package/dist/node/boot/index.js.map +1 -0
  60. package/dist/node/connections/index.js +3 -3
  61. package/dist/node/identity/index.js +2 -2
  62. package/dist/node/integrations/index.d.ts +2 -1
  63. package/dist/node/integrations/index.js +6 -4
  64. package/dist/node/sentry/register.js +2 -2
  65. package/dist/node-Z7ERWJDZ.js +46 -0
  66. package/dist/node-Z7ERWJDZ.js.map +1 -0
  67. package/dist/types-CAwj03sM.d.ts +75 -0
  68. package/migrations/bootstrap-qore-env/codemod.mjs +77 -0
  69. package/migrations/bootstrap-qore-env/instructions.md +28 -0
  70. package/migrations/bootstrap-qore-env/meta.json +7 -0
  71. package/migrations/global-error/codemod.mjs +28 -0
  72. package/migrations/global-error/instructions.md +26 -0
  73. package/migrations/global-error/meta.json +7 -0
  74. package/migrations/local-db-port/codemod.mjs +61 -0
  75. package/migrations/local-db-port/instructions.md +35 -0
  76. package/migrations/local-db-port/meta.json +7 -0
  77. package/migrations/mail-reexport/codemod.mjs +64 -0
  78. package/migrations/mail-reexport/instructions.md +27 -0
  79. package/migrations/mail-reexport/meta.json +7 -0
  80. package/migrations/platform-routes/codemod.mjs +45 -0
  81. package/migrations/platform-routes/instructions.md +30 -0
  82. package/migrations/platform-routes/meta.json +7 -0
  83. package/migrations/qore-boot/codemod.mjs +261 -0
  84. package/migrations/qore-boot/instructions.md +74 -0
  85. package/migrations/qore-boot/meta.json +7 -0
  86. package/migrations/qore-proxy/codemod.mjs +88 -0
  87. package/migrations/qore-proxy/instructions.md +56 -0
  88. package/migrations/qore-proxy/meta.json +7 -0
  89. package/migrations/run.mjs +322 -0
  90. package/migrations/sourcemaps-finalize/codemod.mjs +63 -0
  91. package/migrations/sourcemaps-finalize/instructions.md +56 -0
  92. package/migrations/sourcemaps-finalize/meta.json +7 -0
  93. package/package.json +26 -8
  94. package/skills/qore-enable-auth-method/SKILL.md +4 -3
  95. package/skills/qore-use-mail-domain/SKILL.next.md +4 -4
  96. package/workspace-requirements.json +4 -0
  97. package/dist/chunk-2AYDFLKR.js.map +0 -1
  98. package/dist/chunk-EK6TGWWT.js.map +0 -1
  99. package/dist/observability/index.d.ts +0 -10
  100. package/dist/observability/index.js +0 -7
  101. package/dist/observability/index.js.map +0 -1
  102. package/migrations/report-error/codemod.mjs +0 -94
  103. package/migrations/report-error/instructions.md +0 -46
  104. package/migrations/report-error/meta.json +0 -6
  105. /package/dist/{chunk-ZZTO5Z3N.js.map → chunk-HQT57ITV.js.map} +0 -0
  106. /package/dist/{chunk-ROHIN74F.js.map → chunk-TEBDKNUB.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/auth-core/migrate.ts"],"sourcesContent":["import { sql } from \"drizzle-orm\"\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { grantRuntimeDefaultPrivileges } from \"../db-core/migration-db\"\n\n// Migrations are inlined as string constants rather than read from .sql files\n// at runtime. A runtime `readFile` does not survive bundlers that only trace\n// JS — notably Next.js standalone output, where the .sql is omitted and the\n// read ENOENTs, crashing the instrumentation hook and 500-ing the whole app.\n// Inlining keeps the SQL in the bundled JS so it works in every consumer.\n\n// Split out of what used to be a single MIGRATION_0001_INIT on purpose, and\n// the reason generalises to every statement below it: **Postgres checks the\n// connecting role's privileges before it evaluates `IF NOT EXISTS`.** So an\n// already-applied statement is not a no-op for a role that lacks the right —\n// it is an error:\n//\n// - `CREATE SCHEMA IF NOT EXISTS auth` needs CREATE on the *database* →\n// `permission denied for database <db>` (SQLSTATE 42501)\n// - `CREATE INDEX IF NOT EXISTS` and `ALTER TABLE ... ADD COLUMN IF NOT\n// EXISTS` need *ownership* of the table → `must be owner of table\n// sessions` (also 42501)\n//\n// That is the normal shape of a least-privileged runtime role against an\n// already-provisioned database, and because migrations run in order one such\n// error aborts every statement after it. It has now bitten staging twice: the\n// first time `login_state.forced_reauth` never landed and every\n// `/api/auth/login` 500'd; the second time `0001_init:tables` failed on its\n// `CREATE INDEX` with `must be owner of table sessions`, again blocking every\n// later ALTER even though there was nothing at all to do.\n//\n// So each migration below carries an `isApplied` catalog probe and the runner\n// skips it when its effect is already present. Catalog lookups need nothing\n// beyond CONNECT, so a role with only DML inside an up-to-date `auth` schema\n// gets through cleanly, while a migration that genuinely still has work to do\n// is attempted and — if the role cannot do it — fails loudly, by name.\nconst MIGRATION_0001_SCHEMA = `\nCREATE SCHEMA IF NOT EXISTS auth;\n`\n\nconst MIGRATION_0001_TABLES = `\nCREATE TABLE IF NOT EXISTS auth.sessions (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n user_sub varchar(64) NOT NULL,\n user_email varchar(320),\n organization_id varchar(64),\n organization_alias varchar(255),\n access_token text NOT NULL,\n access_expires_at timestamptz NOT NULL,\n refresh_ct bytea NOT NULL,\n refresh_iv bytea NOT NULL,\n refresh_expires_at timestamptz NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n revoked_at timestamptz\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_sessions_user_sub\n ON auth.sessions(user_sub) WHERE revoked_at IS NULL;\n\nCREATE TABLE IF NOT EXISTS auth.login_state (\n state varchar(128) PRIMARY KEY,\n code_verifier varchar(255) NOT NULL,\n redirect_path text NOT NULL DEFAULT '/',\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_login_state_expires\n ON auth.login_state(expires_at);\n`\n\n// The KC ID token, so RP-initiated logout can pass it as `id_token_hint` —\n// without it, Keycloak's end-session endpoint falls back to showing a logout\n// confirmation page. Nullable: existing sessions predate this column until\n// their next login or token refresh backfills it.\nconst MIGRATION_0002_ID_TOKEN = `\nALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS id_token text;\n`\n\n// Records that this login asked Keycloak to re-authenticate (prompt=login +\n// max_age=0). The callback needs it to know whether the ID token's auth_time\n// MUST prove a fresh authentication (OIDC 3.1.2.1) — without the flag it cannot\n// tell a forced login from an ordinary SSO continuation.\nconst MIGRATION_0003_FORCED_REAUTH = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS forced_reauth boolean NOT NULL DEFAULT false;\n`\n\n// OIDC 3.1.3.7 (11): the nonce sent on the authorization request must be\n// checked against the ID token's claim. Nullable because rows written by an\n// older build have none; the callback treats a null nonce on the row as\n// \"nothing to check\" so an in-flight login survives the deploy.\nconst MIGRATION_0004_NONCE = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS nonce varchar(128);\n`\n\n// Bounds the one-and-only restart the callback grants on Keycloak's explicit\n// \"start over\" signals (authentication_expired / login_required). The\n// callback URL is Keycloak's fixed redirect_uri, so Keycloak never echoes our\n// own query parameters back to it — a guard read off the callback's query\n// string can never fire in production. The restarted login (our own request\n// to /api/auth/login?retried=1) stamps this column on the NEW row instead, so\n// the second callback can see it on the row rather than in a URL Keycloak\n// controls. NOT NULL DEFAULT false: every row, old or new, starts un-retried.\nconst MIGRATION_0005_RETRIED = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS retried boolean NOT NULL DEFAULT false;\n`\n\n// A session created for an identity that did not match what the login expected\n// exists, holds real tokens, and grants nothing until a human confirms it.\n//\n// DELIBERATELY `DEFAULT false` rather than a nullable column with a backfill:\n// these migrations re-run on every app start, so an `UPDATE ... WHERE\n// pending_identity_confirm IS NULL` would confirm every row still awaiting a\n// human on the next deploy — silently adopting exactly the identity this\n// mechanism exists to stop. A default means pre-existing rows are already\n// confirmed, which is correct: they were issued under the old rules.\nconst MIGRATION_0006_PENDING_CONFIRM = `\nALTER TABLE auth.sessions\n ADD COLUMN IF NOT EXISTS pending_identity_confirm boolean NOT NULL DEFAULT false;\n`\n\n// Who this login was supposed to end up as: the subject of the session being\n// replaced, and/or the address the user typed. The callback compares Keycloak's\n// answer against these instead of adopting whatever comes back. Nullable: a\n// clean first login on a fresh browser expects nobody in particular.\nconst MIGRATION_0007_EXPECTED_IDENTITY = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_sub varchar(64);\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_email varchar(320);\n`\n\ninterface Migration {\n // Named so a failure can say *which* statement broke — see the catch below.\n readonly name: string\n readonly sql: string\n // \"Is this migration's effect already present?\" Answered from the catalogs\n // only, so it never needs a privilege the migration itself would need. A\n // partially-applied migration must answer `false` (the SQL is written to be\n // idempotent, so re-running the applied half is harmless).\n readonly isApplied: (db: NodePgDatabase) => Promise<boolean>\n // A migration may only add to the schema: a prod rollback keeps the\n // database, and the previous release must still work on it\n // (scripts/migration-lint.mjs refuses anything else). `true` marks the rare\n // migration that removes or tightens something on purpose; ship it only once\n // no prod still runs a version that reads the old shape.\n readonly contract?: boolean\n}\n\n// All probes funnel through here: one boolean expression, evaluated by the\n// server. Every one of them reads `pg_catalog` directly rather than going\n// through `to_regclass`/`to_regnamespace` or `information_schema`, both of\n// which are privilege-sensitive in ways that defeat the purpose: `to_regclass`\n// resolves the name and so raises `permission denied for schema auth` for a\n// role without USAGE, and `information_schema.columns` silently hides columns\n// the role holds no privilege on — reporting an applied migration as missing\n// and sending us straight into the ALTER we were trying to avoid. The catalogs\n// themselves are world-readable.\nasync function probe(db: NodePgDatabase, expression: string): Promise<boolean> {\n const result = await db.execute<{ applied: boolean }>(\n sql.raw(`SELECT (${expression}) AS \"applied\"`),\n )\n return result.rows[0]?.applied === true\n}\n\nconst schemaExists = (schema: string) => (db: NodePgDatabase) =>\n probe(db, `EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = '${schema}')`)\n\n// Tables and indexes alike — both live in `pg_class`.\nconst relationsExist =\n (...relations: readonly (readonly [schema: string, name: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = relations.map(([schema, name]) => `('${schema}','${name}')`).join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE (n.nspname, c.relname) IN (${tuples})) = ${relations.length}`,\n )\n }\n\nconst columnsExist =\n (...columns: readonly (readonly [schema: string, table: string, column: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = columns\n .map(([schema, table, column]) => `('${schema}','${table}','${column}')`)\n .join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE a.attnum > 0 AND NOT a.attisdropped\n AND (n.nspname, c.relname, a.attname) IN (${tuples})) = ${columns.length}`,\n )\n }\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n name: \"0001_init:schema\",\n sql: MIGRATION_0001_SCHEMA,\n isApplied: schemaExists(\"auth\"),\n },\n {\n name: \"0001_init:tables\",\n sql: MIGRATION_0001_TABLES,\n isApplied: relationsExist(\n [\"auth\", \"sessions\"],\n [\"auth\", \"ix_auth_sessions_user_sub\"],\n [\"auth\", \"login_state\"],\n [\"auth\", \"ix_auth_login_state_expires\"],\n ),\n },\n {\n name: \"0002_id_token\",\n sql: MIGRATION_0002_ID_TOKEN,\n isApplied: columnsExist([\"auth\", \"sessions\", \"id_token\"]),\n },\n {\n name: \"0003_forced_reauth\",\n sql: MIGRATION_0003_FORCED_REAUTH,\n isApplied: columnsExist([\"auth\", \"login_state\", \"forced_reauth\"]),\n },\n {\n name: \"0004_nonce\",\n sql: MIGRATION_0004_NONCE,\n isApplied: columnsExist([\"auth\", \"login_state\", \"nonce\"]),\n },\n {\n name: \"0005_retried\",\n sql: MIGRATION_0005_RETRIED,\n isApplied: columnsExist([\"auth\", \"login_state\", \"retried\"]),\n },\n {\n name: \"0006_pending_confirm\",\n sql: MIGRATION_0006_PENDING_CONFIRM,\n isApplied: columnsExist([\"auth\", \"sessions\", \"pending_identity_confirm\"]),\n },\n {\n name: \"0007_expected_identity\",\n sql: MIGRATION_0007_EXPECTED_IDENTITY,\n isApplied: columnsExist(\n [\"auth\", \"login_state\", \"expected_sub\"],\n [\"auth\", \"login_state\", \"expected_email\"],\n ),\n },\n]\n\nexport interface RunAuthMigrationsOptions {\n // When provided, grants this role SELECT/INSERT/UPDATE/DELETE on every\n // table in the `auth` schema — both ones this call just created and ones a\n // future boot's migrations will create. Omit for a single-role setup (the\n // fallback state of an environment that hasn't opted into a separate\n // migration role yet); passing it is what makes it safe for `db` to\n // connect as an admin/owner role while the app itself never does.\n readonly runtimeRole?: string\n}\n\nexport async function runAuthMigrations(\n db: NodePgDatabase,\n opts: RunAuthMigrationsOptions = {},\n): Promise<void> {\n for (const migration of MIGRATIONS) {\n try {\n if (await migration.isApplied(db)) {\n // Already there — do not issue the statement at all. See the comment\n // above MIGRATION_0001_SCHEMA for why relying on `IF NOT EXISTS` to make\n // it a no-op is not safe under every role.\n continue\n }\n await db.execute(sql.raw(migration.sql))\n } catch (err) {\n // Re-thrown, not swallowed: the caller decides what to do with a failed\n // migration. Naming the statement is what turns a bare \"permission\n // denied for database x\" into something you can actually act on; the\n // `cause` keeps the original Postgres error (code, detail, etc.) intact.\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(`auth migration \"${migration.name}\" failed: ${message}`, { cause: err })\n }\n }\n\n if (opts.runtimeRole) {\n await grantRuntimeDefaultPrivileges(db, \"auth\", opts.runtimeRole)\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,WAAW;AAmCpB,IAAM,wBAAwB;AAAA;AAAA;AAI9B,IAAM,wBAAwB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoC9B,IAAM,0BAA0B;AAAA;AAAA;AAQhC,IAAM,+BAA+B;AAAA;AAAA;AAQrC,IAAM,uBAAuB;AAAA;AAAA;AAY7B,IAAM,yBAAyB;AAAA;AAAA;AAa/B,IAAM,iCAAiC;AAAA;AAAA;AAAA;AASvC,IAAM,mCAAmC;AAAA;AAAA;AAAA;AA+BzC,eAAe,MAAM,IAAoB,YAAsC;AAC7E,QAAM,SAAS,MAAM,GAAG;AAAA,IACtB,IAAI,IAAI,WAAW,UAAU,gBAAgB;AAAA,EAC/C;AACA,SAAO,OAAO,KAAK,CAAC,GAAG,YAAY;AACrC;AAEA,IAAM,eAAe,CAAC,WAAmB,CAAC,OACxC,MAAM,IAAI,uDAAuD,MAAM,IAAI;AAG7E,IAAM,iBACJ,IAAI,cACJ,CAAC,OAAuB;AACtB,QAAM,SAAS,UAAU,IAAI,CAAC,CAAC,QAAQ,IAAI,MAAM,KAAK,MAAM,MAAM,IAAI,IAAI,EAAE,KAAK,IAAI;AACrF,SAAO;AAAA,IACL;AAAA,IACA;AAAA;AAAA,2CAEqC,MAAM,QAAQ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AAK;AAAA,IACL,WAAW;AAAA,MACT,CAAC,QAAQ,eAAe,cAAc;AAAA,MACtC,CAAC,QAAQ,eAAe,gBAAgB;AAAA,IAC1C;AAAA,EACF;AACF;AAYA,eAAsB,kBACpB,IACA,OAAiC,CAAC,GACnB;AACf,aAAW,aAAa,YAAY;AAClC,QAAI;AACF,UAAI,MAAM,UAAU,UAAU,EAAE,GAAG;AAIjC;AAAA,MACF;AACA,YAAM,GAAG,QAAQ,IAAI,IAAI,UAAU,GAAG,CAAC;AAAA,IACzC,SAAS,KAAK;AAKZ,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,YAAM,IAAI,MAAM,mBAAmB,UAAU,IAAI,aAAa,OAAO,IAAI,EAAE,OAAO,IAAI,CAAC;AAAA,IACzF;AAAA,EACF;AAEA,MAAI,KAAK,aAAa;AACpB,UAAM,8BAA8B,IAAI,QAAQ,KAAK,WAAW;AAAA,EAClE;AACF;","names":[]}
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-5XMTUPIY.js";
5
5
  import {
6
6
  getLogger
7
- } from "./chunk-EK6TGWWT.js";
7
+ } from "./chunk-MET4SIMB.js";
8
8
 
9
9
  // src/connections-core/errors.ts
10
10
  var ConnectionError = class extends Error {
@@ -70,4 +70,4 @@ export {
70
70
  CONNECTION_REJECT_REASON_ATTR,
71
71
  requireConnection
72
72
  };
73
- //# sourceMappingURL=chunk-ROHIN74F.js.map
73
+ //# sourceMappingURL=chunk-TEBDKNUB.js.map
@@ -0,0 +1,109 @@
1
+ import {
2
+ defaultEnv,
3
+ normalizeAlias
4
+ } from "./chunk-5XMTUPIY.js";
5
+
6
+ // src/integrations-core/types.ts
7
+ function defineIntegrations(map) {
8
+ return map;
9
+ }
10
+ var AUTH_ENV_FIELDS = {
11
+ none: [],
12
+ api_key_header: ["apiKey"],
13
+ bearer_static: ["token"],
14
+ basic: ["username", "password"],
15
+ oauth2_client_credentials: ["tokenUrl", "clientId", "clientSecret", "scope", "audience"]
16
+ };
17
+ var AUTH_SECRET_FIELDS = ["apiKey", "token", "password", "clientSecret"];
18
+ var RESERVED_KEY_PREFIX = "QORE_INTEGRATION_";
19
+
20
+ // src/integrations-core/env.ts
21
+ function refKey(ref) {
22
+ return typeof ref === "string" ? ref : ref.key;
23
+ }
24
+ function refOptional(ref) {
25
+ return typeof ref !== "string" && (ref.optional === true || ref.default !== void 0);
26
+ }
27
+ function authKeys(def) {
28
+ const auth = def.auth;
29
+ return AUTH_ENV_FIELDS[def.auth.kind].map((field) => auth[field]).filter((key) => typeof key === "string" && key !== "");
30
+ }
31
+ function requiredKeys(def) {
32
+ const keys = [def.baseUrl, ...authKeys(def)];
33
+ for (const ref of Object.values(def.config ?? {})) {
34
+ if (!refOptional(ref)) keys.push(refKey(ref));
35
+ }
36
+ return [...new Set(keys)];
37
+ }
38
+ function allKeys(def) {
39
+ const keys = [def.baseUrl, ...authKeys(def)];
40
+ for (const ref of Object.values(def.config ?? {})) keys.push(refKey(ref));
41
+ return [...new Set(keys)];
42
+ }
43
+ function readRef(env, ref) {
44
+ const value = env[refKey(ref)];
45
+ if (value !== void 0 && value !== "") return value;
46
+ return typeof ref === "string" ? void 0 : ref.default;
47
+ }
48
+ function loggingKey(alias) {
49
+ return `${RESERVED_KEY_PREFIX}${normalizeAlias(alias)}_LOGGING`;
50
+ }
51
+ function loggingEnabled(env, alias) {
52
+ const value = env[loggingKey(alias)];
53
+ return value === "1" || value?.toLowerCase() === "true";
54
+ }
55
+
56
+ // src/integrations-core/assertIntegrations.ts
57
+ var ENV_KEY_RE = /^[A-Z][A-Z0-9_]*$/;
58
+ function assertIntegrations(map, opts = {}) {
59
+ const env = opts.env ?? defaultEnv();
60
+ const warn = opts.warn ?? ((message) => console.warn(message));
61
+ const problems = [];
62
+ for (const [alias, def] of Object.entries(map)) {
63
+ for (const key of allKeys(def)) {
64
+ let why;
65
+ if (key.startsWith(RESERVED_KEY_PREFIX)) {
66
+ why = `${RESERVED_KEY_PREFIX}* keys are reserved by the platform`;
67
+ } else if (key.startsWith("CONN_")) {
68
+ why = "CONN_* keys belong to module connections, not integrations";
69
+ } else if (!ENV_KEY_RE.test(key)) {
70
+ why = "an env key is uppercase letters, digits and underscores";
71
+ }
72
+ if (why) {
73
+ problems.push({
74
+ alias,
75
+ key,
76
+ code: "reserved_key",
77
+ message: `Integration "${alias}" declares env key "${key}": ${why}`
78
+ });
79
+ }
80
+ }
81
+ for (const key of requiredKeys(def)) {
82
+ const value = env[key];
83
+ if (value === void 0 || value === "") {
84
+ problems.push({
85
+ alias,
86
+ key,
87
+ code: "missing_env",
88
+ message: `Integration "${alias}" is missing env key "${key}"; calls to it will fail until it is set`
89
+ });
90
+ }
91
+ }
92
+ }
93
+ for (const p of problems) warn(`[integrations] ${p.message}`);
94
+ return problems;
95
+ }
96
+
97
+ export {
98
+ defineIntegrations,
99
+ AUTH_ENV_FIELDS,
100
+ AUTH_SECRET_FIELDS,
101
+ RESERVED_KEY_PREFIX,
102
+ requiredKeys,
103
+ allKeys,
104
+ readRef,
105
+ loggingKey,
106
+ loggingEnabled,
107
+ assertIntegrations
108
+ };
109
+ //# sourceMappingURL=chunk-TOBGX4CZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/integrations-core/types.ts","../src/integrations-core/env.ts","../src/integrations-core/assertIntegrations.ts"],"sourcesContent":["/**\n * How an integration authenticates. Every field except `header` and\n * `credentialsIn` names an **env key** — the SDK reads the value from the\n * environment at call time, never from the declaration — so a declaration can\n * sit in source control and carry no secret.\n */\nexport type AuthKind =\n | \"none\"\n | \"api_key_header\"\n | \"bearer_static\"\n | \"basic\"\n | \"oauth2_client_credentials\"\n\n/** What the API speaks. Informational for the portal; the client sends bytes either way. */\nexport type Protocol = \"rest\" | \"odata\" | \"soap\" | \"graphql\"\n\n/** The name of an env var, e.g. `SAP_BASE_URL`. */\nexport type EnvKey = string\n\n/**\n * A reference to an env var. The short form is required; the object form can\n * be optional and carry a default the app falls back on when the key is unset.\n */\nexport type EnvRef =\n | EnvKey\n | { key: EnvKey; optional?: boolean; default?: string | number | boolean }\n\nexport type IntegrationAuth =\n | { kind: \"none\" }\n | { kind: \"api_key_header\"; header: string; apiKey: EnvKey }\n | { kind: \"bearer_static\"; token: EnvKey }\n | { kind: \"basic\"; username: EnvKey; password: EnvKey }\n | {\n kind: \"oauth2_client_credentials\"\n tokenUrl: EnvKey\n clientId: EnvKey\n clientSecret: EnvKey\n scope?: EnvKey\n audience?: EnvKey\n /** Where the client credentials go on the token request. Default `\"header\"`. */\n credentialsIn?: \"header\" | \"body\"\n }\n\nexport interface IntegrationDefinition {\n /** Human name shown in the portal, e.g. \"SAP S/4HANA Cloud\". */\n label: string\n protocol: Protocol\n /** Env key holding the base URL for this environment. */\n baseUrl: EnvKey\n auth: IntegrationAuth\n /** Further env the app reads for this integration, by logical name. */\n config?: Record<string, EnvRef>\n}\n\nexport type IntegrationMap = Record<string, IntegrationDefinition>\n\n/**\n * Identity function that pins the literal types of the map, so an alias typo\n * at a call site is a compile error (`keyof M`) rather than a runtime\n * `not_declared`. Same shape as `definePermissions` in `auth-core`.\n */\nexport function defineIntegrations<const M extends IntegrationMap>(map: M): M {\n return map\n}\n\n/**\n * Which fields of each auth kind name an env key. Shared with the manifest\n * extractor and the portal, which derive the required-env list from a\n * declaration without evaluating app code.\n */\nexport const AUTH_ENV_FIELDS: Record<AuthKind, readonly string[]> = {\n none: [],\n api_key_header: [\"apiKey\"],\n bearer_static: [\"token\"],\n basic: [\"username\", \"password\"],\n oauth2_client_credentials: [\"tokenUrl\", \"clientId\", \"clientSecret\", \"scope\", \"audience\"],\n}\n\n/** Auth fields whose env value is a secret, so the portal masks it. */\nexport const AUTH_SECRET_FIELDS = [\"apiKey\", \"token\", \"password\", \"clientSecret\"] as const\n\n/**\n * Env keys under this prefix belong to the platform\n * (`QORE_INTEGRATION_<ALIAS>_LOGGING` today). A declaration may not claim one.\n */\nexport const RESERVED_KEY_PREFIX = \"QORE_INTEGRATION_\"\n","import { normalizeAlias, type Env } from \"../connections-core/env\"\nimport {\n AUTH_ENV_FIELDS,\n RESERVED_KEY_PREFIX,\n type EnvRef,\n type IntegrationDefinition,\n} from \"./types\"\n\nexport type { Env }\n\nexport function refKey(ref: EnvRef): string {\n return typeof ref === \"string\" ? ref : ref.key\n}\n\nfunction refOptional(ref: EnvRef): boolean {\n return typeof ref !== \"string\" && (ref.optional === true || ref.default !== undefined)\n}\n\n/** The auth fields of `def` that are set, as env keys. */\nfunction authKeys(def: IntegrationDefinition): string[] {\n const auth = def.auth as unknown as Record<string, unknown>\n return AUTH_ENV_FIELDS[def.auth.kind]\n .map((field) => auth[field])\n .filter((key): key is string => typeof key === \"string\" && key !== \"\")\n}\n\n/**\n * Every env key the integration cannot run without: the base URL, every auth\n * field that is set, and every config ref that is neither optional nor\n * defaulted. Order is stable so an error message reads the same twice.\n */\nexport function requiredKeys(def: IntegrationDefinition): string[] {\n const keys = [def.baseUrl, ...authKeys(def)]\n for (const ref of Object.values(def.config ?? {})) {\n if (!refOptional(ref)) keys.push(refKey(ref))\n }\n return [...new Set(keys)]\n}\n\n/** Every env key the declaration names, required or not. */\nexport function allKeys(def: IntegrationDefinition): string[] {\n const keys = [def.baseUrl, ...authKeys(def)]\n for (const ref of Object.values(def.config ?? {})) keys.push(refKey(ref))\n return [...new Set(keys)]\n}\n\n/**\n * Read one ref from `env`, applying its default when the key is unset or\n * empty. A default comes back as declared (a number or boolean stays typed);\n * an env value is always a string.\n */\nexport function readRef(env: Env, ref: EnvRef): string | number | boolean | undefined {\n const value = env[refKey(ref)]\n if (value !== undefined && value !== \"\") return value\n return typeof ref === \"string\" ? undefined : ref.default\n}\n\n/** `QORE_INTEGRATION_<ALIAS>_LOGGING` — the one reserved key v1 reads. */\nexport function loggingKey(alias: string): string {\n return `${RESERVED_KEY_PREFIX}${normalizeAlias(alias)}_LOGGING`\n}\n\n/** Whether the per-call JSON log line is switched on for this alias (\"1\" or \"true\"). */\nexport function loggingEnabled(env: Env, alias: string): boolean {\n const value = env[loggingKey(alias)]\n return value === \"1\" || value?.toLowerCase() === \"true\"\n}\n","import { defaultEnv, type Env } from \"../connections-core/env\"\nimport { allKeys, requiredKeys } from \"./env\"\nimport { RESERVED_KEY_PREFIX, type IntegrationMap } from \"./types\"\n\nconst ENV_KEY_RE = /^[A-Z][A-Z0-9_]*$/\n\nexport interface IntegrationProblem {\n alias: string\n key: string\n /** `missing_env`: a required key is unset or empty. `reserved_key`: the declaration claims a key it may not. */\n code: \"missing_env\" | \"reserved_key\"\n message: string\n}\n\n/**\n * Report, at app startup, what is wrong with the declared integrations: a\n * required env key that is unset, or a key the declaration may not claim.\n * **It never throws.** Integrations are a visibility tool: an API key that is\n * not set (an obsolete integration, a vendor not contracted in this\n * environment) must cost the calls to that one integration — they fail with\n * `missing_env` — never the boot of the whole app. Each problem is logged as\n * one warning and returned, so a caller may act on them if it chooses.\n */\nexport function assertIntegrations(\n map: IntegrationMap,\n opts: { env?: Env; warn?: (message: string) => void } = {},\n): IntegrationProblem[] {\n const env = opts.env ?? defaultEnv()\n const warn = opts.warn ?? ((message: string) => console.warn(message))\n const problems: IntegrationProblem[] = []\n\n for (const [alias, def] of Object.entries(map)) {\n for (const key of allKeys(def)) {\n let why: string | undefined\n if (key.startsWith(RESERVED_KEY_PREFIX)) {\n why = `${RESERVED_KEY_PREFIX}* keys are reserved by the platform`\n } else if (key.startsWith(\"CONN_\")) {\n why = \"CONN_* keys belong to module connections, not integrations\"\n } else if (!ENV_KEY_RE.test(key)) {\n why = \"an env key is uppercase letters, digits and underscores\"\n }\n if (why) {\n problems.push({\n alias,\n key,\n code: \"reserved_key\",\n message: `Integration \"${alias}\" declares env key \"${key}\": ${why}`,\n })\n }\n }\n for (const key of requiredKeys(def)) {\n const value = env[key]\n if (value === undefined || value === \"\") {\n problems.push({\n alias,\n key,\n code: \"missing_env\",\n message: `Integration \"${alias}\" is missing env key \"${key}\"; calls to it will fail until it is set`,\n })\n }\n }\n }\n\n for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,MAAM;AAAA,UACN,SAAS,gBAAgB,KAAK,yBAAyB,GAAG;AAAA,QAC5D,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,aAAW,KAAK,SAAU,MAAK,kBAAkB,EAAE,OAAO,EAAE;AAC5D,SAAO;AACT;","names":[]}
@@ -0,0 +1,20 @@
1
+ import {
2
+ initSentry
3
+ } from "./chunk-G7VPNC6M.js";
4
+ import {
5
+ readSentryConfig
6
+ } from "./chunk-7ASQHY7O.js";
7
+
8
+ // src/next/sentry/register.ts
9
+ import * as Sentry from "@sentry/nextjs";
10
+ async function register() {
11
+ const runtime = process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
12
+ initSentry(Sentry, runtime, readSentryConfig(process.env, { frontend: true }));
13
+ }
14
+ var onRequestError = Sentry.captureRequestError;
15
+
16
+ export {
17
+ register,
18
+ onRequestError
19
+ };
20
+ //# sourceMappingURL=chunk-WU7N4PET.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/next/sentry/register.ts"],"sourcesContent":["import * as Sentry from \"@sentry/nextjs\"\nimport { readSentryConfig } from \"../../sentry-core/env\"\nimport { initSentry } from \"../../sentry-core/init\"\n\nexport async function register(): Promise<void> {\n const runtime = process.env.NEXT_RUNTIME === \"edge\" ? \"edge\" : \"node\"\n initSentry(Sentry, runtime, readSentryConfig(process.env, { frontend: true }))\n}\n\nexport const onRequestError = Sentry.captureRequestError\n"],"mappings":";;;;;;;;AAAA,YAAY,YAAY;AAIxB,eAAsB,WAA0B;AAC9C,QAAM,UAAU,QAAQ,IAAI,iBAAiB,SAAS,SAAS;AAC/D,aAAW,QAAQ,SAAS,iBAAiB,QAAQ,KAAK,EAAE,UAAU,KAAK,CAAC,CAAC;AAC/E;AAEO,IAAM,iBAAwB;","names":[]}
@@ -23,13 +23,14 @@ var BUNDLE = /^[a-z0-9][a-z0-9-]{0,31}$/;
23
23
  var SCRIPT = /\.(js|mjs|cjs)$/;
24
24
  var MAPPING_URL = /^\/\/# sourceMappingURL=(\S+)[ \t]*$/gm;
25
25
  var STANDALONE_SERVER = "standalone/.next/server/";
26
+ var isCommand = (cmd) => cmd === "upload" || cmd === "finalize";
26
27
  function parseArgs(argv) {
27
28
  const [cmd, dir, ...rest] = argv;
28
- if (cmd !== "upload" || !dir) return { error: "usage: qore-sourcemaps upload <dir> [--bundle <name>]" };
29
+ if (!isCommand(cmd) || !dir) return { error: "usage: qore-sourcemaps upload|finalize <dir> [--bundle <name>]" };
29
30
  let bundle = "app";
30
31
  if (rest[0] === "--bundle") bundle = rest[1] ?? "";
31
32
  if (!BUNDLE.test(bundle)) return { error: `invalid bundle name: ${bundle}` };
32
- return { dir, bundle };
33
+ return { cmd, dir, bundle };
33
34
  }
34
35
  function nextRoots(has) {
35
36
  if (!has("BUILD_ID") || !has("server")) return null;
@@ -122,11 +123,11 @@ async function runCommand(cmd, args) {
122
123
  env: { ...process.env, COPYFILE_DISABLE: "1" }
123
124
  });
124
125
  }
125
- function walkDir(dir, prefix = "") {
126
+ function walkDir(dir, prefix = "", modules = false) {
126
127
  const out = [];
127
128
  for (const d of readdirSync(join(dir, prefix), { withFileTypes: true })) {
128
129
  const rel = prefix ? `${prefix}/${d.name}` : d.name;
129
- if (d.isDirectory() && d.name !== "node_modules") out.push(...walkDir(dir, rel));
130
+ if (d.isDirectory() && (modules || d.name !== "node_modules")) out.push(...walkDir(dir, rel, modules));
130
131
  else if (d.isFile()) out.push(rel);
131
132
  }
132
133
  return out;
@@ -134,6 +135,7 @@ function walkDir(dir, prefix = "") {
134
135
  var defaultIo = () => ({
135
136
  env: process.env,
136
137
  walk: (dir) => walkDir(dir),
138
+ walkAll: (dir) => walkDir(dir, "", true),
137
139
  exists: existsSync,
138
140
  readText: (p) => readFileSync(p, "utf8"),
139
141
  writeText: (p, t) => writeFileSync(p, t),
@@ -154,11 +156,18 @@ function tryRemove(io, path) {
154
156
  } catch {
155
157
  }
156
158
  }
159
+ function removeAllMaps(io, dir) {
160
+ try {
161
+ for (const p of io.walkAll(dir)) if (p.endsWith(".map")) tryRemove(io, join(dir, p));
162
+ } catch (err) {
163
+ console.warn(`qore-sourcemaps: cleanup skipped: ${describe(err, io.env.QORE_BUILD_UPLOAD_TOKEN)}`);
164
+ }
165
+ }
157
166
  async function main(argv = process.argv.slice(2), io = defaultIo()) {
158
167
  const args = parseArgs(argv);
159
168
  if ("error" in args) {
160
169
  console.warn(`qore-sourcemaps: ${args.error}`);
161
- const dir2 = argv[0] === "upload" ? argv[1] : void 0;
170
+ const dir2 = isCommand(argv[0]) ? argv[1] : void 0;
162
171
  if (dir2 && !dir2.startsWith("-")) {
163
172
  try {
164
173
  for (const m of listMaps(io.walk(dir2))) tryRemove(io, join(dir2, m));
@@ -168,7 +177,7 @@ async function main(argv = process.argv.slice(2), io = defaultIo()) {
168
177
  }
169
178
  return;
170
179
  }
171
- const { dir, bundle } = args;
180
+ const { cmd, dir, bundle } = args;
172
181
  const at = (rel) => join(dir, rel);
173
182
  let maps = [];
174
183
  const scratch = [];
@@ -222,6 +231,7 @@ async function main(argv = process.argv.slice(2), io = defaultIo()) {
222
231
  } finally {
223
232
  for (const m of maps) tryRemove(io, at(m));
224
233
  for (const s of scratch) tryRemove(io, s);
234
+ if (cmd === "finalize") removeAllMaps(io, dir);
225
235
  }
226
236
  }
227
237
  function isMainModule() {
@@ -172,6 +172,103 @@ off the SDK's lint rules that check the same things.
172
172
  The \`qore-\` prefix is reserved for managed skills. Sync never touches a skill
173
173
  it does not ship, so your own skills are safe under any other name.
174
174
  `;
175
+ var APP_README_PATH = "README.md";
176
+ function isLegacyAppReadme(text) {
177
+ const flat = text.replace(/\s+/g, " ");
178
+ return flat.includes("frozen at generation time") && flat.includes("The `quatronic-` prefix is reserved");
179
+ }
180
+ var APP_README_HEAD = `# Claude Code setup for this app
181
+
182
+ This app ships with a Qore Claude Code setup, committed into this repo. The
183
+ \`qore-*\` skills are managed by the SDK; everything else here is yours.
184
+ `;
185
+ var APP_README_CONVENTIONS = `## Conventions
186
+
187
+ - The \`qore-*\` skills are managed by \`@quatronic/sdk\` and stay current with it:
188
+ every SDK upgrade PR re-syncs them. How to turn one off, extend it with your
189
+ own conventions, replace it or keep your own copy is in
190
+ \`qore/README.md\`; editing a managed skill in place does not stick.
191
+ - The \`qore-\` prefix is reserved for managed skills. Name your own skills
192
+ without it (e.g. \`.claude/skills/export-report/SKILL.md\`); sync never touches
193
+ them.
194
+ - \`settings.json\` is yours: it was generated once and nothing re-syncs it.
195
+ `;
196
+ function appReadme(runtime) {
197
+ if (runtime === "next") {
198
+ return `${APP_README_HEAD}
199
+ > New here? Run \`/qore-recommended-tools\` for optional, public skills and
200
+ > plugins (like \`superpowers\` and \`frontend-design\`) that pair well with this app.
201
+
202
+ ## What's here
203
+
204
+ - \`settings.json\` \u2014 a safe permission floor: secrets (\`.env\`, \`.env.local\`) can't be read or
205
+ written (\`.env.example\` stays readable), destructive git is blocked, and \`git push\` plus edits to the auth/SDK
206
+ boundary files ask for confirmation.
207
+ - \`skills/qore-*\` \u2014 the managed skills, listed with when to reach for each in
208
+ \`qore/skills.md\` (imported into \`CLAUDE.md\`). Highlights:
209
+ \`/qore-ship-checklist\` (the quality gate to run before every PR),
210
+ \`/qore-author-skill\` to write your own, and \`/qore-recommended-tools\` for
211
+ optional public skills/plugins.
212
+ - \`qore/\` \u2014 \`README.md\` (what you can and can't do with managed skills),
213
+ \`skills.md\` (the index) and \`manifest.json\` (what sync manages).
214
+ - \`../.github/workflows/ci.yml\` \u2014 the PR gate. It calls Quatronic's shared
215
+ pipeline, which runs lint, format-check, typecheck, unit tests,
216
+ integration tests and build on every pull request and on every push to
217
+ \`main\`. Each of those is one of *your* \`package.json\` scripts, so change
218
+ what a check does by changing the script. Add your own jobs to the
219
+ \`verify\` job's \`needs:\` list; leave the shared call alone, as edits to it
220
+ are replaced when the pipeline is upgraded.
221
+
222
+ ${APP_README_CONVENTIONS}`;
223
+ }
224
+ return `${APP_README_HEAD}
225
+ ## What's here
226
+
227
+ - \`settings.json\` \u2014 a safe permission floor: secrets (\`.env\`, \`.env.local\`) can't be read or
228
+ written, destructive git is blocked, and \`git push\` asks for confirmation.
229
+ - \`skills/qore-*\` \u2014 the managed skills, listed with when to reach for each in
230
+ \`qore/skills.md\` (imported into \`CLAUDE.md\`).
231
+ - \`qore/\` \u2014 \`README.md\` (what you can and can't do with managed skills),
232
+ \`skills.md\` (the index) and \`manifest.json\` (what sync manages).
233
+ - \`../.github/workflows/ci.yml\` \u2014 the PR gate. It calls Quatronic's shared
234
+ pipeline, which runs typecheck, unit tests and build on every pull request
235
+ and on every push to \`main\`. Each of those is one of *your*
236
+ \`package.json\` scripts, so change what a check does by changing the
237
+ script; adding a \`lint\` script is not enough on its own, since the call
238
+ also has to ask for that check. Add your own jobs to the \`verify\` job's
239
+ \`needs:\` list; leave the shared call alone, as edits to it are replaced
240
+ when the pipeline is upgraded.
241
+
242
+ ${APP_README_CONVENTIONS}`;
243
+ }
244
+ var TABLE_ROW = /^\s*\|(.*)\|\s*$/;
245
+ var TABLE_RULE = /^\s*\|[\s:|-]+\|\s*$/;
246
+ var firstCell = (line) => TABLE_ROW.exec(line)?.[1].split("|")[0].trim();
247
+ function replaceSkillsTable(md, names) {
248
+ const eol = md.includes("\r\n") ? "\r\n" : "\n";
249
+ const lines = md.split(/\r?\n/);
250
+ for (let i = 0; i + 2 < lines.length; i++) {
251
+ if (!/^skill$/i.test(firstCell(lines[i]) ?? "") || !TABLE_RULE.test(lines[i + 1])) continue;
252
+ let end = i + 2;
253
+ while (end < lines.length && firstCell(lines[end]) !== void 0) end++;
254
+ const rows = lines.slice(i + 2, end);
255
+ const managed = rows.length > 0 && rows.every((r) => {
256
+ const name = /^`\/?([a-z0-9-]+)`$/.exec(firstCell(r))?.[1];
257
+ return name !== void 0 && names.has(name);
258
+ });
259
+ if (!managed) continue;
260
+ const out = [];
261
+ lines.forEach((line, j) => {
262
+ if (j === i) out.push(CLAUDE_MD_IMPORT);
263
+ else if (j > i && j < end) return;
264
+ else if (line.trim() === CLAUDE_MD_IMPORT) {
265
+ if (out.at(-1)?.trim() === "") out.pop();
266
+ } else out.push(line);
267
+ });
268
+ return out.join(eol);
269
+ }
270
+ return void 0;
271
+ }
175
272
  function buildTree(catalog, sources, f) {
176
273
  const skills = renderSkills(catalog, sources, f);
177
274
  for (const entry of catalog.skills) {
@@ -246,6 +343,7 @@ function planSync(s) {
246
343
  let claudeMd = s.claudeMd;
247
344
  const claudeMdRenamed = [];
248
345
  let claudeMdImportAdded = false;
346
+ let claudeMdTableReplaced = false;
249
347
  if (claudeMd !== void 0) {
250
348
  for (const entry of s.catalog.skills) {
251
349
  for (const legacy of entry.legacyNames ?? []) {
@@ -255,6 +353,11 @@ function planSync(s) {
255
353
  claudeMdRenamed.push([legacy, entry.name]);
256
354
  }
257
355
  }
356
+ const withoutTable = replaceSkillsTable(claudeMd, new Set(s.catalog.skills.map((e) => e.name)));
357
+ if (withoutTable !== void 0) {
358
+ claudeMd = withoutTable;
359
+ claudeMdTableReplaced = true;
360
+ }
258
361
  if (!claudeMd.split(/\r?\n/).some((l) => l.trim() === CLAUDE_MD_IMPORT)) {
259
362
  claudeMd = `${claudeMd.replace(/\s*$/, "")}
260
363
 
@@ -263,6 +366,9 @@ ${CLAUDE_MD_IMPORT}
263
366
  claudeMdImportAdded = true;
264
367
  }
265
368
  }
369
+ const currentReadme = s.read(APP_README_PATH);
370
+ const appReadmeReplaced = currentReadme !== void 0 && isLegacyAppReadme(currentReadme);
371
+ if (appReadmeReplaced) writes.set(APP_README_PATH, appReadme(s.features.runtime));
266
372
  const manifest = {
267
373
  schemaVersion: 1,
268
374
  sdkVersion: s.sdkVersion,
@@ -271,6 +377,10 @@ ${CLAUDE_MD_IMPORT}
271
377
  detached: [...detached].sort(),
272
378
  files: Object.fromEntries([...tree].map(([rel, c]) => [rel, hashContent(c)]))
273
379
  };
380
+ const skillsIn = (rels) => new Set([...rels].map(skillOf).filter((n) => n !== void 0 && !detached.has(n)));
381
+ const before = skillsIn(Object.keys(known));
382
+ const after = skillsIn(tree.keys());
383
+ const touched = skillsIn([...writes.keys(), ...deletes]);
274
384
  const manifestText = renderManifest(manifest);
275
385
  if (s.read(MANIFEST_PATH) === void 0 || normalise(s.read(MANIFEST_PATH)) !== manifestText) {
276
386
  writes.set(MANIFEST_PATH, manifestText);
@@ -281,10 +391,15 @@ ${CLAUDE_MD_IMPORT}
281
391
  edited: edited.sort(),
282
392
  adopted: adopted.sort(),
283
393
  legacyRemoved: legacyRemoved.sort(),
394
+ skillsAdded: [...after].filter((n) => !before.has(n)).sort(),
395
+ skillsUpdated: [...after].filter((n) => before.has(n) && touched.has(n)).sort(),
396
+ skillsRemoved: [...before].filter((n) => !after.has(n)).sort(),
284
397
  manifest,
285
398
  claudeMd: claudeMd === s.claudeMd ? void 0 : claudeMd,
286
399
  claudeMdRenamed: claudeMdRenamed.sort(([a], [b]) => a.localeCompare(b)),
287
- claudeMdImportAdded
400
+ claudeMdImportAdded,
401
+ claudeMdTableReplaced,
402
+ appReadmeReplaced
288
403
  };
289
404
  }
290
405
  function planChanges(p) {
@@ -295,12 +410,18 @@ function renderReport(p, opts) {
295
410
  const lines = [
296
411
  "### Qore skills",
297
412
  "",
298
- `Synced the managed skills for \`@quatronic/sdk@${p.manifest.sdkVersion}\` (runtime \`${f.runtime}\`, auth \`${f.auth}\`, database \`${f.db ? "yes" : "no"}\`${opts.inferred ? ", inferred from the app \u2014 pin with `qore-skills sync --features`" : ", pinned in the manifest"}).`
413
+ `${opts.check ? "Out of date: `qore-skills sync` would update" : "Synced"} the managed skills for \`@quatronic/sdk@${p.manifest.sdkVersion}\` (runtime \`${f.runtime}\`, auth \`${f.auth}\`, database \`${f.db ? "yes" : "no"}\`${opts.inferred ? ", inferred from the app \u2014 pin with `qore-skills sync --features`" : ", pinned in the manifest"}).`
299
414
  ];
300
415
  const managedWrites = [...p.writes.keys()].filter((r) => r !== MANIFEST_PATH);
301
416
  if (!managedWrites.length && !p.deletes.length && p.claudeMd === void 0) {
302
417
  lines.push("", "No skill content changed.");
303
418
  }
419
+ const skills = (title, names) => {
420
+ if (names.length) lines.push("", `**${title}:** ${names.map((n) => `\`${n}\``).join(", ")}`);
421
+ };
422
+ skills("Skills added", p.skillsAdded);
423
+ skills("Skills updated", p.skillsUpdated);
424
+ skills("Skills removed", p.skillsRemoved);
304
425
  const section = (title, items, note) => {
305
426
  if (!items.length) return;
306
427
  lines.push("", `**${title}** ${note}`, "", ...items.map((i) => `- \`.claude/${i}\``));
@@ -316,9 +437,18 @@ function renderReport(p, opts) {
316
437
  p.legacyRemoved,
317
438
  "(replaced by their `qore-*` names; a local edit to one is in this change's diff):"
318
439
  );
440
+ if (p.appReadmeReplaced) {
441
+ lines.push(
442
+ "",
443
+ "**`.claude/README.md`** replaced: the generator's text said this setup is frozen and yours to edit, which the managed skills no longer are. A change of your own to it is in this change's diff."
444
+ );
445
+ }
319
446
  if (p.claudeMd !== void 0) {
320
447
  lines.push("", "**`CLAUDE.md`:**", "");
321
448
  for (const [from, to] of p.claudeMdRenamed) lines.push(`- Renamed \`${from}\` to \`${to}\`.`);
449
+ if (p.claudeMdTableReplaced) {
450
+ lines.push(`- Replaced the generated skills table with \`${CLAUDE_MD_IMPORT}\`, the index of managed skills.`);
451
+ }
322
452
  if (p.claudeMdImportAdded) lines.push(`- Imports \`${CLAUDE_MD_IMPORT}\`, the index of managed skills.`);
323
453
  }
324
454
  return `${lines.join("\n")}
@@ -454,7 +584,7 @@ function main(argv = process.argv.slice(2)) {
454
584
  return 0;
455
585
  }
456
586
  const { plan: p, inferred } = plan(args.cwd, args.features);
457
- const report = renderReport(p, { inferred });
587
+ const report = renderReport(p, { inferred, check: args.cmd === "check" });
458
588
  if (args.cmd === "check") {
459
589
  const changed = planChanges(p);
460
590
  if (args.json) {